diff --git a/crates/swc/tests/fixture/issues-5xxx/5112/output/index.js b/crates/swc/tests/fixture/issues-5xxx/5112/output/index.js index 366df0f958d5..f79356ad14a6 100644 --- a/crates/swc/tests/fixture/issues-5xxx/5112/output/index.js +++ b/crates/swc/tests/fixture/issues-5xxx/5112/output/index.js @@ -1,7 +1,6 @@ function c(r, n) { - let e = new Uint8Array(4 * r * r); return { - e, + e: new Uint8Array(4 * r * r), s: Math.sqrt(1.25), c: (r - n) / 2 }; diff --git a/crates/swc/tests/fixture/issues-5xxx/5865/output/index.js b/crates/swc/tests/fixture/issues-5xxx/5865/output/index.js index 9ef2045034ab..e9a402e4eac1 100644 --- a/crates/swc/tests/fixture/issues-5xxx/5865/output/index.js +++ b/crates/swc/tests/fixture/issues-5xxx/5865/output/index.js @@ -1 +1 @@ -var a;v=(a=r,b=>{let n=a.map(t=>{if(t)return t.foo});return n}); +var a;v=(a=r,b=>a.map(t=>{if(t)return t.foo})); diff --git a/crates/swc/tests/fixture/issues-7xxx/7241/output/index.js b/crates/swc/tests/fixture/issues-7xxx/7241/output/index.js index 25ef426dc600..7ce862f67fc0 100644 --- a/crates/swc/tests/fixture/issues-7xxx/7241/output/index.js +++ b/crates/swc/tests/fixture/issues-7xxx/7241/output/index.js @@ -1,4 +1 @@ -!function() { - let o = something(); - console.log(o); -}(); +console.log(something()); diff --git a/crates/swc/tests/fixture/issues-7xxx/7287/1/output/index.js b/crates/swc/tests/fixture/issues-7xxx/7287/1/output/index.js index cb48ef9e441c..7850df6277de 100644 --- a/crates/swc/tests/fixture/issues-7xxx/7287/1/output/index.js +++ b/crates/swc/tests/fixture/issues-7xxx/7287/1/output/index.js @@ -1 +1 @@ -!function(){let r=(console.log("REQUIRE"),1);console.log(r)}(); +console.log((console.log("REQUIRE"),1)); diff --git a/crates/swc/tests/fixture/issues-8xxx/8155/1/output/1.js b/crates/swc/tests/fixture/issues-8xxx/8155/1/output/1.js index e9098a2f7960..192a00ae65d2 100644 --- a/crates/swc/tests/fixture/issues-8xxx/8155/1/output/1.js +++ b/crates/swc/tests/fixture/issues-8xxx/8155/1/output/1.js @@ -8,8 +8,7 @@ let someFn = (xx, x, y)=>[ 2, 3 ], goodFunction = (_ref = _async_to_generator(function*() { - let rb = yield getArray(), rc = yield getArray(); - console.log(someFn(1, rb, rc)); + console.log(someFn(1, (yield getArray()), (yield getArray()))); }), function() { return _ref.apply(this, arguments); }), badFunction = (_ref1 = _async_to_generator(function*() { diff --git a/crates/swc/tests/tsc-references/accessorsOverrideProperty2.2.minified.js b/crates/swc/tests/tsc-references/accessorsOverrideProperty2.2.minified.js index 4abf1447a75d..040772357af6 100644 --- a/crates/swc/tests/tsc-references/accessorsOverrideProperty2.2.minified.js +++ b/crates/swc/tests/tsc-references/accessorsOverrideProperty2.2.minified.js @@ -2,12 +2,11 @@ class Base { x = 1; } -const obj = new class extends Base { +console.log(new class extends Base { get x() { return 2; } set x(value) { console.log(`x was set to ${value}`); } -}(); -console.log(obj.x); +}().x); diff --git a/crates/swc/tests/tsc-references/accessorsOverrideProperty8.2.minified.js b/crates/swc/tests/tsc-references/accessorsOverrideProperty8.2.minified.js index 83ec2c2ddcc3..9b43e64680f1 100644 --- a/crates/swc/tests/tsc-references/accessorsOverrideProperty8.2.minified.js +++ b/crates/swc/tests/tsc-references/accessorsOverrideProperty8.2.minified.js @@ -5,12 +5,12 @@ const Base = classWithProperties({ }, y: 'string' }, class { -}), mine = new class extends Base { +}); +new class extends Base { get x() { return !1; } get y() { return 'hi'; } -}(); -mine.x; +}().x; diff --git a/crates/swc/tests/tsc-references/defaultExportInAwaitExpression01.2.minified.js b/crates/swc/tests/tsc-references/defaultExportInAwaitExpression01.2.minified.js index aaaac458f27a..260c6cf2aa0b 100644 --- a/crates/swc/tests/tsc-references/defaultExportInAwaitExpression01.2.minified.js +++ b/crates/swc/tests/tsc-references/defaultExportInAwaitExpression01.2.minified.js @@ -9,9 +9,9 @@ global = this, factory = function(exports1) { return _default; } }); - let x = new Promise((resolve, reject)=>{ + let _default = new Promise((resolve, reject)=>{ resolve({}); - }), _default = x; + }); }, "object" == typeof module && "object" == typeof module.exports ? factory(exports) : "function" == typeof define && define.amd ? define([ "exports" ], factory) : (global = "undefined" != typeof globalThis ? globalThis : global || self) && factory(global.aTs = {}); diff --git a/crates/swc/tests/tsc-references/defaultExportInAwaitExpression02.2.minified.js b/crates/swc/tests/tsc-references/defaultExportInAwaitExpression02.2.minified.js index ba3885a8370c..96e107460d7f 100644 --- a/crates/swc/tests/tsc-references/defaultExportInAwaitExpression02.2.minified.js +++ b/crates/swc/tests/tsc-references/defaultExportInAwaitExpression02.2.minified.js @@ -7,14 +7,14 @@ Object.defineProperty(exports, "__esModule", { return _default; } }); -const x = new Promise((resolve, reject)=>{ +const _default = new Promise((resolve, reject)=>{ resolve({}); -}), _default = x; +}); //// [b.ts] Object.defineProperty(exports, "__esModule", { value: !0 }); -const _async_to_generator = require("@swc/helpers/_/_async_to_generator"), _interop_require_default = require("@swc/helpers/_/_interop_require_default"), _a = _interop_require_default._(require("./a")); +const _async_to_generator = require("@swc/helpers/_/_async_to_generator"), _a = require("@swc/helpers/_/_interop_require_default")._(require("./a")); _async_to_generator._(function*() { yield _a.default; })(); diff --git a/crates/swc/tests/tsc-references/es2020IntlAPIs.2.minified.js b/crates/swc/tests/tsc-references/es2020IntlAPIs.2.minified.js index ee3f1b644cb4..d81718060d6f 100644 --- a/crates/swc/tests/tsc-references/es2020IntlAPIs.2.minified.js +++ b/crates/swc/tests/tsc-references/es2020IntlAPIs.2.minified.js @@ -7,11 +7,9 @@ log("en-US"), log("de-DE"); const rtf1 = new Intl.RelativeTimeFormat('en', { style: 'narrow' }); -console.log(rtf1.format(3, 'quarter')), console.log(rtf1.format(-1, 'day')); -const rtf2 = new Intl.RelativeTimeFormat('es', { +console.log(rtf1.format(3, 'quarter')), console.log(rtf1.format(-1, 'day')), console.log(new Intl.RelativeTimeFormat('es', { numeric: 'auto' -}); -console.log(rtf2.format(2, 'day')); +}).format(2, 'day')); const regionNamesInEnglish = new Intl.DisplayNames([ 'en' ], { diff --git a/crates/swc/tests/tsc-references/es2022SharedMemory.2.minified.js b/crates/swc/tests/tsc-references/es2022SharedMemory.2.minified.js index 069c094dfcfb..ca02ea4aacf4 100644 --- a/crates/swc/tests/tsc-references/es2022SharedMemory.2.minified.js +++ b/crates/swc/tests/tsc-references/es2022SharedMemory.2.minified.js @@ -1,7 +1,7 @@ //// [es2022SharedMemory.ts] const sab = new SharedArrayBuffer(1024 * Int32Array.BYTES_PER_ELEMENT), int32 = new Int32Array(sab), sab64 = new SharedArrayBuffer(1024 * BigInt64Array.BYTES_PER_ELEMENT), int64 = new BigInt64Array(sab64); Atomics.wait(int32, 0, 0); -const { async, value } = Atomics.waitAsync(int32, 0, 0), { async: async64, value: value64 } = Atomics.waitAsync(int64, 0, BigInt(0)), main = async ()=>{ +const { async, value } = Atomics.waitAsync(int32, 0, 0), { async: async64, value: value64 } = Atomics.waitAsync(int64, 0, BigInt(0)); +(async ()=>{ async && await value, async64 && await value64; -}; -main(); +})(); diff --git a/crates/swc/tests/tsc-references/exportAssignmentOfExportNamespaceWithDefault.2.minified.js b/crates/swc/tests/tsc-references/exportAssignmentOfExportNamespaceWithDefault.2.minified.js index 560a82d611f9..354af4e2b5f2 100644 --- a/crates/swc/tests/tsc-references/exportAssignmentOfExportNamespaceWithDefault.2.minified.js +++ b/crates/swc/tests/tsc-references/exportAssignmentOfExportNamespaceWithDefault.2.minified.js @@ -1,7 +1,5 @@ //// [main.ts] Object.defineProperty(exports, "__esModule", { value: !0 -}); -const _interop_require_default = require("@swc/helpers/_/_interop_require_default"), _a = _interop_require_default._(require("a")); -(0, _a.default)(); +}), (0, require("@swc/helpers/_/_interop_require_default")._(require("a")).default)(); //// [external.d.ts] diff --git a/crates/swc/tests/tsc-references/exportsAndImports4-es6.2.minified.js b/crates/swc/tests/tsc-references/exportsAndImports4-es6.2.minified.js index c7459ead67e4..598779514fde 100644 --- a/crates/swc/tests/tsc-references/exportsAndImports4-es6.2.minified.js +++ b/crates/swc/tests/tsc-references/exportsAndImports4-es6.2.minified.js @@ -13,8 +13,8 @@ const _default = "hello"; Object.defineProperty(exports, "__esModule", { value: !0 }); -const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard"), _t1 = _interop_require_wildcard._(require("./t1")), a = require("./t1"); -a.default, _t1.default, _t1.default, _t1.default, _t1.default, _t1.default, _t1.default, _t1.default; +const _t1 = require("@swc/helpers/_/_interop_require_wildcard")._(require("./t1")); +require("./t1").default, _t1.default, _t1.default, _t1.default, _t1.default, _t1.default, _t1.default, _t1.default; //// [t3.ts] Object.defineProperty(exports, "__esModule", { value: !0 @@ -49,5 +49,5 @@ Object.defineProperty(exports, "__esModule", { return _t1.default; } }); -const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard"), _t1 = _interop_require_wildcard._(require("./t1")), a = require("./t1"); +const _t1 = require("@swc/helpers/_/_interop_require_wildcard")._(require("./t1")), a = require("./t1"); a.default, _t1.default, _t1.default, _t1.default, _t1.default, _t1.default, _t1.default, _t1.default; diff --git a/crates/swc/tests/tsc-references/importAssertion2(module=commonjs).2.minified.js b/crates/swc/tests/tsc-references/importAssertion2(module=commonjs).2.minified.js index c4af5b38f0cc..b6486165020c 100644 --- a/crates/swc/tests/tsc-references/importAssertion2(module=commonjs).2.minified.js +++ b/crates/swc/tests/tsc-references/importAssertion2(module=commonjs).2.minified.js @@ -35,7 +35,7 @@ Object.defineProperty(exports, "__esModule", { return _0; } }); -const _export_star = require("@swc/helpers/_/_export_star"), _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard"), _0 = _interop_require_wildcard._(_export_star._(require("./0"), exports)); +const _export_star = require("@swc/helpers/_/_export_star"), _0 = require("@swc/helpers/_/_interop_require_wildcard")._(_export_star._(require("./0"), exports)); //// [2.ts] Object.defineProperty(exports, "__esModule", { value: !0 diff --git a/crates/swc/tests/tsc-references/importCallExpression5ES2020.2.minified.js b/crates/swc/tests/tsc-references/importCallExpression5ES2020.2.minified.js index 178a3e3073d2..33769ef13d08 100644 --- a/crates/swc/tests/tsc-references/importCallExpression5ES2020.2.minified.js +++ b/crates/swc/tests/tsc-references/importCallExpression5ES2020.2.minified.js @@ -12,5 +12,4 @@ export function backup() { return "backup"; } //// [2.ts] -const specify = bar() ? "./0" : void 0; -import(specify), import(void 0), import(bar() ? "./1" : null), import(null); +import(bar() ? "./0" : void 0), import(void 0), import(bar() ? "./1" : null), import(null); diff --git a/crates/swc/tests/tsc-references/importCallExpression6ES2020.2.minified.js b/crates/swc/tests/tsc-references/importCallExpression6ES2020.2.minified.js index 178a3e3073d2..33769ef13d08 100644 --- a/crates/swc/tests/tsc-references/importCallExpression6ES2020.2.minified.js +++ b/crates/swc/tests/tsc-references/importCallExpression6ES2020.2.minified.js @@ -12,5 +12,4 @@ export function backup() { return "backup"; } //// [2.ts] -const specify = bar() ? "./0" : void 0; -import(specify), import(void 0), import(bar() ? "./1" : null), import(null); +import(bar() ? "./0" : void 0), import(void 0), import(bar() ? "./1" : null), import(null); diff --git a/crates/swc/tests/tsc-references/intersectionsAndEmptyObjects.2.minified.js b/crates/swc/tests/tsc-references/intersectionsAndEmptyObjects.2.minified.js index ebc1c2da7c25..72b53acda779 100644 --- a/crates/swc/tests/tsc-references/intersectionsAndEmptyObjects.2.minified.js +++ b/crates/swc/tests/tsc-references/intersectionsAndEmptyObjects.2.minified.js @@ -3,19 +3,11 @@ Object.defineProperty(exports, "__esModule", { value: !0 }); const _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard"), intersectDictionaries = (d1, d2)=>Object.assign({}, d1, d2), testDictionary = (_value)=>{}, d1 = {}; -testDictionary(d1); -const d2 = intersectDictionaries(d1, d1); -testDictionary(d2); +testDictionary(d1), testDictionary(intersectDictionaries(d1, d1)); const d3 = { s: '' }; -testDictionary(d3); -const d4 = intersectDictionaries(d1, d3); -testDictionary(d4); -const d5 = intersectDictionaries(d3, d1); -testDictionary(d5); -const d6 = intersectDictionaries(d3, d3); -testDictionary(d6), mock(Promise.resolve().then(()=>_interop_require_wildcard._(require("./ex")))); +testDictionary(d3), testDictionary(intersectDictionaries(d1, d3)), testDictionary(intersectDictionaries(d3, d1)), testDictionary(intersectDictionaries(d3, d3)), mock(Promise.resolve().then(()=>_interop_require_wildcard._(require("./ex")))); //// [ex.d.ts] Object.defineProperty(exports, "__esModule", { value: !0 diff --git a/crates/swc/tests/tsc-references/mixinAbstractClasses.2.2.minified.js b/crates/swc/tests/tsc-references/mixinAbstractClasses.2.2.minified.js index ded8b89b96e0..cd41d47be044 100644 --- a/crates/swc/tests/tsc-references/mixinAbstractClasses.2.2.minified.js +++ b/crates/swc/tests/tsc-references/mixinAbstractClasses.2.2.minified.js @@ -1,7 +1,6 @@ //// [mixinAbstractClasses.2.ts] var baseClass; -const MixedBase = (baseClass = class { +new (baseClass = class { }, class extends baseClass { mixinMethod() {} -}); -new MixedBase(); +})(); diff --git a/crates/swc/tests/tsc-references/numberFormatCurrencySignResolved.2.minified.js b/crates/swc/tests/tsc-references/numberFormatCurrencySignResolved.2.minified.js index 5ffc5c61f4f1..83f779a58e29 100644 --- a/crates/swc/tests/tsc-references/numberFormatCurrencySignResolved.2.minified.js +++ b/crates/swc/tests/tsc-references/numberFormatCurrencySignResolved.2.minified.js @@ -1,7 +1,6 @@ //// [numberFormatCurrencySignResolved.ts] -const options = new Intl.NumberFormat('en-NZ', { +new Intl.NumberFormat('en-NZ', { style: 'currency', currency: 'NZD', currencySign: 'accounting' -}).resolvedOptions(); -options.currencySign; +}).resolvedOptions().currencySign; diff --git a/crates/swc/tests/tsc-references/privateNameMethodAsync.2.minified.js b/crates/swc/tests/tsc-references/privateNameMethodAsync.2.minified.js index 28c0690bd3d8..d6f3aff83622 100644 --- a/crates/swc/tests/tsc-references/privateNameMethodAsync.2.minified.js +++ b/crates/swc/tests/tsc-references/privateNameMethodAsync.2.minified.js @@ -2,15 +2,6 @@ var _bar, _baz, _qux; import { _ as _class_private_method_get } from "@swc/helpers/_/_class_private_method_get"; import { _ as _class_private_method_init } from "@swc/helpers/_/_class_private_method_init"; -let C = (_bar = new WeakSet(), _baz = new WeakSet(), _qux = new WeakSet(), class { - async foo() { - let b = await _class_private_method_get(this, _bar, bar).call(this); - return b + (_class_private_method_get(this, _baz, baz).call(this).next().value || 0) + ((await _class_private_method_get(this, _qux, qux).call(this).next()).value || 0); - } - constructor(){ - _class_private_method_init(this, _bar), _class_private_method_init(this, _baz), _class_private_method_init(this, _qux); - } -}); async function bar() { return await Promise.resolve(42); } @@ -20,4 +11,11 @@ function* baz() { async function* qux() { yield await Promise.resolve(42); } -new C().foo().then(console.log); +new (_bar = new WeakSet(), _baz = new WeakSet(), _qux = new WeakSet(), class { + async foo() { + return await _class_private_method_get(this, _bar, bar).call(this) + (_class_private_method_get(this, _baz, baz).call(this).next().value || 0) + ((await _class_private_method_get(this, _qux, qux).call(this).next()).value || 0); + } + constructor(){ + _class_private_method_init(this, _bar), _class_private_method_init(this, _baz), _class_private_method_init(this, _qux); + } +})().foo().then(console.log); diff --git a/crates/swc/tests/tsc-references/privateNameReadonly.2.minified.js b/crates/swc/tests/tsc-references/privateNameReadonly.2.minified.js index 6efdf0b8bddb..0d9768581ee5 100644 --- a/crates/swc/tests/tsc-references/privateNameReadonly.2.minified.js +++ b/crates/swc/tests/tsc-references/privateNameReadonly.2.minified.js @@ -2,12 +2,11 @@ var _bar; import { _ as _class_private_method_init } from "@swc/helpers/_/_class_private_method_init"; import { _ as _read_only_error } from "@swc/helpers/_/_read_only_error"; -let C = (_bar = new WeakSet(), class { +console.log(new (_bar = new WeakSet(), class { foo() { console.log("should log this then throw"), _read_only_error("#bar"); } constructor(){ _class_private_method_init(this, _bar); } -}); -console.log(new C().foo()); +})().foo()); diff --git a/crates/swc/tests/tsc-references/privateNameSetterNoGetter.2.minified.js b/crates/swc/tests/tsc-references/privateNameSetterNoGetter.2.minified.js index def7c93cf59d..f41a9d9a202d 100644 --- a/crates/swc/tests/tsc-references/privateNameSetterNoGetter.2.minified.js +++ b/crates/swc/tests/tsc-references/privateNameSetterNoGetter.2.minified.js @@ -3,7 +3,8 @@ var _x; import { _ as _class_private_field_init } from "@swc/helpers/_/_class_private_field_init"; import { _ as _class_private_field_set } from "@swc/helpers/_/_class_private_field_set"; import { _ as _write_only_error } from "@swc/helpers/_/_write_only_error"; -let C = (_x = new WeakMap(), class { +function set_x(x) {} +console.log(new (_x = new WeakMap(), class { m() { _class_private_field_set(this, _x, _write_only_error("#x") + 2); } @@ -13,6 +14,4 @@ let C = (_x = new WeakMap(), class { set: set_x }); } -}); -function set_x(x) {} -console.log(new C().m()); +})().m()); diff --git a/crates/swc/tests/tsc-references/privateNameStaticAccessorsCallExpression.2.minified.js b/crates/swc/tests/tsc-references/privateNameStaticAccessorsCallExpression.2.minified.js index 6b42ab520844..1f81e7ddbf7e 100644 --- a/crates/swc/tests/tsc-references/privateNameStaticAccessorsCallExpression.2.minified.js +++ b/crates/swc/tests/tsc-references/privateNameStaticAccessorsCallExpression.2.minified.js @@ -3,9 +3,7 @@ import { _ as _class_static_private_field_spec_get } from "@swc/helpers/_/_class import { _ as _class_static_private_field_spec_set } from "@swc/helpers/_/_class_static_private_field_spec_set"; class A { static test() { - _class_static_private_field_spec_get(this, A, _fieldFunc).call(A); - let func = _class_static_private_field_spec_get(this, A, _fieldFunc); - func(), new (_class_static_private_field_spec_get(this, A, _fieldFunc))(); + _class_static_private_field_spec_get(this, A, _fieldFunc).call(A), _class_static_private_field_spec_get(this, A, _fieldFunc)(), new (_class_static_private_field_spec_get(this, A, _fieldFunc))(); let arr = [ 1, 2 diff --git a/crates/swc/tests/tsc-references/privateNameStaticMethodCallExpression.2.minified.js b/crates/swc/tests/tsc-references/privateNameStaticMethodCallExpression.2.minified.js index fdfb2ff37095..db697e2368a3 100644 --- a/crates/swc/tests/tsc-references/privateNameStaticMethodCallExpression.2.minified.js +++ b/crates/swc/tests/tsc-references/privateNameStaticMethodCallExpression.2.minified.js @@ -2,9 +2,7 @@ import { _ as _class_static_private_method_get } from "@swc/helpers/_/_class_static_private_method_get"; class AA { test() { - _class_static_private_method_get(AA, AA, method).call(AA); - let func = _class_static_private_method_get(AA, AA, method); - func(), new (_class_static_private_method_get(AA, AA, method))(); + _class_static_private_method_get(AA, AA, method).call(AA), _class_static_private_method_get(AA, AA, method)(), new (_class_static_private_method_get(AA, AA, method))(); let arr = [ 1, 2 diff --git a/crates/swc/tests/tsc-references/propertyOverridesAccessors2.2.minified.js b/crates/swc/tests/tsc-references/propertyOverridesAccessors2.2.minified.js index 3c559f30c8ba..572dd6ce8cf7 100644 --- a/crates/swc/tests/tsc-references/propertyOverridesAccessors2.2.minified.js +++ b/crates/swc/tests/tsc-references/propertyOverridesAccessors2.2.minified.js @@ -7,7 +7,6 @@ class Base { console.log(`x was set to ${value}`); } } -const obj = new class extends Base { +console.log(new class extends Base { x = 1; -}(); -console.log(obj.x); +}().x); diff --git a/crates/swc/tests/tsc-references/propertyOverridesAccessors3.2.minified.js b/crates/swc/tests/tsc-references/propertyOverridesAccessors3.2.minified.js index eb90caf85749..25b496f8aaaa 100644 --- a/crates/swc/tests/tsc-references/propertyOverridesAccessors3.2.minified.js +++ b/crates/swc/tests/tsc-references/propertyOverridesAccessors3.2.minified.js @@ -11,9 +11,6 @@ class Animal { console.log(this._sound); } } -const a = new Animal; -a.makeSound(); -const lion = new class extends Animal { +(new Animal).makeSound(), (new class extends Animal { sound = 'RAWR!'; -}; -lion.makeSound(); +}).makeSound(); diff --git a/crates/swc_ecma_minifier/src/compress/optimize/sequences.rs b/crates/swc_ecma_minifier/src/compress/optimize/sequences.rs index 5935afbc9628..946714199bdb 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/sequences.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/sequences.rs @@ -558,15 +558,7 @@ impl Optimizer<'_> { ) -> Option>> { Some(match s { Stmt::Expr(e) => vec![Mergable::Expr(&mut e.expr)], - Stmt::Decl(Decl::Var(v)) - if matches!( - &**v, - VarDecl { - kind: VarDeclKind::Var | VarDeclKind::Let, - .. - } - ) => - { + Stmt::Decl(Decl::Var(v)) => { if options.reduce_vars || options.collapse_vars { v.decls.iter_mut().map(Mergable::Var).collect() } else { @@ -1669,7 +1661,7 @@ impl Optimizer<'_> { Mergable::FnDecl(a) => idents_used_by_ignoring_nested(&**a), Mergable::Drop => return Ok(false), }; - if obj_ids.intersection(&a_ids).next().is_some() { + if !obj_ids.is_disjoint(&a_ids) { return Ok(false); } @@ -2319,61 +2311,67 @@ impl Optimizer<'_> { } } - macro_rules! take_a { - ($force_drop:expr, $drop_op:expr) => { - match a { - Mergable::Var(a) => { - if self.options.unused { - if let Some(usage) = self.data.vars.get(&left_id.to_id()) { - // We are eliminating one usage, so we use 1 instead of - // 0 - if !$force_drop && usage.usage_count == 1 && !usage.reassigned { - report_change!("sequences: Dropping inlined variable"); - a.name.take(); - } + let take_a = |a: &mut Mergable, force_drop: bool, drop_op| { + match a { + Mergable::Var(a) => { + if self.options.unused { + if let Some(usage) = self.data.vars.get(&left_id.to_id()) { + // We are eliminating one usage, so we use 1 instead of + // 0 + if !force_drop && usage.usage_count == 1 && !usage.reassigned { + report_change!("sequences: Dropping inlined variable"); + a.name.take(); } } - - if can_take_init || $force_drop { - a.init.take() - } else { - a.init.clone() - } - .unwrap_or_else(|| undefined(DUMMY_SP)) } - Mergable::Expr(a) => { - if can_remove || $force_drop { - if let Expr::Assign(e) = a { - if e.op == op!("=") || $drop_op { - report_change!( - "sequences: Dropping assignment as we are going to drop \ - the variable declaration. ({})", - left_id - ); - **a = *e.right.take(); - } + if can_take_init || force_drop { + let init = a.init.take(); + + if let Some(usage) = self.data.vars.get(&left_id.to_id()) { + if usage.var_kind == Some(VarDeclKind::Const) { + a.init = Some(undefined(DUMMY_SP)); } } - Box::new(a.take()) + init + } else { + a.init.clone() + } + .unwrap_or_else(|| undefined(DUMMY_SP)) + } + Mergable::Expr(a) => { + if can_remove || force_drop { + if let Expr::Assign(e) = a { + if e.op == op!("=") || drop_op { + report_change!( + "sequences: Dropping assignment as we are going to drop the \ + variable declaration. ({})", + left_id + ); + + **a = *e.right.take(); + } + } } - Mergable::FnDecl(a) => { - // We can inline a function declaration as a function expression. + Box::new(a.take()) + } - Box::new(Expr::Fn(FnExpr { - ident: Some(a.ident.take()), - function: a.function.take(), - })) - } + Mergable::FnDecl(a) => { + // We can inline a function declaration as a function expression. - Mergable::Drop => { - unreachable!() - } + Box::new(Expr::Fn(FnExpr { + ident: Some(a.ident.take()), + function: a.function.take(), + })) } - }; - } + + Mergable::Drop => { + unreachable!() + } + } + }; // x = 1, x += 2 => x = 3 match b { @@ -2383,7 +2381,7 @@ impl Optimizer<'_> { report_change!("sequences: Merged assignment into another assignment"); self.changed = true; - let mut a_expr = take_a!(true, false); + let mut a_expr = take_a(a, true, false); let a_expr = self.ignore_return_value(&mut a_expr); if let Some(a) = a_expr { @@ -2416,7 +2414,7 @@ impl Optimizer<'_> { b.op = a_op; - let to = take_a!(true, true); + let to = take_a(a, true, true); b.right = Box::new(Expr::Bin(BinExpr { span: DUMMY_SP, @@ -2464,7 +2462,7 @@ impl Optimizer<'_> { left_id.span.ctxt ); - let to = take_a!(false, false); + let to = take_a(a, false, false); replace_id_with_expr(b, left_id.to_id(), to); diff --git a/crates/swc_ecma_minifier/tests/benches-full/d3.js b/crates/swc_ecma_minifier/tests/benches-full/d3.js index a85aa22e2f31..6ee078a54260 100644 --- a/crates/swc_ecma_minifier/tests/benches-full/d3.js +++ b/crates/swc_ecma_minifier/tests/benches-full/d3.js @@ -1381,7 +1381,7 @@ return (1 === (a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a))) ? "hsl(" : "hsla(") + (this.h || 0) + ", " + 100 * (this.s || 0) + "%, " + 100 * (this.l || 0) + "%" + (1 === a ? ")" : ", " + a + ")"); } })); - const radians = Math.PI / 180, degrees = 180 / Math.PI, t0 = 4 / 29, t1 = 6 / 29, t2 = 3 * t1 * t1, t3 = t1 * t1 * t1; + const radians = Math.PI / 180, degrees = 180 / Math.PI, t0 = 4 / 29, t1 = 6 / 29, t2 = 3 * (6 / 29) * (6 / 29), t3 = 6 / 29 * (6 / 29) * (6 / 29); function labConvert(o) { if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity); if (o instanceof Hcl) return hcl2lab(o); @@ -2727,29 +2727,23 @@ const x0 = x; if (directed) { const subgroupIndex = range(~n + 1, n).filter((j)=>j < 0 ? matrix[~j * n + i] : matrix[i * n + j]); - for (const j of (sortSubgroups && subgroupIndex.sort((a, b)=>sortSubgroups(a < 0 ? -matrix[~a * n + i] : matrix[i * n + a], b < 0 ? -matrix[~b * n + i] : matrix[i * n + b])), subgroupIndex))if (j < 0) { - const chord = chords[~j * n + i] || (chords[~j * n + i] = { - source: null, - target: null - }); - chord.target = { - index: i, - startAngle: x, - endAngle: x += matrix[~j * n + i] * k, - value: matrix[~j * n + i] - }; - } else { - const chord = chords[i * n + j] || (chords[i * n + j] = { - source: null, - target: null - }); - chord.source = { - index: i, - startAngle: x, - endAngle: x += matrix[i * n + j] * k, - value: matrix[i * n + j] - }; - } + for (const j of (sortSubgroups && subgroupIndex.sort((a, b)=>sortSubgroups(a < 0 ? -matrix[~a * n + i] : matrix[i * n + a], b < 0 ? -matrix[~b * n + i] : matrix[i * n + b])), subgroupIndex))j < 0 ? (chords[~j * n + i] || (chords[~j * n + i] = { + source: null, + target: null + })).target = { + index: i, + startAngle: x, + endAngle: x += matrix[~j * n + i] * k, + value: matrix[~j * n + i] + } : (chords[i * n + j] || (chords[i * n + j] = { + source: null, + target: null + })).source = { + index: i, + startAngle: x, + endAngle: x += matrix[i * n + j] * k, + value: matrix[i * n + j] + }; groups[i] = { index: i, startAngle: x0, @@ -3345,11 +3339,11 @@ a = EDGE_STACK[--i]; continue; } - const b0 = b - b % 3, al = a0 + (a + 1) % 3, bl = b0 + (b + 2) % 3, p0 = triangles[ar], pr = triangles[a], pl = triangles[al], p1 = triangles[bl], illegal = function(ax, ay, bx, by, cx, cy, px, py) { + const b0 = b - b % 3, al = a0 + (a + 1) % 3, bl = b0 + (b + 2) % 3, p0 = triangles[ar], pr = triangles[a], pl = triangles[al], p1 = triangles[bl]; + if (function(ax, ay, bx, by, cx, cy, px, py) { const dx = ax - px, dy = ay - py, ex = bx - px, ey = by - py, fx = cx - px, fy = cy - py, bp = ex * ex + ey * ey, cp = fx * fx + fy * fy; return dx * (ey * cp - bp * fy) - dy * (ex * cp - bp * fx) + (dx * dx + dy * dy) * (ex * fy - ey * fx) < 0; - }(coords[2 * p0], coords[2 * p0 + 1], coords[2 * pr], coords[2 * pr + 1], coords[2 * pl], coords[2 * pl + 1], coords[2 * p1], coords[2 * p1 + 1]); - if (illegal) { + }(coords[2 * p0], coords[2 * p0 + 1], coords[2 * pr], coords[2 * pr + 1], coords[2 * pl], coords[2 * pl + 1], coords[2 * p1], coords[2 * p1 + 1])) { triangles[a] = p1, triangles[b] = p0; const hbl = halfedges[bl]; if (-1 === hbl) { @@ -3389,8 +3383,7 @@ return Math.abs(l - r) >= 3.3306690738754716e-16 * Math.abs(l + r) ? l - r : 0; } function orient(rx, ry, qx, qy, px, py) { - const sign = orientIfSure(px, py, rx, ry, qx, qy) || orientIfSure(rx, ry, qx, qy, px, py) || orientIfSure(qx, qy, px, py, rx, ry); - return sign < 0; + return 0 > (orientIfSure(px, py, rx, ry, qx, qy) || orientIfSure(rx, ry, qx, qy, px, py) || orientIfSure(qx, qy, px, py, rx, ry)); } function quicksort(ids, dists, left, right) { if (right - left <= 20) for(let i = left + 1; i <= right; i++){ @@ -3439,8 +3432,8 @@ this._ += `L${this._x1 = +x},${this._y1 = +y}`; } arc(x, y, r) { - x = +x, y = +y, r = +r; - const x0 = x + r, y0 = y; + x = +x, y = +y; + const x0 = x + (r = +r), y0 = y; if (r < 0) throw Error("negative radius"); null === this._x1 ? this._ += `M${x0},${y0}` : (Math.abs(this._x1 - x0) > 1e-6 || Math.abs(this._y1 - y0) > 1e-6) && (this._ += "L" + x0 + "," + y0), r && (this._ += `A${r},${r},0,1,1,${x - r},${y}A${r},${r},0,1,1,${this._x1 = x0},${this._y1 = y0}`); } @@ -3515,8 +3508,8 @@ } let h0, h1 = hull[hull.length - 1]; for(let i = 0; i < hull.length; ++i){ - h0 = h1, h1 = hull[i]; - const t = 2 * Math.floor(inedges[h1] / 3), x = circumcenters[t], y = circumcenters[t + 1], v = 4 * h0, p = this._project(x, y, vectors[v + 2], vectors[v + 3]); + h0 = h1; + const t = 2 * Math.floor(inedges[h1 = hull[i]] / 3), x = circumcenters[t], y = circumcenters[t + 1], v = 4 * h0, p = this._project(x, y, vectors[v + 2], vectors[v + 3]); p && this._renderSegment(x, y, p[0], p[1], context); } return buffer && buffer.value(); @@ -3755,8 +3748,8 @@ if (d.hull && d.hull.length > 2 && function(d) { const { triangles, coords } = d; for(let i = 0; i < triangles.length; i += 3){ - const a = 2 * triangles[i], b = 2 * triangles[i + 1], c = 2 * triangles[i + 2], cross = (coords[c] - coords[a]) * (coords[b + 1] - coords[a + 1]) - (coords[b] - coords[a]) * (coords[c + 1] - coords[a + 1]); - if (cross > 1e-10) return !1; + const a = 2 * triangles[i], b = 2 * triangles[i + 1], c = 2 * triangles[i + 2]; + if ((coords[c] - coords[a]) * (coords[b + 1] - coords[a + 1]) - (coords[b] - coords[a]) * (coords[c + 1] - coords[a + 1]) > 1e-10) return !1; } return !0; }(d)) { @@ -9141,9 +9134,7 @@ return select(creator(name).call(document.documentElement)); }, exports1.creator = creator, exports1.cross = function(...values) { var reduce; - const reduce1 = "function" == typeof values[values.length - 1] && (reduce = values.pop(), (values)=>reduce(...values)); - values = values.map(arrayify); - const lengths = values.map(length), j = values.length - 1, index = Array(j + 1).fill(0), product = []; + const reduce1 = "function" == typeof values[values.length - 1] && (reduce = values.pop(), (values)=>reduce(...values)), lengths = (values = values.map(arrayify)).map(length), j = values.length - 1, index = Array(j + 1).fill(0), product = []; if (j < 0 || lengths.some(empty)) return product; for(;;){ product.push(index.map((j, i)=>values[i][j])); diff --git a/crates/swc_ecma_minifier/tests/benches-full/terser.js b/crates/swc_ecma_minifier/tests/benches-full/terser.js index db7d613d15b5..11ecffd2187e 100644 --- a/crates/swc_ecma_minifier/tests/benches-full/terser.js +++ b/crates/swc_ecma_minifier/tests/benches-full/terser.js @@ -481,14 +481,7 @@ case 13: if ("\n" == peek()) return next(!0, in_string), ""; } - if (is_octal(ch1)) { - if (template_string && strict_hex) { - const represents_null_character = "0" === ch1 && !is_octal(peek()); - represents_null_character || parse_error("Octal escape sequences are not allowed in template strings"); - } - return ch = ch1, ((p = peek()) >= "0" && p <= "7" && (ch += next(!0))[0] <= "3" && (p = peek()) >= "0" && p <= "7" && (ch += next(!0)), "0" === ch) ? "\0" : (ch.length > 0 && next_token.has_directive("use strict") && strict_hex && parse_error("Legacy octal escape sequences are not allowed in strict mode"), String.fromCharCode(parseInt(ch, 8))); - } - return ch1; + return is_octal(ch1) ? (template_string && strict_hex && !("0" === ch1 && !is_octal(peek())) && parse_error("Octal escape sequences are not allowed in template strings"), ch = ch1, ((p = peek()) >= "0" && p <= "7" && (ch += next(!0))[0] <= "3" && (p = peek()) >= "0" && p <= "7" && (ch += next(!0)), "0" === ch) ? "\0" : (ch.length > 0 && next_token.has_directive("use strict") && strict_hex && parse_error("Legacy octal escape sequences are not allowed in strict mode"), String.fromCharCode(parseInt(ch, 8)))) : ch1; } function hex_bytes(n, strict_hex) { for(var num = 0; n > 0; --n){ @@ -565,8 +558,7 @@ else if ("]" == ch && in_class) in_class = !1, source += ch; else if ("/" != ch || in_class) "\\" == ch ? prev_backslash = !0 : source += ch; else break; - const flags = read_name(); - return token("regexp", "/" + source + "/" + flags); + return token("regexp", "/" + source + "/" + read_name()); }); function read_operator(prefix) { return token("operator", function grow(op) { @@ -625,8 +617,7 @@ return (next(), ">" === peek()) ? (next(), token("arrow", "=>")) : read_operator("="); case 63: if (!function() { - const must_be_dot = 46 === S.text.charCodeAt(S.pos + 1); - if (!must_be_dot) return !1; + if (46 !== S.text.charCodeAt(S.pos + 1)) return !1; const cannot_be_digit = S.text.charCodeAt(S.pos + 2); return cannot_be_digit < 48 || cannot_be_digit > 57; }()) break; @@ -1510,43 +1501,30 @@ var is_async = !1, is_static = !1, is_generator = !1, is_private = !1, accessor_type = null; is_class && "static" === name && is_not_method_start() && (is_static = !0, name = as_property_name()), "async" === name && is_not_method_start() && (is_async = !0, name = as_property_name()), "operator" === prev().type && "*" === prev().value && (is_generator = !0, name = as_property_name()), ("get" === name || "set" === name) && is_not_method_start() && (accessor_type = name, name = as_property_name()), "privatename" === prev().type && (is_private = !0); const property_token = prev(); - if (null != accessor_type) { - if (is_private) { - const AccessorClass = "get" === accessor_type ? AST_PrivateGetter : AST_PrivateSetter; - return new AccessorClass({ - start, - static: is_static, - key: get_symbol_ast(name), - value: create_accessor(), - end: prev() - }); - } - { - const AccessorClass = "get" === accessor_type ? AST_ObjectGetter : AST_ObjectSetter; - return new AccessorClass({ - start, - static: is_static, - key: name = get_symbol_ast(name), - quote: name instanceof AST_SymbolMethod ? property_token.quote : void 0, - value: create_accessor(), - end: prev() - }); - } - } - if (is("punc", "(")) { - name = get_symbol_ast(name); - const AST_MethodVariant = is_private ? AST_PrivateMethod : AST_ConciseMethod; - return 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 : void 0, - value: create_accessor(is_generator, is_async), - end: prev() - }); - } + if (null != accessor_type) return is_private ? new ("get" === accessor_type ? AST_PrivateGetter : AST_PrivateSetter)({ + start, + static: is_static, + key: get_symbol_ast(name), + value: create_accessor(), + end: prev() + }) : new ("get" === accessor_type ? AST_ObjectGetter : AST_ObjectSetter)({ + start, + static: is_static, + key: name = get_symbol_ast(name), + quote: name instanceof AST_SymbolMethod ? property_token.quote : void 0, + value: create_accessor(), + end: prev() + }); + if (is("punc", "(")) return new (is_private ? AST_PrivateMethod : AST_ConciseMethod)({ + start: start, + static: is_static, + is_generator: is_generator, + async: is_async, + key: name = get_symbol_ast(name), + quote: name instanceof AST_SymbolMethod ? property_token.quote : void 0, + value: create_accessor(is_generator, is_async), + end: prev() + }); if (is_class) { const key = get_symbol_ast(name, AST_SymbolClassProperty), quote = key instanceof AST_SymbolClassProperty ? property_token.quote : void 0, AST_ClassPropertyVariant = is_private ? AST_ClassPrivateProperty : AST_ClassProperty; if (is("operator", "=")) return next(), new AST_ClassPropertyVariant({ @@ -1683,17 +1661,13 @@ } var subscripts = function(expr, allow_calls, is_chain) { var start = expr.start; - if (is("punc", ".")) { - next(); - const AST_DotVariant = is("privatename") ? AST_DotHash : AST_Dot; - return subscripts(new AST_DotVariant({ - start: start, - expression: expr, - optional: !1, - property: as_name(), - end: prev() - }), allow_calls, is_chain); - } + if (is("punc", ".")) return next(), subscripts(new (is("privatename") ? AST_DotHash : AST_Dot)({ + start: start, + expression: expr, + optional: !1, + property: as_name(), + end: prev() + }), allow_calls, is_chain); if (is("punc", "[")) { next(); var prop = expression(!0); @@ -1728,16 +1702,14 @@ end: prev() }); annotate(call), chain_contents = subscripts(call, !0, !0); - } else if (is("name") || is("privatename")) { - const AST_DotVariant = is("privatename") ? AST_DotHash : AST_Dot; - chain_contents = subscripts(new AST_DotVariant({ - start, - expression: expr, - optional: !0, - property: as_name(), - end: prev() - }), allow_calls, !0); - } else if (is("punc", "[")) { + } else if (is("name") || is("privatename")) chain_contents = subscripts(new (is("privatename") ? AST_DotHash : AST_Dot)({ + start, + expression: expr, + optional: !0, + property: as_name(), + end: prev() + }), allow_calls, !0); + else if (is("punc", "[")) { next(); const property = expression(!0); expect("]"), chain_contents = subscripts(new AST_Sub({ @@ -3141,9 +3113,9 @@ walk_abort: walk_abort, walk_body: walk_body, walk_parent: walk_parent, - _INLINE: _INLINE, - _NOINLINE: _NOINLINE, - _PURE: _PURE + _INLINE: 0b00000010, + _NOINLINE: 0b00000100, + _PURE: 0b00000001 }); function def_transform(node, descend) { node.DEFMETHOD("transform", function(tw, in_list) { @@ -3897,14 +3869,12 @@ argument: to_moz(M.expression) }; }), def_to_moz(AST_Binary, function(M) { - if ("=" == M.operator && to_moz_in_destructuring()) return { + return "=" == M.operator && to_moz_in_destructuring() ? { type: "AssignmentPattern", left: to_moz(M.left), right: to_moz(M.right) - }; - const type = "&&" == M.operator || "||" == M.operator || "??" === M.operator ? "LogicalExpression" : "BinaryExpression"; - return { - type, + } : { + type: "&&" == M.operator || "||" == M.operator || "??" === M.operator ? "LogicalExpression" : "BinaryExpression", left: to_moz(M.left), operator: M.operator, right: to_moz(M.right) @@ -3932,21 +3902,17 @@ name: M.key }); var string_or_num = "string" == typeof M.key || "number" == typeof M.key, computed = !string_or_num && (!(M.key instanceof AST_Symbol) || M.key instanceof AST_SymbolRef); - if (M instanceof AST_ObjectKeyVal ? (kind = "init", computed = !string_or_num) : M instanceof AST_ObjectGetter ? kind = "get" : M instanceof AST_ObjectSetter && (kind = "set"), M instanceof AST_PrivateGetter || M instanceof AST_PrivateSetter) { - const kind = M instanceof AST_PrivateGetter ? "get" : "set"; - return { - type: "MethodDefinition", - computed: !1, - kind: kind, - static: M.static, - key: { - type: "PrivateIdentifier", - name: M.key.name - }, - value: to_moz(M.value) - }; - } - return M instanceof AST_ClassPrivateProperty ? { + return (M instanceof AST_ObjectKeyVal ? (kind = "init", computed = !string_or_num) : M instanceof AST_ObjectGetter ? kind = "get" : M instanceof AST_ObjectSetter && (kind = "set"), M instanceof AST_PrivateGetter || M instanceof AST_PrivateSetter) ? { + type: "MethodDefinition", + computed: !1, + kind: M instanceof AST_PrivateGetter ? "get" : "set", + static: M.static, + key: { + type: "PrivateIdentifier", + name: M.key.name + }, + value: to_moz(M.value) + } : M instanceof AST_ClassPrivateProperty ? { type: "PropertyDefinition", key: { type: "PrivateIdentifier", @@ -4978,14 +4944,11 @@ if (!shallow_cmp(node_1, node_2) || (node_1._children_backwards(walk_1_push), node_2._children_backwards(walk_2_push), walk_1_state.length !== walk_2_state.length)) return !1; } return 0 == walk_1_state.length && 0 == walk_2_state.length; - }, mkshallow = (props)=>{ - const comparisons = Object.keys(props).map((key)=>{ + }, mkshallow = (props)=>Function("other", "return " + Object.keys(props).map((key)=>{ if ("eq" === props[key]) return `this.${key} === other.${key}`; if ("exist" === props[key]) return `(this.${key} == null ? other.${key} == null : this.${key} === other.${key})`; throw Error(`mkshallow: Unexpected instruction: ${props[key]}`); - }).join(" && "); - return Function("other", "return " + comparisons); - }, pass_through = ()=>!0; + }).join(" && ")), pass_through = ()=>!0; AST_Node.prototype.shallow_cmp = function() { throw Error("did not find a shallow_cmp function for " + this.constructor.name); }, AST_Debugger.prototype.shallow_cmp = pass_through, AST_Directive.prototype.shallow_cmp = mkshallow({ @@ -5090,8 +5053,8 @@ var m = nth_identifier.get(++scope.cname); if (!(ALL_RESERVED_WORDS.has(m) || options.reserved.has(m)) && !(unmangleable_names && unmangleable_names.has(m))) { for(let i = ext.length; --i >= 0;){ - const def = ext[i], name = def.mangled_name || def.unmangleable(options) && def.name; - if (m == name) continue out; + const def = ext[i]; + if (m == (def.mangled_name || def.unmangleable(options) && def.name)) continue out; } return m; } @@ -5169,9 +5132,7 @@ (exported instanceof AST_Defun || exported instanceof AST_DefClass) && node.is_default && (def.export = 2); } } - this.walk(tw); - const is_toplevel = this instanceof AST_Toplevel; - is_toplevel && (this.globals = new Map()); + this.walk(tw), this instanceof AST_Toplevel && (this.globals = new Map()); var tw = new TreeWalker((node)=>{ if (node instanceof AST_LoopControl && node.label) return node.label.thedef.references.push(node), !0; if (node instanceof AST_SymbolRef) { @@ -5437,8 +5398,7 @@ 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 2 * first + lambda_modifiers(this) + 12 + list_overhead(this.argnames) + list_overhead(this.body); + return 2 * !!first_in_statement(info) + 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() { @@ -6598,13 +6558,12 @@ var expression = this.expression.drop_side_effect_free(compressor, first_in_statement); return first_in_statement && expression && is_iife_call(expression) ? expression === this.expression && "!" == this.operator ? this : expression.negate(compressor, first_in_statement) : 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; + return this.is_declared(compressor) || pure_prop_access_globals.has(this.name) ? 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, key = computed_key && this.key.drop_side_effect_free(compressor, first_in_statement), value = this.value && this.value.drop_side_effect_free(compressor, first_in_statement); + const key = this instanceof AST_ObjectKeyVal && this.key instanceof AST_Node && this.key.drop_side_effect_free(compressor, first_in_statement), value = this.value && this.value.drop_side_effect_free(compressor, first_in_statement); return key && value ? make_sequence(this, [ key, value @@ -6845,16 +6804,7 @@ } for(var prev, n = 0, 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)=>node instanceof AST_Scope || (node instanceof AST_Binary && "in" === node.operator ? walk_abort : void 0)); - abort || (stat.init ? stat.init = cons_seq(stat.init) : (stat.init = prev.body, n--, CHANGED = !0)); - } - } else stat instanceof AST_ForIn ? stat.init instanceof AST_Const || stat.init instanceof AST_Let || (stat.object = cons_seq(stat.object)) : stat instanceof AST_If ? stat.condition = cons_seq(stat.condition) : stat instanceof AST_Switch ? stat.expression = cons_seq(stat.expression) : stat instanceof AST_With && (stat.expression = cons_seq(stat.expression)); - } - if (compressor.option("conditionals") && stat instanceof AST_If) { + if (!prev || (stat instanceof AST_Exit ? stat.value = cons_seq(stat.value || make_node(AST_Undefined, stat).transform(compressor)) : stat instanceof AST_For ? stat.init instanceof AST_Definitions || walk(prev.body, (node)=>node instanceof AST_Scope || (node instanceof AST_Binary && "in" === node.operator ? walk_abort : void 0)) || (stat.init ? stat.init = cons_seq(stat.init) : (stat.init = prev.body, n--, CHANGED = !0)) : stat instanceof AST_ForIn ? stat.init instanceof AST_Const || stat.init instanceof AST_Let || (stat.object = cons_seq(stat.object)) : stat instanceof AST_If ? stat.condition = cons_seq(stat.condition) : stat instanceof AST_Switch ? stat.expression = cons_seq(stat.expression) : stat instanceof AST_With && (stat.expression = cons_seq(stat.expression))), compressor.option("conditionals") && stat instanceof AST_If) { var decls = [], body = to_simple_statement(stat.body, decls), alt = to_simple_statement(stat.alternative, decls); if (!1 !== body && !1 !== alt && decls.length > 0) { var len = decls.length; @@ -6959,8 +6909,8 @@ args = iife.args.slice(len); for(var names = new Set(), i = len; --i >= 0;){ var sym = fn.argnames[i], arg = iife.args[i]; - const def = sym.definition && sym.definition(), is_reassigned = def && def.orig.length > 1; - if (!is_reassigned && (args.unshift(make_node(AST_VarDef, sym, { + const def = sym.definition && sym.definition(); + if ((!def || !(def.orig.length > 1)) && (args.unshift(make_node(AST_VarDef, sym, { name: sym, value: arg })), !names.has(sym.name))) { @@ -7605,8 +7555,7 @@ }), node !== self1) { 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 === self1) && node_def.global && !in_use_ids.has(node_def.id) && in_use_ids.set(node_def.id, node_def), node instanceof AST_DefClass) for (const prop of (node.extends && (node.extends.has_side_effects(compressor) || node.extends.may_throw(compressor)) && node.extends.walk(tw), node.properties))(prop.has_side_effects(compressor) || prop.may_throw(compressor)) && prop.walk(tw); + if ((tw.parent() instanceof AST_Export || !drop_funcs && scope === self1) && node_def.global && !in_use_ids.has(node_def.id) && in_use_ids.set(node_def.id, node_def), node instanceof AST_DefClass) for (const prop of (node.extends && (node.extends.has_side_effects(compressor) || node.extends.may_throw(compressor)) && node.extends.walk(tw), node.properties))(prop.has_side_effects(compressor) || prop.may_throw(compressor)) && prop.walk(tw); return map_add(initializations, node_def.id, node), !0; } if (node instanceof AST_SymbolFunarg && scope === self1 && map_add(var_defs_by_id, node.definition().id, node), node instanceof AST_Definitions && scope === self1) { @@ -8390,10 +8339,9 @@ return params.push(value), arg !== value; })) { let [source, flags] = params; - source = regexp_source_fix(new RegExp(source).source); const rx = make_node(AST_RegExp, self1, { value: { - source, + source: source = regexp_source_fix(new RegExp(source).source), flags } }); @@ -8650,8 +8598,7 @@ expression: fn, args: self1.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) { + if (is_regular_func && compressor.option("side_effects") && fn.body.every(is_empty)) { var args = self1.args.concat(make_node(AST_Undefined, self1)); return make_sequence(self1, args).optimize(compressor); } @@ -8667,8 +8614,7 @@ } function append_var(decls, expressions, name, value) { var def = name.definition(); - const already_appended = scope.variables.has(name.name); - already_appended || (scope.variables.set(name.name, def), scope.enclosed.push(def), decls.push(make_node(AST_VarDef, name, { + scope.variables.has(name.name) || (scope.variables.set(name.name, def), scope.enclosed.push(def), decls.push(make_node(AST_VarDef, name, { name: name, value: null }))); @@ -9434,8 +9380,7 @@ if (expr instanceof AST_Object) for(var props = expr.properties, 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 || !safe_to_flatten(prop.value, compressor)) return; + if (!props.every((p)=>(p instanceof AST_ObjectKeyVal || arrows && p instanceof AST_ConciseMethod && !p.is_generator) && !p.computed_key()) || !safe_to_flatten(prop.value, compressor)) return; return make_node(AST_Sub, this, { expression: make_node(AST_Array, expr, { elements: props.map(function(prop) { @@ -9601,13 +9546,9 @@ }), def_optimize(AST_RegExp, literals_in_boolean_context), def_optimize(AST_Return, function(self1, compressor) { return self1.value && is_undefined(self1.value, compressor) && (self1.value = null), self1; }), def_optimize(AST_Arrow, opt_AST_Lambda), def_optimize(AST_Function, function(self1, compressor) { - if (self1 = opt_AST_Lambda(self1, compressor), compressor.option("unsafe_arrows") && compressor.option("ecma") >= 2015 && !self1.name && !self1.is_generator && !self1.uses_arguments && !self1.pinned()) { - const uses_this = walk(self1, (node)=>{ - if (node instanceof AST_This) return walk_abort; - }); - if (!uses_this) return make_node(AST_Arrow, self1, self1).optimize(compressor); - } - return self1; + return (self1 = opt_AST_Lambda(self1, compressor), !(compressor.option("unsafe_arrows") && compressor.option("ecma") >= 2015) || self1.name || self1.is_generator || self1.uses_arguments || self1.pinned() || walk(self1, (node)=>{ + if (node instanceof AST_This) return walk_abort; + })) ? self1 : make_node(AST_Arrow, self1, self1).optimize(compressor); }), def_optimize(AST_Class, function(self1) { return self1; }), def_optimize(AST_Yield, function(self1, compressor) { @@ -17510,9 +17451,7 @@ } catch (e) { if ("EEXIST" !== e.code) throw e; } - const log_path = `${debug_folder}/terser-debug-${9999999 * Math.random() | 0}.log`; - options = options || {}; - const options_str = JSON.stringify(options, (_key, thing)=>"function" == typeof thing ? "[Function " + thing.toString() + "]" : thing instanceof RegExp ? "[RegExp " + thing.toString() + "]" : thing, 4), files_str = (file)=>"object" == typeof file && options.parse && options.parse.spidermonkey ? JSON.stringify(file, null, 2) : "object" == typeof file ? Object.keys(file).map((key)=>key + ": " + files_str(file[key])).join("\n\n") : "string" == typeof file ? "```\n" + file + "\n```" : file; + const log_path = `${debug_folder}/terser-debug-${9999999 * Math.random() | 0}.log`, options_str = JSON.stringify(options = options || {}, (_key, thing)=>"function" == typeof thing ? "[Function " + thing.toString() + "]" : thing instanceof RegExp ? "[RegExp " + thing.toString() + "]" : thing, 4), files_str = (file)=>"object" == typeof file && options.parse && options.parse.spidermonkey ? JSON.stringify(file, null, 2) : "object" == typeof file ? Object.keys(file).map((key)=>key + ": " + files_str(file[key])).join("\n\n") : "string" == typeof file ? "```\n" + file + "\n```" : file; fs.writeFileSync(log_path, "Options: \n" + options_str + "\n\nInput files:\n\n" + files_str(files) + "\n"); }(files, options, _fs_module, process.env.TERSER_DEBUG_DIR); var quoted_props, toplevel, timings = (options = defaults(options, { diff --git a/crates/swc_ecma_minifier/tests/benches-full/victory.js b/crates/swc_ecma_minifier/tests/benches-full/victory.js index 44bd410da382..ce6517670ebf 100644 --- a/crates/swc_ecma_minifier/tests/benches-full/victory.js +++ b/crates/swc_ecma_minifier/tests/benches-full/victory.js @@ -24774,9 +24774,7 @@ } function cross(...values) { var reduce; - const reduce1 = "function" == typeof values[values.length - 1] && (reduce = values.pop(), (values)=>reduce(...values)); - values = values.map(arrayify); - const lengths = values.map(length), j = values.length - 1, index = Array(j + 1).fill(0), product = []; + const reduce1 = "function" == typeof values[values.length - 1] && (reduce = values.pop(), (values)=>reduce(...values)), lengths = (values = values.map(arrayify)).map(length), j = values.length - 1, index = Array(j + 1).fill(0), product = []; if (j < 0 || lengths.some(empty)) return product; for(;;){ product.push(index.map((j, i)=>values[i][j])); diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/2257/full/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/2257/full/output.js index 13f030588b55..d426d6908620 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/2257/full/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/2257/full/output.js @@ -10230,8 +10230,7 @@ return -1 !== hashStart && (input = input.slice(0, hashStart)), input; } function extract(input) { - input = removeHash(input); - const queryStart = input.indexOf("?"); + const queryStart = (input = removeHash(input)).indexOf("?"); return -1 === queryStart ? "" : input.slice(queryStart + 1); } function parseValue(value, options) { @@ -10407,9 +10406,9 @@ encode: !0, strict: !0 }, options); - const url = removeHash(object.url).split("?")[0] || "", queryFromUrl = exports.extract(object.url), parsedQueryFromUrl = exports.parse(queryFromUrl, { + const url = removeHash(object.url).split("?")[0] || "", queryFromUrl = exports.extract(object.url), query = Object.assign(exports.parse(queryFromUrl, { sort: !1 - }), query = Object.assign(parsedQueryFromUrl, object.query); + }), object.query); let queryString = exports.stringify(query, options); queryString && (queryString = `?${queryString}`); let hash = function(url) { diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/5682/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/5682/output.js index 10c82ee769c3..8d932ef4a212 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/5682/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/5682/output.js @@ -1,4 +1,4 @@ -const m = 60000, h = 60 * m, d = 24 * h, w = 7 * d, y = 365.25 * d; +const m = 60000, h = 3600000, d = 86400000, w = 604800000, y = 31557600000; export default function(value, options) { try { if ('string' == typeof value && value.length > 0) return function(str) { @@ -58,10 +58,9 @@ export default function(value, options) { }(value); throw Error('Value is not a string or number.'); } catch (error) { - const message = function(value) { + throw Error(function(value) { return 'object' == typeof value && null !== value && 'message' in value; - }(error) ? `${error.message}. value=${JSON.stringify(value)}` : 'An unknown error has occurred.'; - throw Error(message); + }(error) ? `${error.message}. value=${JSON.stringify(value)}` : 'An unknown error has occurred.'); } } function plural(ms, msAbs, n, name) { diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/5865/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/5865/output.js index 8815d30ab876..94928ad943f2 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/5865/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/5865/output.js @@ -1,6 +1,3 @@ -v = ((a)=>(b)=>{ - const n = a.map((t)=>{ +v = ((a)=>(b)=>a.map((t)=>{ if (t) return ((e)=>e.foo)(t); - }); - return n; - })(r); + }))(r); diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/5910/1/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/5910/1/output.js index 0c3bffa08a5e..487dd27414ae 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/5910/1/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/5910/1/output.js @@ -1,7 +1,6 @@ export function fn1() { let walkingIndex = 0; return function() { - const myIndex = walkingIndex; - console.log(myIndex, walkingIndex += 1); + console.log(walkingIndex, walkingIndex += 1); }; } diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/6492/2/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/6492/2/output.js index ff7a2700b924..a6a95bcdccd5 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/6492/2/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/6492/2/output.js @@ -1,2 +1 @@ -const val = 42..toString(); -console.log('val', val); +console.log('val', 42..toString()); diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/6492/3/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/6492/3/output.js index ff7a2700b924..a6a95bcdccd5 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/6492/3/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/6492/3/output.js @@ -1,2 +1 @@ -const val = 42..toString(); -console.log('val', val); +console.log('val', 42..toString()); diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/6492/4/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/6492/4/output.js index ff7a2700b924..a6a95bcdccd5 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/6492/4/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/6492/4/output.js @@ -1,2 +1 @@ -const val = 42..toString(); -console.log('val', val); +console.log('val', 42..toString()); diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/7004/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/7004/output.js index a6e3e83e5adb..dcf7cb06d8f0 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/7004/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/7004/output.js @@ -1,11 +1,8 @@ -!function() { - var option; - const desc = [ - null, - (option = { - __labelPrefix: 'test', - tags: [] - }).__labelPrefix - ].concat(option.tags); - console.log(desc); -}(); +var option; +console.log([ + null, + (option = { + __labelPrefix: 'test', + tags: [] + }).__labelPrefix +].concat(option.tags)); diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/7241/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/7241/output.js index 70ee78471cef..7ce862f67fc0 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/7241/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/7241/output.js @@ -1,4 +1 @@ -!function() { - const _Test = something(); - console.log(_Test); -}(); +console.log(something()); diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/7287/1/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/7287/1/output.js index bb6b8a74108b..59238dabb24e 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/7287/1/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/7287/1/output.js @@ -1,4 +1 @@ -!function() { - const r = (console.log("REQUIRE"), 1); - console.log(r); -}(); +console.log((console.log("REQUIRE"), 1)); diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/7739/1/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/7739/1/output.js index c7b179387ac3..83af93cf17e6 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/7739/1/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/7739/1/output.js @@ -2,6 +2,4 @@ const formatterOpt = { minimumFractionDigits: 0, maximumFractionDigits: 0 }; -withCurrency && (formatterOpt.style = 'currency'); -const formatter = new Intl.NumberFormat('en', formatterOpt); -console.log(formatter.format(amount)); +withCurrency && (formatterOpt.style = 'currency'), console.log(new Intl.NumberFormat('en', formatterOpt).format(amount)); diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/7847/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/7847/output.js index 0819771a20a0..e0d732a4490b 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/7847/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/7847/output.js @@ -7,8 +7,5 @@ function requireState() { } if (g()) { var state, hasRequiredState; - const a = requireState(); - console.log(a.getHighWaterMark()); - const b = requireState(); - console.log(b.getHighWaterMark()); + console.log(requireState().getHighWaterMark()), console.log(requireState().getHighWaterMark()); } diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/8173/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/8173/output.js index 6ed0858d61d7..1d8d13dfc57f 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/8173/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/8173/output.js @@ -32,8 +32,7 @@ const someFn = (xx, x, y)=>[ 2, 3 ], goodFunction = (_ref = _async_to_generator(function*() { - const rb = yield getArray(), rc = yield getArray(); - console.log(someFn(1, rb, rc)); + console.log(someFn(1, (yield getArray()), (yield getArray()))); }), function() { return _ref.apply(this, arguments); }), badFunction = (_ref1 = _async_to_generator(function*() { diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/firebase-core/1/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/firebase-core/1/output.js index f6ed3f464c12..22899007bd1f 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/firebase-core/1/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/firebase-core/1/output.js @@ -67,8 +67,8 @@ const customData = data[0] || {}, fullCode = `${this.service}/${code}`, template = this.errors[code], message = template ? template.replace(PATTERN, (_, key)=>{ const value = customData[key]; return null != value ? String(value) : `<${key}?>`; - }) : "Error", fullMessage = `${this.serviceName}: ${message} (${fullCode}).`, error = new FirebaseError(fullCode, fullMessage, customData); - return error; + }) : "Error", fullMessage = `${this.serviceName}: ${message} (${fullCode}).`; + return new FirebaseError(fullCode, fullMessage, customData); } } const PATTERN = /\{\$([^}]+)}/g; @@ -2204,8 +2204,7 @@ this.container = container; } getPlatformInfoString() { - const providers = this.container.getProviders(); - return providers.map((provider)=>{ + return this.container.getProviders().map((provider)=>{ if (!function(provider) { const component = provider.getComponent(); return (null == component ? void 0 : component.type) === "VERSION"; diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/firebase-firestore/1/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/firebase-firestore/1/output.js index 7214983bf8d7..b897c97bb8a2 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/firebase-firestore/1/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/firebase-firestore/1/output.js @@ -251,8 +251,7 @@ }; } valueOf() { - const t = this.seconds - -62135596800; - return String(t).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0"); + return String(this.seconds - -62135596800).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0"); } } class rt { @@ -425,16 +424,14 @@ this.binaryString = t; } static fromBase64String(t) { - const e = atob(t); - return new _t(e); + return new _t(atob(t)); } static fromUint8Array(t) { - const e = function(t) { + return new _t(function(t) { let e = ""; for(let n = 0; n < t.length; ++n)e += String.fromCharCode(t[n]); return e; - }(t); - return new _t(e); + }(t)); } toBase64() { return btoa(this.binaryString); @@ -466,9 +463,8 @@ let t = n[1]; e = Number(t = (t + "000000000").substr(0, 9)); } - const s = new Date(t); return { - seconds: Math.floor(s.getTime() / 1e3), + seconds: Math.floor(new Date(t).getTime() / 1e3), nanos: e }; } @@ -1454,8 +1450,7 @@ return this.copy(null, null, !this.color, t, e); } checkMaxDepth() { - const t = this.check(); - return Math.pow(2, t) <= this.size + 1; + return Math.pow(2, this.check()) <= this.size + 1; } check() { if (this.isRed() && this.left.isRed() || this.right.isRed()) throw L(); @@ -1894,8 +1889,8 @@ }; } function fs(t) { - const e = !!t.before, n = t.values || []; - return new oe(n, e); + const e = !!t.before; + return new oe(t.values || [], e); } function _s(t) { return { @@ -3004,11 +2999,10 @@ this.activeTargetIds = this.activeTargetIds.delete(t); } Os() { - const t = { + return JSON.stringify({ activeTargetIds: this.activeTargetIds.toArray(), updateTimeMs: Date.now() - }; - return JSON.stringify(t); + }); } } class Kr { @@ -3361,11 +3355,8 @@ if ("targetChange" in e) { var t1, e1; e.targetChange; - const s = "NO_CHANGE" === (t1 = e.targetChange.targetChangeType || "NO_CHANGE") ? 0 : "ADD" === t1 ? 1 : "REMOVE" === t1 ? 2 : "CURRENT" === t1 ? 3 : "RESET" === t1 ? 4 : L(), i = e.targetChange.targetIds || [], r = (e1 = e.targetChange.resumeToken, t.D ? (void 0 === e1 || "string" == typeof e1 || L(), _t.fromBase64String(e1 || "")) : (void 0 === e1 || e1 instanceof Uint8Array || L(), _t.fromUint8Array(e1 || new Uint8Array()))), o = e.targetChange.cause, c = o && function(t) { - const e = void 0 === t.code ? K.UNKNOWN : dn(t.code); - return new j(e, t.message || ""); - }(o); - n = new xn(s, i, r, c || null); + const s = "NO_CHANGE" === (t1 = e.targetChange.targetChangeType || "NO_CHANGE") ? 0 : "ADD" === t1 ? 1 : "REMOVE" === t1 ? 2 : "CURRENT" === t1 ? 3 : "RESET" === t1 ? 4 : L(), i = e.targetChange.targetIds || [], r = (e1 = e.targetChange.resumeToken, t.D ? (void 0 === e1 || "string" == typeof e1 || L(), _t.fromBase64String(e1 || "")) : (void 0 === e1 || e1 instanceof Uint8Array || L(), _t.fromUint8Array(e1 || new Uint8Array()))), o = e.targetChange.cause; + n = new xn(s, i, r, o && new j(void 0 === o.code ? K.UNKNOWN : dn(o.code), o.message || "") || null); } else if ("documentChange" in e) { e.documentChange; const s = e.documentChange; @@ -3374,28 +3365,28 @@ mapValue: { fields: s.document.fields } - }), c = Kt.newFoundDocument(i, r, o), a = s.targetIds || [], u = s.removedTargetIds || []; - n = new Cn(a, u, c.key, c); + }), c = Kt.newFoundDocument(i, r, o); + n = new Cn(s.targetIds || [], s.removedTargetIds || [], c.key, c); } else if ("documentDelete" in e) { e.documentDelete; const s = e.documentDelete; s.document; - const i = zn(t, s.document), r = s.readTime ? jn(s.readTime) : rt.min(), o = Kt.newNoDocument(i, r), c = s.removedTargetIds || []; - n = new Cn([], c, o.key, o); + const i = zn(t, s.document), r = s.readTime ? jn(s.readTime) : rt.min(), o = Kt.newNoDocument(i, r); + n = new Cn([], s.removedTargetIds || [], o.key, o); } else if ("documentRemove" in e) { e.documentRemove; const s = e.documentRemove; s.document; - const i = zn(t, s.document), r = s.removedTargetIds || []; - n = new Cn([], r, i, null); + const i = zn(t, s.document); + n = new Cn([], s.removedTargetIds || [], i, null); } else { if (!("filter" in e)) return L(); { e.filter; const t = e.filter; t.targetId; - const s = t.count || 0, i = new un(s), r = t.targetId; - n = new Nn(r, i); + const i = new un(t.count || 0); + n = new Nn(t.targetId, i); } } return n; @@ -3671,7 +3662,7 @@ this.asyncQueue = t, this.timerId = e, this.targetTimeMs = n, this.op = s, this.removalCallback = i, this.deferred = new Q(), this.then = this.deferred.promise.then.bind(this.deferred.promise), this.deferred.promise.catch((t)=>{}); } static createAndSchedule(t, e, n, s, i) { - const r = Date.now() + n, o = new xo(t, e, r, s, i); + const o = new xo(t, e, Date.now() + n, s, i); return o.start(n), o; } start(t) { @@ -4577,9 +4568,7 @@ Pc(t) { const e = this._c.then(()=>(this.Ec = !0, t().catch((t)=>{ let e; - this.Tc = t, this.Ec = !1; - const e1 = (e = t.message || "", t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + "\n" + t.stack), e); - throw O("INTERNAL UNHANDLED ERROR: ", e1), t; + throw this.Tc = t, this.Ec = !1, O("INTERNAL UNHANDLED ERROR: ", (e = t.message || "", t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + "\n" + t.stack), e)), t; }).then((t)=>(this.Ec = !1, t)))); return this._c = e, e; } @@ -4923,12 +4912,12 @@ }(t._query), (function(t, e, n = {}) { const s = new Q(); return t.asyncQueue.enqueueAndForget(async ()=>(function(t, e, n, s, i) { - const r = new Lc({ + const o = new Qo(n, new Lc({ next: (n)=>{ e.enqueueAndForget(()=>Uo(t, o)), n.fromCache && "server" === s.source ? i.reject(new j(K.UNAVAILABLE, 'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')) : i.resolve(n); }, error: (t)=>i.reject(t) - }), o = new Qo(n, r, { + }), { includeMetadataChanges: !0, fo: !0 }); @@ -4938,7 +4927,7 @@ } !function(t, e = !0) { C = _firebase_app__WEBPACK_IMPORTED_MODULE_0__.Jn, (0, _firebase_app__WEBPACK_IMPORTED_MODULE_0__.Xd)(new _firebase_component__WEBPACK_IMPORTED_MODULE_1__.wA("firestore", (t, { options: n })=>{ - const s = t.getProvider("app").getImmediate(), i = new ka(s, new H(t.getProvider("auth-internal"))); + const i = new ka(t.getProvider("app").getImmediate(), new H(t.getProvider("auth-internal"))); return n = Object.assign({ useFetchStreams: e }, n), i._setSettings(n), i; diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/react-instancesearch/002/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/react-instancesearch/002/output.js index 959ab3932652..5e9a20f9e2d3 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/react-instancesearch/002/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/react-instancesearch/002/output.js @@ -164,13 +164,13 @@ export default function createInstantSearchManager({ indexName, initialState = { ...indices, [indexId]: widgets.concat(widget) }; - }, {}), derivedParameters = Object.keys(derivedIndices).map((indexId)=>({ - parameters: derivedIndices[indexId].reduce((res, widget)=>widget.getSearchParameters(res), sharedParameters), - indexId - })); + }, {}); return { mainParameters, - derivedParameters + derivedParameters: Object.keys(derivedIndices).map((indexId)=>({ + parameters: derivedIndices[indexId].reduce((res, widget)=>widget.getSearchParameters(res), sharedParameters), + indexId + })) }; } function search() { @@ -179,8 +179,7 @@ export default function createInstantSearchManager({ indexName, initialState = { helper.derivedHelpers.slice().forEach((derivedHelper)=>{ derivedHelper.detach(); }), derivedParameters.forEach(({ indexId, parameters })=>{ - const derivedHelper = helper.derive(()=>parameters); - derivedHelper.on("result", handleSearchSuccess({ + helper.derive(()=>parameters).on("result", handleSearchSuccess({ indexId })).on("error", handleSearchError); }), helper.setState(mainParameters), helper.search(); diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/react-instancesearch/003/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/react-instancesearch/003/output.js index 004c0f911f1a..ffa5df77cd23 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/react-instancesearch/003/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/react-instancesearch/003/output.js @@ -179,13 +179,13 @@ export default function createInstantSearchManager({ indexName, initialState = { ...indices, [indexId]: widgets.concat(widget) }; - }, {}), derivedParameters = Object.keys(derivedIndices).map((indexId)=>({ - parameters: derivedIndices[indexId].reduce((res, widget)=>widget.getSearchParameters(res), sharedParameters), - indexId - })); + }, {}); return { mainParameters, - derivedParameters + derivedParameters: Object.keys(derivedIndices).map((indexId)=>({ + parameters: derivedIndices[indexId].reduce((res, widget)=>widget.getSearchParameters(res), sharedParameters), + indexId + })) }; } function search() { @@ -194,8 +194,7 @@ export default function createInstantSearchManager({ indexName, initialState = { helper.derivedHelpers.slice().forEach((derivedHelper)=>{ derivedHelper.detach(); }), derivedParameters.forEach(({ indexId, parameters })=>{ - const derivedHelper = helper.derive(()=>parameters); - derivedHelper.on("result", handleSearchSuccess({ + helper.derive(()=>parameters).on("result", handleSearchSuccess({ indexId })).on("error", handleSearchError); }), helper.setState(mainParameters), helper.search(); diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/vercel/003/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/vercel/003/output.js index 038f4d7b9988..405d52db1159 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/vercel/003/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/vercel/003/output.js @@ -7,7 +7,7 @@ const manager = function() { } function g(u, v) { for (let w of u){ - const x = j(v), y = x.get(w.target); + const y = j(v).get(w.target); y && y(w); } } @@ -20,12 +20,10 @@ const manager = function() { }(e) || new IntersectionObserver(g, e); }, l: function(m, n, o) { - const p = j(m); - p.set(n, o), m.observe(n); + j(m).set(n, o), m.observe(n); }, q: function(r, s) { - const t = j(r); - t.delete(s), r.unobserve(s); + j(r).delete(s), r.unobserve(s); } }; }(); diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/vercel/005/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/vercel/005/output.js index 66d7f046952d..117f9825297b 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/vercel/005/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/vercel/005/output.js @@ -57,8 +57,7 @@ export default function(value, options) { }(value); throw Error("Value is not a string or number."); } catch (error) { - const message = "object" == typeof error && null !== error && "message" in error ? `${error.message}. value=${JSON.stringify(value)}` : "An unknown error has occured."; - throw Error(message); + throw Error("object" == typeof error && null !== error && "message" in error ? `${error.message}. value=${JSON.stringify(value)}` : "An unknown error has occured."); } } function plural(ms, msAbs, n, name) { diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/vercel/006/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/vercel/006/output.js index 162329b0fa38..f3673d36071e 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/vercel/006/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/vercel/006/output.js @@ -79,13 +79,11 @@ class LoadScript extends React.PureComponent { style.parentNode && style.parentNode.removeChild(style); }); }, this.injectScript = ()=>{ - this.props.preventGoogleFontsLoading && preventGoogleFonts(), invariant(!!this.props.id, 'LoadScript requires "id" prop to be a string: %s', this.props.id); - const injectScriptOptions = { + this.props.preventGoogleFontsLoading && preventGoogleFonts(), invariant(!!this.props.id, 'LoadScript requires "id" prop to be a string: %s', this.props.id), injectScript({ id: this.props.id, nonce: this.props.nonce, url: makeLoadScriptUrl(this.props) - }; - injectScript(injectScriptOptions).then(()=>{ + }).then(()=>{ this.props.onLoad && this.props.onLoad(), this.setState(function() { return { loaded: !0 diff --git a/crates/swc_ecma_minifier/tests/fixture/next/41527/1/output.js b/crates/swc_ecma_minifier/tests/fixture/next/41527/1/output.js index 39586eb78601..d33f87b6d3e8 100644 --- a/crates/swc_ecma_minifier/tests/fixture/next/41527/1/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/next/41527/1/output.js @@ -108,14 +108,9 @@ Toolbar.DEFAULTS = {}, Toolbar.DEFAULTS = { handlers: { clean () { const range = this.quill.getSelection(); - if (null != range) { - if (0 === range.length) { - const formats = this.quill.getFormat(); - Object.keys(formats).forEach((name)=>{ - null != this.quill.scroll.query(name, Scope.INLINE) && this.quill.format(name, !1, Quill.sources.USER); - }); - } else this.quill.removeFormat(range, Quill.sources.USER); - } + null != range && (0 === range.length ? Object.keys(this.quill.getFormat()).forEach((name)=>{ + null != this.quill.scroll.query(name, Scope.INLINE) && this.quill.format(name, !1, Quill.sources.USER); + }) : this.quill.removeFormat(range, Quill.sources.USER)); }, direction (value) { const { align } = this.quill.getFormat(); diff --git a/crates/swc_ecma_minifier/tests/fixture/next/outstatic/1/output.js b/crates/swc_ecma_minifier/tests/fixture/next/outstatic/1/output.js index f1f79a0113c4..9af9c121e6f6 100644 --- a/crates/swc_ecma_minifier/tests/fixture/next/outstatic/1/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/next/outstatic/1/output.js @@ -6,36 +6,28 @@ 1973: function(module) { eval(module.code); }, - 1985: function(o, f, i) { + 1985: function(c, o, f) { "use strict"; - var k = 0, v = (o)=>"checkbox" === o.type; - var b = (o, f)=>{ - var i; - return o.has((i = f, i.substring(0, i.search(/\.\d+(\.|$)/)) || i)); - }, g = ()=>{}; - function C(o, f, i) {} - var m = (o)=>"radio" === o.type; - function w(o = {}) { - let f, i = { - ...o - }, k = {}, v = 0, b = {}, g = {}; - const C = 0, m = async (o)=>{ - const i = o.target; - let k = i.name; - const v = 0; - if (v) { - let i, b; - const g = 0; - g ? (v._f.onBlur && v._f.onBlur(o), f && f(0)) : v._f.onChange && v._f.onChange(o); - const m = 0; - v._f.deps && C(k, b, i, m); - } + var i = 0, l = (c)=>"checkbox" === c.type; + var k = (c, o)=>{ + var f; + return c.has((f = o, f.substring(0, f.search(/\.\d+(\.|$)/)) || f)); + }, v = ()=>{}; + function b(c, o, f) {} + var g = (c)=>"radio" === c.type; + function m(c = {}) { + let o, f = { + ...c + }, i = {}, l = 0, k = {}, v = {}; + const b = 0, g = async (c)=>{ + let o = c.target.name; + const f = 0; }; } - f.useForm = function(o = {}) { - const f = k.default.useRef(); - f.current ? f.current.control._options = o : f.current = { - ...w(o) + o.useForm = function(c = {}) { + const o = i.default.useRef(); + o.current ? o.current.control._options = c : o.current = { + ...m(c) }; }; } diff --git a/crates/swc_ecma_minifier/tests/fixture/next/styled-components/1/output.js b/crates/swc_ecma_minifier/tests/fixture/next/styled-components/1/output.js index fb075cdd6a85..210ac621cb03 100644 --- a/crates/swc_ecma_minifier/tests/fixture/next/styled-components/1/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/next/styled-components/1/output.js @@ -5905,8 +5905,7 @@ var _window, _window$matchMedia; const media = null === (_window = window) || void 0 === _window ? void 0 : null === (_window$matchMedia = _window.matchMedia) || void 0 === _window$matchMedia ? void 0 : _window$matchMedia.call(_window, "(prefers-color-scheme: dark)"); function handleChange(event) { - const isNight = event.matches; - setSystemColorMode(isNight ? "night" : "day"); + setSystemColorMode(event.matches ? "night" : "day"); } if (media) { if (void 0 !== media.addEventListener) return media.addEventListener("change", handleChange), function() { @@ -6023,8 +6022,7 @@ ":not(:focus-visible)": { outline: "solid 1px transparent" } - }, getVariantStyles = (variant = "default", theme)=>{ - const style = { + }, getVariantStyles = (variant = "default", theme)=>({ default: { color: "btn.text", backgroundColor: "btn.bg", @@ -6202,9 +6200,7 @@ borderColor: "btn.outline.selectedBorder" } } - }; - return style[variant]; - }, getSizeStyles = (size = "medium", variant = "default", iconOnly)=>{ + })[variant], getSizeStyles = (size = "medium", variant = "default", iconOnly)=>{ let paddingY, paddingX, fontSize; switch(size){ case "small": @@ -6249,8 +6245,7 @@ outline: "solid 1px transparent" } } - }), getButtonStyles = (theme)=>{ - const styles = { + }), getButtonStyles = (theme)=>({ ...getBaseStyles(theme), display: "grid", gridTemplateAreas: '"leadingIcon text trailingIcon"', @@ -6266,9 +6261,7 @@ '[data-component="trailingIcon"]': { gridArea: "trailingIcon" } - }; - return styles; - }; + }); function ButtonBase_extends() { return (ButtonBase_extends = Object.assign || function(target) { for(var i = 1; i < arguments.length; i++){ @@ -6327,11 +6320,11 @@ return void 0 === (fallback = getKey(lib_esm_theme, key)) && (fallback = null), function(props) { return get(props.theme, key, fallback); }; - }, COMMON = constants_compose(space, color, display), whiteSpace = constants_system({ + }, COMMON = constants_compose(space, color, display), TYPOGRAPHY = constants_compose(typography, constants_system({ whiteSpace: { property: "whiteSpace" } - }), TYPOGRAPHY = constants_compose(typography, whiteSpace); + })); constants_compose(border, shadow); const CounterLabel = He.span.withConfig({ displayName: "CounterLabel", diff --git a/crates/swc_ecma_minifier/tests/fixture/next/target-es2015/static/chunks/main-04b5934c26266542/output.js b/crates/swc_ecma_minifier/tests/fixture/next/target-es2015/static/chunks/main-04b5934c26266542/output.js index 16d7046c68e9..ec5192a50ea4 100644 --- a/crates/swc_ecma_minifier/tests/fixture/next/target-es2015/static/chunks/main-04b5934c26266542/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/next/target-es2015/static/chunks/main-04b5934c26266542/output.js @@ -197,10 +197,7 @@ (null == j ? void 0 : null == (ref = j.tagName) ? void 0 : ref.toLowerCase()) === type && oldTags.push(j); } const newTags = components.map(reactElementToDOM).filter((newTag)=>{ - for(let k = 0, len = oldTags.length; k < len; k++){ - const oldTag = oldTags[k]; - if (isEqualNode(oldTag, newTag)) return oldTags.splice(k, 1), !1; - } + for(let k = 0, len = oldTags.length; k < len; k++)if (isEqualNode(oldTags[k], newTag)) return oldTags.splice(k, 1), !1; return !0; }); oldTags.forEach((t)=>{ @@ -436,8 +433,8 @@ } function doRender(input) { let resolvePromise, { App, Component, props, err } = input, styleSheets = "initial" in input ? void 0 : input.styleSheets; - Component = Component || lastAppProps.Component, props = props || lastAppProps.props; - const appProps = _extends({}, props, { + Component = Component || lastAppProps.Component; + const appProps = _extends({}, props = props || lastAppProps.props, { Component, err, router @@ -492,12 +489,9 @@ return !function(domEl, fn) { _utils.ST && performance.mark("beforeRender"); const reactEl = fn(shouldHydrate ? markHydrateComplete : markRenderComplete); - if (reactRoot) { - const startTransition = _react.default.startTransition; - startTransition(()=>{ - reactRoot.render(reactEl); - }); - } else reactRoot = ReactDOM.hydrateRoot(domEl, reactEl), shouldHydrate = !1; + reactRoot ? (0, _react.default.startTransition)(()=>{ + reactRoot.render(reactEl); + }) : (reactRoot = ReactDOM.hydrateRoot(domEl, reactEl), shouldHydrate = !1); }(appElement, (callback)=>_react.default.createElement(Root, { callbacks: [ callback, @@ -768,8 +762,8 @@ if (previouslyLoadedPath.current = asPath, document.title) setRouteAnnouncement(document.title); else { var ref; - const pageHeader = document.querySelector("h1"), content = null != (ref = null == pageHeader ? void 0 : pageHeader.innerText) ? ref : null == pageHeader ? void 0 : pageHeader.textContent; - setRouteAnnouncement(content || asPath); + const pageHeader = document.querySelector("h1"); + setRouteAnnouncement((null != (ref = null == pageHeader ? void 0 : pageHeader.innerText) ? ref : null == pageHeader ? void 0 : pageHeader.textContent) || asPath); } } }, [ @@ -903,14 +897,12 @@ }); } function getClientBuildManifest() { - if (self.__BUILD_MANIFEST) return Promise.resolve(self.__BUILD_MANIFEST); - const onBuildManifest = new Promise((resolve)=>{ + return self.__BUILD_MANIFEST ? Promise.resolve(self.__BUILD_MANIFEST) : resolvePromiseWithTimeout(new Promise((resolve)=>{ const cb = self.__BUILD_MANIFEST_CB; self.__BUILD_MANIFEST_CB = ()=>{ resolve(self.__BUILD_MANIFEST), cb && cb(); }; - }); - return resolvePromiseWithTimeout(onBuildManifest, 3800, markAssetError(Error("Failed to load client build manifest"))); + }), 3800, markAssetError(Error("Failed to load client build manifest"))); } function getFilesForRoute(assetPrefix, route) { return getClientBuildManifest().then((manifest)=>{ @@ -1000,16 +992,12 @@ get: ()=>_router.default.events }), urlPropertyFields.forEach((field)=>{ Object.defineProperty(singletonRouter, field, { - get () { - const router = getRouter(); - return router[field]; - } + get: ()=>getRouter()[field] }); }), coreMethodFields.forEach((field)=>{ singletonRouter[field] = function() { for(var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++)args[_key] = arguments[_key]; - const router = getRouter(); - return router[field](...args); + return getRouter()[field](...args); }; }), [ "routeChangeStart", @@ -1039,16 +1027,13 @@ Object.defineProperty(exports, "__esModule", { value: !0 }), exports.handleClientScriptLoad = handleClientScriptLoad, exports.initScriptLoader = function(scriptLoaderItems) { - scriptLoaderItems.forEach(handleClientScriptLoad), function() { - const scripts = [ - ...document.querySelectorAll('[data-nscript="beforeInteractive"]'), - ...document.querySelectorAll('[data-nscript="beforePageRender"]') - ]; - scripts.forEach((script)=>{ - const cacheKey = script.id || script.getAttribute("src"); - LoadCache.add(cacheKey); - }); - }(); + scriptLoaderItems.forEach(handleClientScriptLoad), [ + ...document.querySelectorAll('[data-nscript="beforeInteractive"]'), + ...document.querySelectorAll('[data-nscript="beforePageRender"]') + ].forEach((script)=>{ + const cacheKey = script.id || script.getAttribute("src"); + LoadCache.add(cacheKey); + }); }, exports.default = void 0; var _extends = __webpack_require__(6495).Z, _interop_require_wildcard = __webpack_require__(1598).Z, _object_without_properties_loose = __webpack_require__(7273).Z, _react = _interop_require_wildcard(__webpack_require__(7294)), _headManagerContext = __webpack_require__(8404), _headManager = __webpack_require__(6007), _requestIdleCallback = __webpack_require__(9311); const ScriptCache = new Map(), LoadCache = new Set(), ignoreProps = [ @@ -1181,9 +1166,8 @@ function _appGetInitialProps() { return (_appGetInitialProps = _async_to_generator(function*(param) { let { Component, ctx } = param; - const pageProps = yield _utils.loadGetInitialProps(Component, ctx); return { - pageProps + pageProps: yield _utils.loadGetInitialProps(Component, ctx) }; })).apply(this, arguments); } @@ -1209,9 +1193,8 @@ }; function _getInitialProps(param) { let { res, err } = param; - const statusCode = res && res.statusCode ? res.statusCode : err ? err.statusCode : 404; return { - statusCode + statusCode: res && res.statusCode ? res.statusCode : err ? err.statusCode : 404 }; } const styles = { @@ -1275,8 +1258,7 @@ Object.defineProperty(exports, "__esModule", { value: !0 }), exports.AmpStateContext = void 0; - var _react = (0, __webpack_require__(2648).Z)(__webpack_require__(7294)); - const AmpStateContext = _react.default.createContext({}); + const AmpStateContext = (0, __webpack_require__(2648).Z)(__webpack_require__(7294)).default.createContext({}); exports.AmpStateContext = AmpStateContext; }, 7363: function(__unused_webpack_module, exports) { @@ -1302,8 +1284,7 @@ Object.defineProperty(exports, "__esModule", { value: !0 }), exports.HeadManagerContext = void 0; - var _react = (0, __webpack_require__(2648).Z)(__webpack_require__(7294)); - const HeadManagerContext = _react.default.createContext({}); + const HeadManagerContext = (0, __webpack_require__(2648).Z)(__webpack_require__(7294)).default.createContext({}); exports.HeadManagerContext = HeadManagerContext; }, 5443: function(module, exports, __webpack_require__) { @@ -1515,8 +1496,7 @@ Object.defineProperty(exports, "__esModule", { value: !0 }), exports.RouterContext = void 0; - var _react = (0, __webpack_require__(2648).Z)(__webpack_require__(7294)); - const RouterContext = _react.default.createContext(null); + const RouterContext = (0, __webpack_require__(2648).Z)(__webpack_require__(7294)).default.createContext(null); exports.RouterContext = RouterContext; }, 6273: function(__unused_webpack_module, exports, __webpack_require__) { @@ -1584,8 +1564,8 @@ function resolveHref(router, href, resolveAs) { let base; let urlAsString = "string" == typeof href ? href : _formatUrl.formatWithValidation(href); - const urlProtoMatch = urlAsString.match(/^[a-zA-Z]{1,}:\/\//), urlAsStringNoProto = urlProtoMatch ? urlAsString.slice(urlProtoMatch[0].length) : urlAsString, urlParts = urlAsStringNoProto.split("?"); - if ((urlParts[0] || "").match(/(\/\/|\\)/)) { + const urlProtoMatch = urlAsString.match(/^[a-zA-Z]{1,}:\/\//), urlAsStringNoProto = urlProtoMatch ? urlAsString.slice(urlProtoMatch[0].length) : urlAsString; + if ((urlAsStringNoProto.split("?")[0] || "").match(/(\/\/|\\)/)) { console.error("Invalid href passed to next/router: ".concat(urlAsString, ", repeated forward-slashes (//) or backslashes \\ are not valid in the href")); const normalizedUrl = _utils.normalizeRepeatedSlashes(urlAsStringNoProto); urlAsString = (urlProtoMatch ? urlProtoMatch[0] : "") + normalizedUrl; @@ -1844,8 +1824,7 @@ if (routeMatch && pathname !== cleanedParsedPathname && Object.keys(routeMatch).forEach((key)=>{ routeMatch && query[key] === routeMatch[key] && delete query[key]; }), _isDynamic.isDynamicRoute(pathname)) { - const prefixedAs = !routeProps.shallow && routeInfo.resolvedAs ? routeInfo.resolvedAs : _addBasePath.addBasePath(_addLocale.addLocale(new URL(as, location.href).pathname, nextState.locale), !0); - let rewriteAs = prefixedAs; + let rewriteAs = !routeProps.shallow && routeInfo.resolvedAs ? routeInfo.resolvedAs : _addBasePath.addBasePath(_addLocale.addLocale(new URL(as, location.href).pathname, nextState.locale), !0); _hasBasePath.hasBasePath(rewriteAs) && (rewriteAs = _removeBasePath.removeBasePath(rewriteAs)); const routeRegex1 = _routeRegex.getRouteRegex(pathname), curRouteMatch = _routeMatcher.getRouteMatcher(routeRegex1)(rewriteAs); curRouteMatch && Object.assign(query, curRouteMatch); @@ -1860,13 +1839,9 @@ } let { error, props, __N_SSG, __N_SSP } = routeInfo; const component = routeInfo.Component; - if (component && component.unstable_scriptLoader) { - const scripts = [].concat(component.unstable_scriptLoader()); - scripts.forEach((script)=>{ - _script.handleClientScriptLoad(script.props); - }); - } - if ((__N_SSG || __N_SSP) && props) { + if (component && component.unstable_scriptLoader && [].concat(component.unstable_scriptLoader()).forEach((script)=>{ + _script.handleClientScriptLoad(script.props); + }), (__N_SSG || __N_SSP) && props) { if (props.pageProps && props.pageProps.__N_REDIRECT) { options.locale = !1; const destination = props.pageProps.__N_REDIRECT; @@ -1912,8 +1887,8 @@ }), upcomingScrollState = null != forcedScroll ? forcedScroll : shouldScroll ? { x: 0, y: 0 - } : null, canSkipUpdating = options._h && !upcomingScrollState && !readyStateChange && !localeChange && _compareStates.compareRouterStates(upcomingRouterState, _this.state); - if (!canSkipUpdating) { + } : null; + if (!(options._h && !upcomingScrollState && !readyStateChange && !localeChange && _compareStates.compareRouterStates(upcomingRouterState, _this.state))) { if (yield _this.set(upcomingRouterState, routeInfo, upcomingScrollState).catch((e)=>{ if (e.cancelled) error = error || e; else throw e; @@ -2447,8 +2422,7 @@ value: !0 }), exports.default = function(route) { let ext = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : ""; - const path = "/" === route ? "/index" : /^\/index(\/|$)/.test(route) ? "/index".concat(route) : "".concat(route); - return path + ext; + return ("/" === route ? "/index" : /^\/index(\/|$)/.test(route) ? "/index".concat(route) : "".concat(route)) + ext; }; }, 159: function(__unused_webpack_module, exports, __webpack_require__) { @@ -2813,7 +2787,7 @@ })), null; }; var _react = (0, __webpack_require__(1598).Z)(__webpack_require__(7294)); - const isServer = !1, useClientOnlyLayoutEffect = isServer ? ()=>{} : _react.useLayoutEffect, useClientOnlyEffect = isServer ? ()=>{} : _react.useEffect; + const isServer = !1, useClientOnlyLayoutEffect = _react.useLayoutEffect, useClientOnlyEffect = isServer ? ()=>{} : _react.useEffect; }, 3794: function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; @@ -2829,8 +2803,8 @@ const { href } = window.location, origin = getLocationOrigin(); return href.substring(origin.length); }, exports.getDisplayName = getDisplayName, exports.isResSent = isResSent, exports.normalizeRepeatedSlashes = function(url) { - const urlParts = url.split("?"), urlNoQuery = urlParts[0]; - return urlNoQuery.replace(/\\/g, "/").replace(/\/\/+/g, "/") + (urlParts[1] ? "?".concat(urlParts.slice(1).join("?")) : ""); + const urlParts = url.split("?"); + return urlParts[0].replace(/\\/g, "/").replace(/\/\/+/g, "/") + (urlParts[1] ? "?".concat(urlParts.slice(1).join("?")) : ""); }, exports.loadGetInitialProps = loadGetInitialProps, exports.ST = exports.SP = exports.warnOnce = exports.isAbsoluteUrl = void 0; var _async_to_generator = __webpack_require__(932).Z; const ABSOLUTE_URL_REGEX = /^[a-zA-Z][a-zA-Z\d+\-.]*?:/; @@ -2855,10 +2829,7 @@ } : {}; const props = yield App.getInitialProps(ctx); if (res && isResSent(res)) return props; - if (!props) { - const message1 = '"'.concat(getDisplayName(App), '.getInitialProps()" should resolve to an object. But found "').concat(props, '" instead.'); - throw Error(message1); - } + if (!props) throw Error('"'.concat(getDisplayName(App), '.getInitialProps()" should resolve to an object. But found "').concat(props, '" instead.')); return props; })).apply(this, arguments); } diff --git a/crates/swc_ecma_minifier/tests/fixture/next/wrap-contracts/output.js b/crates/swc_ecma_minifier/tests/fixture/next/wrap-contracts/output.js index 903deaa422cd..0dcca48a4d86 100644 --- a/crates/swc_ecma_minifier/tests/fixture/next/wrap-contracts/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/next/wrap-contracts/output.js @@ -39,12 +39,12 @@ const byteLen = EC.n.bitLength() + 7 >> 3; let i = 0; for(; null == x && i < 100;){ - const res = sha512.array(new Uint8Array([ - ...toBytesInt32(i), - ...m - ])), r = [ + const r = [ 2, - ...res + ...sha512.array(new Uint8Array([ + ...toBytesInt32(i), + ...m + ])) ]; [x, y] = Unmarshal(r.slice(0, byteLen + 1)), i++; } @@ -54,32 +54,32 @@ const byteLen = EC.n.bitLength() + 7 >> 3; let i = 0; for(;;){ - const res = sha512.array(new Uint8Array([ + const k = new BN(sha512.array(new Uint8Array([ ...toBytesInt32(i), ...m - ])), k = new BN(res.slice(0, byteLen)); + ])).slice(0, byteLen)); if (-1 == k.cmp(EC.curve.n.sub(one))) return k.add(one); i++; } } function Evaluate(privateKey, m) { - const currentKey = EC.keyFromPrivate(privateKey), r = EC.genKeyPair(), rBN = r.getPrivate(), pointH = H1(m), point = pointH.mul(privateKey), vrf = point.encode(), rgPoint = EC.curve.g.mul(rBN), rhPoint = pointH.mul(rBN), b = [ + const currentKey = EC.keyFromPrivate(privateKey), rBN = EC.genKeyPair().getPrivate(), pointH = H1(m), vrf = pointH.mul(privateKey).encode(), rgPoint = EC.curve.g.mul(rBN), rhPoint = pointH.mul(rBN), s = H2([ ...EC.curve.g.encode(), ...pointH.encode(), ...currentKey.getPublic().encode(), ...vrf, ...rgPoint.encode(), ...rhPoint.encode() - ], s = H2(b), t = rBN.sub(s.mul(currentKey.getPrivate())).umod(EC.curve.n), index = sha256.array(new Uint8Array(vrf)), buf = [ - ...Array(32 - s.byteLength()).fill(0), - ...s.toArray(), - ...Array(32 - t.byteLength()).fill(0), - ...t.toArray(), - ...vrf - ]; + ]), t = rBN.sub(s.mul(currentKey.getPrivate())).umod(EC.curve.n); return [ - index, - buf + sha256.array(new Uint8Array(vrf)), + [ + ...Array(32 - s.byteLength()).fill(0), + ...s.toArray(), + ...Array(32 - t.byteLength()).fill(0), + ...t.toArray(), + ...vrf + ] ]; } function ProofHoHash(publicKey, data, proof) { @@ -87,14 +87,14 @@ if (129 !== proof.length) throw Error('invalid vrf'); const s = proof.slice(0, 32), t = proof.slice(32, 64), vrf = proof.slice(64, 129), uhPoint = decodePoint(vrf); if (!uhPoint) throw Error('invalid vrf'); - const tgPoint = EC.curve.g.mul(t), ksgPoint = currentKey.getPublic().mul(s), tksgPoint = tgPoint.add(ksgPoint), hPoint = H1(data), thPoint = hPoint.mul(t), shPoint = uhPoint.mul(s), tkshPoint = thPoint.add(shPoint), b = [ + const tgPoint = EC.curve.g.mul(t), ksgPoint = currentKey.getPublic().mul(s), tksgPoint = tgPoint.add(ksgPoint), hPoint = H1(data), thPoint = hPoint.mul(t), shPoint = uhPoint.mul(s), tkshPoint = thPoint.add(shPoint), h2 = H2([ ...EC.curve.g.encode(), ...hPoint.encode(), ...currentKey.getPublic().encode(), ...vrf, ...tksgPoint.encode(), ...tkshPoint.encode() - ], h2 = H2(b), buf = [ + ]), buf = [ ...Array(32 - h2.byteLength()).fill(0), ...h2.toArray() ]; @@ -1323,17 +1323,9 @@ }); } close(callback) { - if (callback = fromCallback(callback, kPromise), this[kClosed]) this.nextTick(callback); - else if (this[kClosing]) this[kCloseCallbacks].push(callback); - else if (this[kClosing] = !0, this[kCloseCallbacks].push(callback), this[kWorking]) { - if (this[kAbortOnClose]) { - const cb = this[kFinishWork](); - cb(new ModuleError('Aborted on iterator close()', { - code: 'LEVEL_ITERATOR_NOT_OPEN' - })); - } - } else this._close(this[kHandleClose]); - return callback[kPromise]; + return callback = fromCallback(callback, kPromise), this[kClosed] ? this.nextTick(callback) : this[kClosing] ? this[kCloseCallbacks].push(callback) : (this[kClosing] = !0, this[kCloseCallbacks].push(callback), this[kWorking] ? this[kAbortOnClose] && this[kFinishWork]()(new ModuleError('Aborted on iterator close()', { + code: 'LEVEL_ITERATOR_NOT_OPEN' + })) : this._close(this[kHandleClose])), callback[kPromise]; } _close(callback) { this.nextTick(callback); @@ -1473,8 +1465,7 @@ class AbstractLevel extends EventEmitter { constructor(manifest, options){ if (super(), 'object' != typeof manifest || null === manifest) throw TypeError("The first argument 'manifest' must be an object"); - options = getOptions(options); - const { keyEncoding, valueEncoding, passive, ...forward } = options; + const { keyEncoding, valueEncoding, passive, ...forward } = options = getOptions(options); for (const encoding of (this[kResources] = new Set(), this[kOperations] = [], this[kDeferOpen] = !0, this[kOptions] = forward, this[kStatus] = 'opening', this.supports = supports(manifest, { status: !0, promises: !0, @@ -2311,14 +2302,14 @@ throw Error(`Unable to get chunk: ${(0, error_1.getError)(resp)}`); } async getChunkData(offset) { - const chunk = await this.getChunk(offset), buf = ArweaveUtils.b64UrlToBuffer(chunk.chunk); - return buf; + const chunk = await this.getChunk(offset); + return ArweaveUtils.b64UrlToBuffer(chunk.chunk); } firstChunkOffset(offsetResponse) { return parseInt(offsetResponse.offset) - parseInt(offsetResponse.size) + 1; } async downloadChunkedData(id) { - const offsetResponse = await this.getTransactionOffset(id), size = parseInt(offsetResponse.size), endOffset = parseInt(offsetResponse.offset), startOffset = endOffset - size + 1, data = new Uint8Array(size); + const offsetResponse = await this.getTransactionOffset(id), size = parseInt(offsetResponse.size), startOffset = parseInt(offsetResponse.offset) - size + 1, data = new Uint8Array(size); let byte = 0; for(; byte < size;){ let chunkData; @@ -2570,20 +2561,20 @@ }); } async encrypt(data, key, salt) { - const derivedKey = crypto1.pbkdf2Sync(key, salt = salt || "salt", 100000, 32, this.hashAlgorithm), iv = crypto1.randomBytes(16), cipher = crypto1.createCipheriv(this.encryptionAlgorithm, derivedKey, iv), encrypted = Buffer.concat([ + const derivedKey = crypto1.pbkdf2Sync(key, salt = salt || "salt", 100000, 32, this.hashAlgorithm), iv = crypto1.randomBytes(16), cipher = crypto1.createCipheriv(this.encryptionAlgorithm, derivedKey, iv); + return Buffer.concat([ iv, cipher.update(data), cipher.final() ]); - return encrypted; } async decrypt(encrypted, key, salt) { try { - const derivedKey = crypto1.pbkdf2Sync(key, salt = salt || "salt", 100000, 32, this.hashAlgorithm), iv = encrypted.slice(0, 16), data = encrypted.slice(16), decipher = crypto1.createDecipheriv(this.encryptionAlgorithm, derivedKey, iv), decrypted = Buffer.concat([ + const derivedKey = crypto1.pbkdf2Sync(key, salt = salt || "salt", 100000, 32, this.hashAlgorithm), iv = encrypted.slice(0, 16), data = encrypted.slice(16), decipher = crypto1.createDecipheriv(this.encryptionAlgorithm, derivedKey, iv); + return Buffer.concat([ decipher.update(data), decipher.final() ]); - return decrypted; } catch (error) { throw Error("Failed to decrypt"); } @@ -2843,12 +2834,10 @@ }))); } async function computeRootHash(data) { - const rootNode = await generateTree(data); - return rootNode.id; + return (await generateTree(data)).id; } async function generateTree(data) { - const rootNode = await buildLayers(await generateLeaves(await chunkData(data))); - return rootNode; + return await buildLayers(await generateLeaves(await chunkData(data))); } async function generateTransactionChunks(data) { const chunks = await chunkData(data), leaves = await generateLeaves(chunks), root = await buildLayers(leaves), proofs = await generateProofs(root), lastChunk = chunks.slice(-1)[0]; @@ -2859,10 +2848,7 @@ }; } async function buildLayers(nodes, level = 0) { - if (nodes.length < 2) { - const root = nodes[0]; - return root; - } + if (nodes.length < 2) return nodes[0]; const nextLayer = []; for(let i = 0; i < nodes.length; i += 2)nextLayer.push(await hashBranch(nodes[i], nodes[i + 1])); return buildLayers(nextLayer, level + 1); @@ -2963,8 +2949,8 @@ await hash(left), await hash(right), await hash(offsetBuffer) - ]), updatedOutput = `${output}\n${JSON.stringify(Buffer.from(left))},${JSON.stringify(Buffer.from(right))},${offset} => ${JSON.stringify(pathHash)}`; - return debug(remainder, updatedOutput); + ]); + return debug(remainder, `${output}\n${JSON.stringify(Buffer.from(left))},${JSON.stringify(Buffer.from(right))},${offset} => ${JSON.stringify(pathHash)}`); } exports.arrayCompare = arrayCompare, exports.validatePath = validatePath, exports.debug = debug; }, @@ -3039,8 +3025,8 @@ return; } chunkIndex_ && (this.chunkIndex = chunkIndex_); - const chunk = this.transaction.getChunk(chunkIndex_ || this.chunkIndex, this.data), chunkOk = await (0, merkle_1.validatePath)(this.transaction.chunks.data_root, parseInt(chunk.offset), 0, parseInt(chunk.data_size), ArweaveUtils.b64UrlToBuffer(chunk.data_path)); - if (!chunkOk) throw Error(`Unable to validate chunk ${this.chunkIndex}`); + const chunk = this.transaction.getChunk(chunkIndex_ || this.chunkIndex, this.data); + if (!await (0, merkle_1.validatePath)(this.transaction.chunks.data_root, parseInt(chunk.offset), 0, parseInt(chunk.data_size), ArweaveUtils.b64UrlToBuffer(chunk.data_path))) throw Error(`Unable to validate chunk ${this.chunkIndex}`); const resp = await this.api.post("chunk", this.transaction.getChunk(this.chunkIndex, this.data)).catch((e)=>(console.error(e.message), { status: -1, data: { @@ -3062,8 +3048,7 @@ const resp = await api.get(`tx/${id}`); if (200 !== resp.status) throw Error(`Tx ${id} not found: ${resp.status}`); const transaction = resp.data; - transaction.data = new Uint8Array(0); - const serialized = { + return transaction.data = new Uint8Array(0), { txPosted: !0, chunkIndex: 0, lastResponseError: "", @@ -3071,7 +3056,6 @@ lastResponseStatus: 0, transaction }; - return serialized; } toJSON() { return { @@ -3084,8 +3068,7 @@ }; } async postTransaction() { - const uploadInBody = this.totalChunks <= MAX_CHUNKS_IN_BODY; - if (uploadInBody) { + if (this.totalChunks <= MAX_CHUNKS_IN_BODY) { this.transaction.data = this.data; const resp = await this.api.post("tx", this.transaction).catch((e)=>(console.error(e), { status: -1, @@ -3317,33 +3300,21 @@ } function b64UrlToString(b64UrlString) { let buffer = b64UrlToBuffer(b64UrlString); - if ("undefined" == typeof TextDecoder) { - const TextDecoder1 = __webpack_require__(9539).TextDecoder; - return new TextDecoder1("utf-8", { - fatal: !0 - }).decode(buffer); - } - return new TextDecoder("utf-8", { + return "undefined" == typeof TextDecoder ? new (__webpack_require__(9539)).TextDecoder("utf-8", { + fatal: !0 + }).decode(buffer) : new TextDecoder("utf-8", { fatal: !0 }).decode(buffer); } function bufferToString(buffer) { - if ("undefined" == typeof TextDecoder) { - const TextDecoder1 = __webpack_require__(9539).TextDecoder; - return new TextDecoder1("utf-8", { - fatal: !0 - }).decode(buffer); - } - return new TextDecoder("utf-8", { + return "undefined" == typeof TextDecoder ? new (__webpack_require__(9539)).TextDecoder("utf-8", { + fatal: !0 + }).decode(buffer) : new TextDecoder("utf-8", { fatal: !0 }).decode(buffer); } function stringToBuffer(string) { - if ("undefined" == typeof TextEncoder) { - const TextEncoder1 = __webpack_require__(9539).TextEncoder; - return new TextEncoder1().encode(string); - } - return new TextEncoder().encode(string); + return "undefined" == typeof TextEncoder ? new (__webpack_require__(9539)).TextEncoder().encode(string) : new TextEncoder().encode(string); } function stringToB64Url(string) { return bufferTob64Url(stringToBuffer(string)); @@ -3441,8 +3412,8 @@ async parseUri(siloURI) { const parsed = siloURI.match(/^([a-z0-9-_]+)\.([0-9]+)/i); if (!parsed) throw Error("Invalid Silo name, must be a name in the format of [a-z0-9]+.[0-9]+, e.g. 'bubble.7'"); - const siloName = parsed[1], hashIterations = Math.pow(2, parseInt(parsed[2])), digest = await this.hash(ArweaveUtils.stringToBuffer(siloName), hashIterations), accessKey = ArweaveUtils.bufferTob64(digest.slice(0, 15)), encryptionkey = await this.hash(digest.slice(16, 31), 1); - return new SiloResource(siloURI, accessKey, encryptionkey); + const siloName = parsed[1], hashIterations = Math.pow(2, parseInt(parsed[2])), digest = await this.hash(ArweaveUtils.stringToBuffer(siloName), hashIterations); + return new SiloResource(siloURI, ArweaveUtils.bufferTob64(digest.slice(0, 15)), await this.hash(digest.slice(16, 31), 1)); } async hash(input, iterations) { let digest = await this.crypto.hash(input); @@ -3627,8 +3598,7 @@ }); } else { try { - const existingPermissions = await window.arweaveWallet.getPermissions(); - existingPermissions.includes("SIGN_TRANSACTION") || await window.arweaveWallet.connect([ + (await window.arweaveWallet.getPermissions()).includes("SIGN_TRANSACTION") || await window.arweaveWallet.connect([ "SIGN_TRANSACTION" ]); } catch (_a) {} @@ -3856,14 +3826,14 @@ throw Error(`Unable to get chunk: ${(0, error_1.getError)(resp)}`); } async getChunkData(offset) { - const chunk = await this.getChunk(offset), buf = ArweaveUtils.b64UrlToBuffer(chunk.chunk); - return buf; + const chunk = await this.getChunk(offset); + return ArweaveUtils.b64UrlToBuffer(chunk.chunk); } firstChunkOffset(offsetResponse) { return parseInt(offsetResponse.offset) - parseInt(offsetResponse.size) + 1; } async downloadChunkedData(id) { - const offsetResponse = await this.getTransactionOffset(id), size = parseInt(offsetResponse.size), endOffset = parseInt(offsetResponse.offset), startOffset = endOffset - size + 1, data = new Uint8Array(size); + const offsetResponse = await this.getTransactionOffset(id), size = parseInt(offsetResponse.size), startOffset = parseInt(offsetResponse.offset) - size + 1, data = new Uint8Array(size); let byte = 0; for(; byte < size;){ let chunkData; @@ -3964,24 +3934,23 @@ }); const common_1 = __webpack_require__(536); common_1.default.init = function(apiConfig = {}) { - function getDefaultConfig() { + const defaultConfig = function() { const defaults = { host: "arweave.net", port: 443, protocol: "https" }; if (!window || !window.location || !window.location.protocol || !window.location.hostname) return defaults; - const currentProtocol = window.location.protocol.replace(":", ""), currentHost = window.location.hostname, currentPort = window.location.port ? parseInt(window.location.port) : "https" == currentProtocol ? 443 : 80, isLocal = [ + const currentProtocol = window.location.protocol.replace(":", ""), currentHost = window.location.hostname, currentPort = window.location.port ? parseInt(window.location.port) : "https" == currentProtocol ? 443 : 80; + return [ "localhost", "127.0.0.1" - ].includes(currentHost) || "file" == currentProtocol; - return isLocal ? defaults : { + ].includes(currentHost) || "file" == currentProtocol ? defaults : { host: currentHost, port: currentPort, protocol: currentProtocol }; - } - const defaultConfig = getDefaultConfig(), protocol = apiConfig.protocol || defaultConfig.protocol, host = apiConfig.host || defaultConfig.host, port = apiConfig.port || defaultConfig.port; + }(), protocol = apiConfig.protocol || defaultConfig.protocol, host = apiConfig.host || defaultConfig.host, port = apiConfig.port || defaultConfig.port; return new common_1.default(Object.assign(Object.assign({}, apiConfig), { host, protocol, @@ -4133,15 +4102,13 @@ detectWebCrypto() { if ("undefined" == typeof crypto) return !1; const subtle = null == crypto ? void 0 : crypto.subtle; - if (void 0 === subtle) return !1; - const names = [ + return void 0 !== subtle && [ "generateKey", "importKey", "exportKey", "digest", "sign" - ]; - return names.every((name)=>"function" == typeof subtle[name]); + ].every((name)=>"function" == typeof subtle[name]); } async encrypt(data, key, salt) { const initialKey = await this.driver.importKey("raw", "string" == typeof key ? ArweaveUtils.stringToBuffer(key) : key, { @@ -4297,12 +4264,10 @@ }))); } async function computeRootHash(data) { - const rootNode = await generateTree(data); - return rootNode.id; + return (await generateTree(data)).id; } async function generateTree(data) { - const rootNode = await buildLayers(await generateLeaves(await chunkData(data))); - return rootNode; + return await buildLayers(await generateLeaves(await chunkData(data))); } async function generateTransactionChunks(data) { const chunks = await chunkData(data), leaves = await generateLeaves(chunks), root = await buildLayers(leaves), proofs = await generateProofs(root), lastChunk = chunks.slice(-1)[0]; @@ -4313,10 +4278,7 @@ }; } async function buildLayers(nodes, level = 0) { - if (nodes.length < 2) { - const root = nodes[0]; - return root; - } + if (nodes.length < 2) return nodes[0]; const nextLayer = []; for(let i = 0; i < nodes.length; i += 2)nextLayer.push(await hashBranch(nodes[i], nodes[i + 1])); return buildLayers(nextLayer, level + 1); @@ -4417,8 +4379,8 @@ await hash(left), await hash(right), await hash(offsetBuffer) - ]), updatedOutput = `${output}\n${JSON.stringify(Buffer.from(left))},${JSON.stringify(Buffer.from(right))},${offset} => ${JSON.stringify(pathHash)}`; - return debug(remainder, updatedOutput); + ]); + return debug(remainder, `${output}\n${JSON.stringify(Buffer.from(left))},${JSON.stringify(Buffer.from(right))},${offset} => ${JSON.stringify(pathHash)}`); } exports.arrayCompare = arrayCompare, exports.validatePath = validatePath, exports.debug = debug; }, @@ -4465,8 +4427,8 @@ return; } chunkIndex_ && (this.chunkIndex = chunkIndex_); - const chunk = this.transaction.getChunk(chunkIndex_ || this.chunkIndex, this.data), chunkOk = await (0, merkle_1.validatePath)(this.transaction.chunks.data_root, parseInt(chunk.offset), 0, parseInt(chunk.data_size), ArweaveUtils.b64UrlToBuffer(chunk.data_path)); - if (!chunkOk) throw Error(`Unable to validate chunk ${this.chunkIndex}`); + const chunk = this.transaction.getChunk(chunkIndex_ || this.chunkIndex, this.data); + if (!await (0, merkle_1.validatePath)(this.transaction.chunks.data_root, parseInt(chunk.offset), 0, parseInt(chunk.data_size), ArweaveUtils.b64UrlToBuffer(chunk.data_path))) throw Error(`Unable to validate chunk ${this.chunkIndex}`); const resp = await this.api.post("chunk", this.transaction.getChunk(this.chunkIndex, this.data)).catch((e)=>(console.error(e.message), { status: -1, data: { @@ -4488,8 +4450,7 @@ const resp = await api.get(`tx/${id}`); if (200 !== resp.status) throw Error(`Tx ${id} not found: ${resp.status}`); const transaction = resp.data; - transaction.data = new Uint8Array(0); - const serialized = { + return transaction.data = new Uint8Array(0), { txPosted: !0, chunkIndex: 0, lastResponseError: "", @@ -4497,7 +4458,6 @@ lastResponseStatus: 0, transaction }; - return serialized; } toJSON() { return { @@ -4510,8 +4470,7 @@ }; } async postTransaction() { - const uploadInBody = this.totalChunks <= MAX_CHUNKS_IN_BODY; - if (uploadInBody) { + if (this.totalChunks <= MAX_CHUNKS_IN_BODY) { this.transaction.data = this.data; const resp = await this.api.post("tx", this.transaction).catch((e)=>(console.error(e), { status: -1, @@ -4691,33 +4650,21 @@ } function b64UrlToString(b64UrlString) { let buffer = b64UrlToBuffer(b64UrlString); - if ("undefined" == typeof TextDecoder) { - const TextDecoder1 = __webpack_require__(9539).TextDecoder; - return new TextDecoder1("utf-8", { - fatal: !0 - }).decode(buffer); - } - return new TextDecoder("utf-8", { + return "undefined" == typeof TextDecoder ? new (__webpack_require__(9539)).TextDecoder("utf-8", { + fatal: !0 + }).decode(buffer) : new TextDecoder("utf-8", { fatal: !0 }).decode(buffer); } function bufferToString(buffer) { - if ("undefined" == typeof TextDecoder) { - const TextDecoder1 = __webpack_require__(9539).TextDecoder; - return new TextDecoder1("utf-8", { - fatal: !0 - }).decode(buffer); - } - return new TextDecoder("utf-8", { + return "undefined" == typeof TextDecoder ? new (__webpack_require__(9539)).TextDecoder("utf-8", { + fatal: !0 + }).decode(buffer) : new TextDecoder("utf-8", { fatal: !0 }).decode(buffer); } function stringToBuffer(string) { - if ("undefined" == typeof TextEncoder) { - const TextEncoder1 = __webpack_require__(9539).TextEncoder; - return new TextEncoder1().encode(string); - } - return new TextEncoder().encode(string); + return "undefined" == typeof TextEncoder ? new (__webpack_require__(9539)).TextEncoder().encode(string) : new TextEncoder().encode(string); } function stringToB64Url(string) { return bufferTob64Url(stringToBuffer(string)); @@ -4791,8 +4738,8 @@ async parseUri(siloURI) { const parsed = siloURI.match(/^([a-z0-9-_]+)\.([0-9]+)/i); if (!parsed) throw Error("Invalid Silo name, must be a name in the format of [a-z0-9]+.[0-9]+, e.g. 'bubble.7'"); - const siloName = parsed[1], hashIterations = Math.pow(2, parseInt(parsed[2])), digest = await this.hash(ArweaveUtils.stringToBuffer(siloName), hashIterations), accessKey = ArweaveUtils.bufferTob64(digest.slice(0, 15)), encryptionkey = await this.hash(digest.slice(16, 31), 1); - return new SiloResource(siloURI, accessKey, encryptionkey); + const siloName = parsed[1], hashIterations = Math.pow(2, parseInt(parsed[2])), digest = await this.hash(ArweaveUtils.stringToBuffer(siloName), hashIterations); + return new SiloResource(siloURI, ArweaveUtils.bufferTob64(digest.slice(0, 15)), await this.hash(digest.slice(16, 31), 1)); } async hash(input, iterations) { let digest = await this.crypto.hash(input); @@ -4950,8 +4897,7 @@ }); } else { try { - const existingPermissions = await window.arweaveWallet.getPermissions(); - existingPermissions.includes("SIGN_TRANSACTION") || await window.arweaveWallet.connect([ + (await window.arweaveWallet.getPermissions()).includes("SIGN_TRANSACTION") || await window.arweaveWallet.connect([ "SIGN_TRANSACTION" ]); } catch (_a) {} @@ -5068,11 +5014,11 @@ }, 2500: function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; - const encoders = __webpack_require__(6579), decoders = __webpack_require__(8307), inherits = __webpack_require__(5717), api = exports; + const encoders = __webpack_require__(6579), decoders = __webpack_require__(8307), inherits = __webpack_require__(5717); function Entity(name, body) { this.name = name, this.body = body, this.decoders = {}, this.encoders = {}; } - api.define = function(name, body) { + exports.define = function(name, body) { return new Entity(name, body); }, Entity.prototype._createNamed = function(Base) { const name = this.name; @@ -5116,9 +5062,7 @@ } } inherits(DecoderBuffer, Reporter), exports.C = DecoderBuffer, DecoderBuffer.isDecoderBuffer = function(data) { - if (data instanceof DecoderBuffer) return !0; - const isCompatible = 'object' == typeof data && Buffer.isBuffer(data.base) && 'DecoderBuffer' === data.constructor.name && 'number' == typeof data.offset && 'number' == typeof data.length && 'function' == typeof data.save && 'function' == typeof data.restore && 'function' == typeof data.isEmpty && 'function' == typeof data.readUInt8 && 'function' == typeof data.skip && 'function' == typeof data.raw; - return isCompatible; + return data instanceof DecoderBuffer || 'object' == typeof data && Buffer.isBuffer(data.base) && 'DecoderBuffer' === data.constructor.name && 'number' == typeof data.offset && 'number' == typeof data.length && 'function' == typeof data.save && 'function' == typeof data.restore && 'function' == typeof data.isEmpty && 'function' == typeof data.readUInt8 && 'function' == typeof data.skip && 'function' == typeof data.raw; }, DecoderBuffer.prototype.save = function() { return { offset: this.offset, @@ -5138,9 +5082,7 @@ }, DecoderBuffer.prototype.raw = function(save) { return this.base.slice(save ? save.offset : this.offset, this.length); }, exports.R = EncoderBuffer, EncoderBuffer.isEncoderBuffer = function(data) { - if (data instanceof EncoderBuffer) return !0; - const isCompatible = 'object' == typeof data && 'EncoderBuffer' === data.constructor.name && 'number' == typeof data.length && 'function' == typeof data.join; - return isCompatible; + return data instanceof EncoderBuffer || 'object' == typeof data && 'EncoderBuffer' === data.constructor.name && 'number' == typeof data.length && 'function' == typeof data.join; }, EncoderBuffer.prototype.join = function(out, offset) { return out || (out = Buffer.alloc(this.length)), offset || (offset = 0), 0 === this.length || (Array.isArray(this.value) ? this.value.forEach(function(item) { item.join(out, offset), offset += item.length; @@ -5267,15 +5209,12 @@ if ('object' != typeof arg || arg.constructor !== Object) return arg; const res = {}; return Object.keys(arg).forEach(function(key) { - key == (0 | key) && (key |= 0); - const value = arg[key]; - res[value] = key; + key == (0 | key) && (key |= 0), res[arg[key]] = key; }), res; })); }, overrided.forEach(function(method) { Node.prototype[method] = function() { - const state = this._baseState; - throw Error(method + ' not implemented for encoding: ' + state.enc); + throw Error(method + ' not implemented for encoding: ' + this._baseState.enc); }; }), tags.forEach(function(tag) { Node.prototype[tag] = function() { @@ -5287,8 +5226,7 @@ const state = this._baseState; return assert(null === state.use), state.use = item, this; }, Node.prototype.optional = function() { - const state = this._baseState; - return state.optional = !0, this; + return this._baseState.optional = !0, this; }, Node.prototype.def = function(val) { const state = this._baseState; return assert(null === state.default), state.default = val, state.optional = !0, this; @@ -5305,8 +5243,7 @@ const state = this._baseState; return assert(null === state.key), state.key = newKey, this; }, Node.prototype.any = function() { - const state = this._baseState; - return state.any = !0, this; + return this._baseState.any = !0, this; }, Node.prototype.choice = function(obj) { const state = this._baseState; return assert(null === state.choice), state.choice = obj, this._useArgs(Object.keys(obj).map(function(key) { @@ -5511,9 +5448,7 @@ function reverse(map) { const res = {}; return Object.keys(map).forEach(function(key) { - (0 | key) == key && (key |= 0); - const value = map[key]; - res[value] = key; + (0 | key) == key && (key |= 0), res[map[key]] = key; }), res; } exports.tagClass = { @@ -5559,9 +5494,7 @@ constants._reverse = function(map) { const res = {}; return Object.keys(map).forEach(function(key) { - (0 | key) == key && (key |= 0); - const value = map[key]; - res[value] = key; + (0 | key) == key && (key |= 0), res[map[key]] = key; }), res; }, constants.der = __webpack_require__(160); }, @@ -5699,8 +5632,7 @@ const res = buffer.readUInt8(); return buffer.isError(res) ? res : 0 !== res; }, DERNode.prototype._decodeInt = function(buffer, values) { - const raw = buffer.raw(); - let res = new bignum(raw); + let res = new bignum(buffer.raw()); return values && (res = values[res.toString(10)] || res), res; }, DERNode.prototype._use = function(entity, obj) { return 'function' == typeof entity && (entity = entity(obj)), entity._getDecoder('der').tree; @@ -5893,7 +5825,7 @@ DEREncoder.call(this, entity), this.enc = 'pem'; } inherits(PEMEncoder, DEREncoder), module.exports = PEMEncoder, PEMEncoder.prototype.encode = function(data, options) { - const buf = DEREncoder.prototype.encode.call(this, data), p = buf.toString('base64'), out = [ + const p = DEREncoder.prototype.encode.call(this, data).toString('base64'), out = [ '-----BEGIN ' + options.label + '-----' ]; for(let i = 0; i < p.length; i += 64)out.push(p.slice(i, i + 64)); @@ -8509,10 +8441,9 @@ }; } [kStore](mode) { - const transaction = this[kIDB].transaction([ + return this[kIDB].transaction([ this[kLocation] - ], mode); - return transaction.objectStore(this[kLocation]); + ], mode).objectStore(this[kLocation]); } [kOnComplete](request, callback) { const transaction = request.transaction; @@ -8537,7 +8468,8 @@ }); } _getMany(keys, options, callback) { - const store = this[kStore]('readonly'), tasks = keys.map((key)=>(next)=>{ + const store = this[kStore]('readonly'); + parallel(keys.map((key)=>(next)=>{ let request; try { request = store.get(key); @@ -8550,8 +8482,7 @@ }, request.onerror = (ev)=>{ ev.stopPropagation(), next(request.error); }; - }); - parallel(tasks, 16, callback); + }), 16, callback); } _del(key, options, callback) { let req; @@ -9298,15 +9229,11 @@ }, Buffer.prototype.readBigInt64LE = defineBigIntMethod(function(offset) { validateNumber(offset >>>= 0, 'offset'); const first = this[offset], last = this[offset + 7]; - (void 0 === first || void 0 === last) && boundsError(offset, this.length - 8); - const val = this[offset + 4] + 256 * this[offset + 5] + 65536 * this[offset + 6] + (last << 24); - return (BigInt(val) << BigInt(32)) + BigInt(first + 256 * this[++offset] + 65536 * this[++offset] + 16777216 * this[++offset]); + return (void 0 === first || void 0 === last) && boundsError(offset, this.length - 8), (BigInt(this[offset + 4] + 256 * this[offset + 5] + 65536 * this[offset + 6] + (last << 24)) << BigInt(32)) + BigInt(first + 256 * this[++offset] + 65536 * this[++offset] + 16777216 * this[++offset]); }), Buffer.prototype.readBigInt64BE = defineBigIntMethod(function(offset) { validateNumber(offset >>>= 0, 'offset'); const first = this[offset], last = this[offset + 7]; - (void 0 === first || void 0 === last) && boundsError(offset, this.length - 8); - const val = (first << 24) + 65536 * this[++offset] + 256 * this[++offset] + this[++offset]; - return (BigInt(val) << BigInt(32)) + BigInt(16777216 * this[++offset] + 65536 * this[++offset] + 256 * this[++offset] + last); + return (void 0 === first || void 0 === last) && boundsError(offset, this.length - 8), (BigInt((first << 24) + 65536 * this[++offset] + 256 * this[++offset] + this[++offset]) << BigInt(32)) + BigInt(16777216 * this[++offset] + 65536 * this[++offset] + 256 * this[++offset] + last); }), Buffer.prototype.readFloatLE = function(offset, noAssert) { return offset >>>= 0, noAssert || checkOffset(offset, 4, this.length), ieee754.read(this, offset, !0, 23, 4); }, Buffer.prototype.readFloatBE = function(offset, noAssert) { @@ -14522,8 +14449,7 @@ return write(num, stream), stream.buffer; } function decode(buffer) { - const stream = new Pipe(buffer); - return read(stream); + return read(new Pipe(buffer)); } module.exports = { encode, @@ -14565,8 +14491,7 @@ return write(num, stream), stream.buffer; } function decode(buffer) { - const stream = new Pipe(buffer); - return read(stream); + return read(new Pipe(buffer)); } module.exports = { encode, @@ -18357,32 +18282,17 @@ 11: 'data' }; _exports.immediataryParsers = { - varuint1: (stream)=>{ - const int1 = stream.read(1)[0]; - return int1; - }, - varuint32: (stream)=>{ - const int32 = leb.unsigned.read(stream); - return int32; - }, - varint32: (stream)=>{ - const int32 = leb.signed.read(stream); - return int32; - }, - varint64: (stream)=>{ - const int64 = leb.signed.read(stream); - return int64; - }, + varuint1: (stream)=>stream.read(1)[0], + varuint32: (stream)=>leb.unsigned.read(stream), + varint32: (stream)=>leb.signed.read(stream), + varint64: (stream)=>leb.signed.read(stream), uint32: (stream)=>[ ...stream.read(4) ], uint64: (stream)=>[ ...stream.read(8) ], - block_type: (stream)=>{ - const type = stream.read(1)[0]; - return LANGUAGE_TYPES[type]; - }, + block_type: (stream)=>LANGUAGE_TYPES[stream.read(1)[0]], br_table: (stream)=>{ const json = { targets: [] @@ -18445,8 +18355,7 @@ const type = stream.read(1)[0]; entry.params.push(LANGUAGE_TYPES[type]); } - const numOfReturns = leb.unsigned.readBn(stream).toNumber(); - numOfReturns && (type = stream.read(1)[0], entry.return_type = LANGUAGE_TYPES[type]), json.entries.push(entry); + leb.unsigned.readBn(stream).toNumber() && (type = stream.read(1)[0], entry.return_type = LANGUAGE_TYPES[type]), json.entries.push(entry); } return json; }, @@ -18590,14 +18499,14 @@ } }; _exports.parseOp = (stream)=>{ - const json = {}, op = stream.read(1)[0], fullName = OPCODES[op]; - let [type, name] = fullName.split('.'); + const json = {}; + let [type, name] = OPCODES[stream.read(1)[0]].split('.'); void 0 === name ? name = type : json.return_type = type, json.name = name; const immediates = OP_IMMEDIATES['const' === name ? type : name]; return immediates && (json.immediates = _exports.immediataryParsers[immediates](stream)), json; }, _exports.parse = (stream, filter)=>{ - const preramble = _exports.parsePreramble(stream), json = [ - preramble + const json = [ + _exports.parsePreramble(stream) ]; for(; !stream.end;){ const header = _exports.parseSectionHeader(stream); @@ -18628,8 +18537,7 @@ 'call' === op.name && op.immediates >= funcIndex && (op.immediates = (++op.immediates).toString()); } function meterTheMeteringStatement() { - const code = meteringStatement(0, 0); - return code.reduce((sum, op)=>sum + getCost(op.name, costTable.code), 0); + return meteringStatement(0, 0).reduce((sum, op)=>sum + getCost(op.name, costTable.code), 0); } const branchingOps = new Set([ 'grow_memory', @@ -18661,7 +18569,7 @@ function createSection(module, name) { const newSectionId = SECTION_IDS[name]; for(let index in module){ - const section = module[index], sectionId = SECTION_IDS[section.name]; + const sectionId = SECTION_IDS[module[index].name]; if (sectionId && newSectionId < sectionId) { module.splice(index, 0, { name, @@ -18708,7 +18616,7 @@ break; case 'code': for(const i in section.entries){ - const entry = section.entries[i], typeIndex = functionModule.entries[i], type = typeModule.entries[typeIndex], cost = getCost(type, costTable.type); + const entry = section.entries[i], typeIndex = functionModule.entries[i], cost = getCost(typeModule.entries[typeIndex], costTable.type); meterCodeEntry(entry, costTable.code, funcIndex, meterType, cost); } } @@ -19792,8 +19700,7 @@ async createWorker (url) { let text; try { - const worker = await startWorker(url); - return worker; + return await startWorker(url); } catch (e) { console.warn('could not load worker:', url); } @@ -19929,8 +19836,8 @@ clearArray(workers), clearArray(availableWorkers), clearArray(waitingForWorkerQueue), currentlyProcessingIdToRequestMap.clear(), numWorkers = 0, canUseWorkers = !0; } function dosDateTimeToDate(date, time) { - const day = 0x1f & date, month = (date >> 5 & 0xf) - 1, year = (date >> 9 & 0x7f) + 1980, millisecond = 0, second = (0x1f & time) * 2, minute = time >> 5 & 0x3f, hour = time >> 11 & 0x1f; - return new Date(year, month, day, hour, minute, second, millisecond); + const day = 0x1f & date, month = (date >> 5 & 0xf) - 1, second = (0x1f & time) * 2, minute = time >> 5 & 0x3f; + return new Date((date >> 9 & 0x7f) + 1980, month, day, time >> 11 & 0x1f, minute, second, 0); } class ZipEntry { constructor(reader, rawEntry){ @@ -19947,8 +19854,7 @@ return decodeBuffer(new Uint8Array(buffer)); } async json() { - const text = await this.text(); - return JSON.parse(text); + return JSON.parse(await this.text()); } } const EOCDR_WITHOUT_COMMENT_SIZE = 22, MAX_COMMENT_SIZE = 0xffff, EOCDR_SIGNATURE = 0x06054b50, ZIP64_EOCDR_SIGNATURE = 0x06064b50; @@ -19994,8 +19900,8 @@ if (getUint32LE(eocdl, 0) !== END_OF_CENTRAL_DIRECTORY_LOCATOR_SIGNATURE) throw Error('invalid zip64 end of central directory locator signature'); const zip64EocdrOffset = getUint64LE(eocdl, 8), zip64Eocdr = await readAs(reader, zip64EocdrOffset, 56); if (getUint32LE(zip64Eocdr, 0) !== ZIP64_EOCDR_SIGNATURE) throw Error('invalid zip64 end of central directory record signature'); - const entryCount = getUint64LE(zip64Eocdr, 32), centralDirectorySize = getUint64LE(zip64Eocdr, 40), centralDirectoryOffset = getUint64LE(zip64Eocdr, 48); - return readEntries(reader, centralDirectoryOffset, centralDirectorySize, entryCount, comment, commentBytes); + const entryCount = getUint64LE(zip64Eocdr, 32), centralDirectorySize = getUint64LE(zip64Eocdr, 40); + return readEntries(reader, getUint64LE(zip64Eocdr, 48), centralDirectorySize, entryCount, comment, commentBytes); } const CENTRAL_DIRECTORY_FILE_HEADER_SIGNATURE = 0x02014b50; async function readEntries(reader, centralDirectoryOffset, centralDirectorySize, rawEntryCount, comment, commentBytes) { @@ -20061,12 +19967,11 @@ } rawEntries.push(rawEntry); } - const zip = { - comment, - commentBytes - }; return { - zip, + zip: { + comment, + commentBytes + }, entries: rawEntries.map((e)=>new ZipEntry(reader, e)) }; } @@ -20092,8 +19997,8 @@ const dataView = await readAs(reader, fileDataStart, rawEntry.compressedSize); return isTypedArraySameAsArrayBuffer(dataView) ? dataView.buffer : dataView.slice().buffer; } - const typedArrayOrBlob = await readAsBlobOrTypedArray(reader, fileDataStart, rawEntry.compressedSize), result = await inflateRawAsync(typedArrayOrBlob, rawEntry.uncompressedSize); - return result; + const typedArrayOrBlob = await readAsBlobOrTypedArray(reader, fileDataStart, rawEntry.compressedSize); + return await inflateRawAsync(typedArrayOrBlob, rawEntry.uncompressedSize); } async function readEntryDataAsBlob(reader, rawEntry, type) { const { decompress, fileDataStart } = await readEntryDataHeader(reader, rawEntry); @@ -20105,8 +20010,8 @@ type }); } - const typedArrayOrBlob = await readAsBlobOrTypedArray(reader, fileDataStart, rawEntry.compressedSize), result = await inflateRawAsync(typedArrayOrBlob, rawEntry.uncompressedSize, type); - return result; + const typedArrayOrBlob = await readAsBlobOrTypedArray(reader, fileDataStart, rawEntry.compressedSize); + return await inflateRawAsync(typedArrayOrBlob, rawEntry.uncompressedSize, type); } function setOptions$1(options) { setOptions(options); @@ -20119,8 +20024,7 @@ else if ('string' == typeof source) { const req = await fetch(source); if (!req.ok) throw Error(`failed http request ${source}, status: ${req.status}: ${req.statusText}`); - const blob = await req.blob(); - reader = new BlobReader(blob); + reader = new BlobReader(await req.blob()); } else if ('function' == typeof source.getLength && 'function' == typeof source.read) reader = source; else throw Error('unsupported source type'); const totalLength = await reader.getLength(); @@ -20733,13 +20637,11 @@ return this.db.close(); } async dump() { - const result = await this.db.iterator().all(); - return result; + return await this.db.iterator().all(); } async getLastSortKey() { let lastSortKey = ''; - const keys = await this.db.keys().all(); - for (const key of keys){ + for (const key of (await this.db.keys().all())){ const sortKey = key.substring(45); sortKey.localeCompare(lastSortKey) > 0 && (lastSortKey = sortKey); } @@ -20903,20 +20805,20 @@ } async bundleInteraction(input, options) { this.logger.info('Bundle interaction input', input); - const interactionTx = await this.createInteraction(input, options.tags, CreateContract_1.emptyTransfer, options.strict, !0, options.vrf), response = await fetch(`${this._evaluationOptions.bundlerUrl}gateway/sequencer/register`, { - method: 'POST', - body: JSON.stringify(interactionTx), - headers: { - 'Accept-Encoding': 'gzip, deflate, br', - 'Content-Type': 'application/json', - Accept: 'application/json' - } - }).then((res)=>(this.logger.debug(res), res.ok ? res.json() : Promise.reject(res))).catch((error)=>{ - var _a; - throw this.logger.error(error), (null === (_a = error.body) || void 0 === _a ? void 0 : _a.message) && this.logger.error(error.body.message), Error(`Unable to bundle interaction: ${JSON.stringify(error)}`); - }); + const interactionTx = await this.createInteraction(input, options.tags, CreateContract_1.emptyTransfer, options.strict, !0, options.vrf); return { - bundlrResponse: response, + bundlrResponse: await fetch(`${this._evaluationOptions.bundlerUrl}gateway/sequencer/register`, { + method: 'POST', + body: JSON.stringify(interactionTx), + headers: { + 'Accept-Encoding': 'gzip, deflate, br', + 'Content-Type': 'application/json', + Accept: 'application/json' + } + }).then((res)=>(this.logger.debug(res), res.ok ? res.json() : Promise.reject(res))).catch((error)=>{ + var _a; + throw this.logger.error(error), (null === (_a = error.body) || void 0 === _a ? void 0 : _a.message) && this.logger.error(error.body.message), Error(`Unable to bundle interaction: ${JSON.stringify(error)}`); + }), originalTxId: interactionTx.id }; } @@ -20935,12 +20837,10 @@ const handlerResult = await this.callContract(input, void 0, void 0, tags, transfer); if ('ok' !== handlerResult.type) throw Error(`Cannot create interaction: ${handlerResult.errorMessage}`); } - vrf && tags.push({ + return vrf && tags.push({ name: SmartWeaveTags_1.SmartWeaveTags.REQUEST_VRF, value: 'true' - }); - const interactionTx = await (0, create_interaction_tx_1.createInteractionTx)(this.warp.arweave, this.signer, this._contractTxId, input, tags, transfer.target, transfer.winstonQty, bundle, reward); - return interactionTx; + }), await (0, create_interaction_tx_1.createInteractionTx)(this.warp.arweave, this.signer, this._contractTxId, input, tags, transfer.target, transfer.winstonQty, bundle, reward); } txId() { return this._contractTxId; @@ -20989,9 +20889,9 @@ return null !== (_a = this._parentContract) && void 0 !== _a && _a.rootSortKey ? upToSortKey ? this._parentContract.rootSortKey.localeCompare(upToSortKey) > 0 ? this._parentContract.rootSortKey : upToSortKey : this._parentContract.rootSortKey : upToSortKey; } async createExecutionContextFromTx(contractTxId, transaction) { - const caller = transaction.owner.address, sortKey = transaction.sortKey, baseContext = await this.createExecutionContext(contractTxId, sortKey, !0); + const caller = transaction.owner.address, sortKey = transaction.sortKey; return { - ...baseContext, + ...await this.createExecutionContext(contractTxId, sortKey, !0), caller }; } @@ -21047,11 +20947,11 @@ result: evalStateResult.cachedValue.state, txId: this._contractTxId }); - const interaction = { - input, - caller: this._parentContract.txId() - }, interactionData = { - interaction, + const interactionData = { + interaction: { + input, + caller: this._parentContract.txId() + }, interactionTx, currentTx }, result = await this.evalInteraction(interactionData, executionContext, evalStateResult.cachedValue); @@ -21102,8 +21002,8 @@ } async save(sourceData) { if (!this.signer) throw Error("Wallet not connected. Use 'connect' method first."); - const { arweave } = this.warp, source = new SourceImpl_1.SourceImpl(arweave), srcTx = await source.save(sourceData, this.signer); - return srcTx.id; + const { arweave } = this.warp, source = new SourceImpl_1.SourceImpl(arweave); + return (await source.save(sourceData, this.signer)).id; } get callingInteraction() { return this._callingInteraction; @@ -21330,7 +21230,7 @@ ])); } async zipContents(source) { - const archiver = __webpack_require__(1445), streamBuffers = __webpack_require__(4034), outputStreamBuffer = new streamBuffers.WritableStreamBuffer({ + const archiver = __webpack_require__(1445), outputStreamBuffer = new (__webpack_require__(4034)).WritableStreamBuffer({ initialSize: 1024000, incrementAmount: 1024000 }), archive = archiver('zip', { @@ -21759,8 +21659,7 @@ for(this.logger.debug('GQL page load:', benchmark.elapsed()); 403 === response.status;)this.logger.warn(`GQL rate limiting, waiting ${ArweaveGatewayInteractionsLoader._30seconds}ms before next try.`), await (0, utils_1.sleep)(ArweaveGatewayInteractionsLoader._30seconds), response = await this.arweaveWrapper.gql(ArweaveGatewayInteractionsLoader.query, variables); if (200 !== response.status) throw Error(`Unable to retrieve transactions. Arweave gateway responded with status ${response.status}.`); if (response.data.errors) throw this.logger.error(response.data.errors), Error('Error while loading interaction transactions'); - const data = response.data, txs = data.data.transactions; - return txs; + return response.data.data.transactions; } type() { return 'arweave'; @@ -22049,9 +21948,7 @@ for(let i = 0; i < missingInteractionsLength; i++){ const missingInteraction = missingInteractions[i], singleInteractionBenchmark = Benchmark_1.Benchmark.measure(); if (currentSortKey = missingInteraction.sortKey, missingInteraction.vrf && !this.verifyVrf(missingInteraction.vrf, missingInteraction.sortKey, this.arweave)) throw Error('Vrf verification failed.'); - this.logger.debug(`${(0, utils_1.indent)(depth)}[${contractDefinition.txId}][${missingInteraction.id}][${missingInteraction.block.height}]: ${missingInteractions.indexOf(missingInteraction) + 1}/${missingInteractions.length} [of all:${sortedInteractions.length}]`); - const isInteractWrite = this.tagsParser.isInteractWrite(missingInteraction, contractDefinition.txId); - if (isInteractWrite && internalWrites) { + if (this.logger.debug(`${(0, utils_1.indent)(depth)}[${contractDefinition.txId}][${missingInteraction.id}][${missingInteraction.block.height}]: ${missingInteractions.indexOf(missingInteraction) + 1}/${missingInteractions.length} [of all:${sortedInteractions.length}]`), this.tagsParser.isInteractWrite(missingInteraction, contractDefinition.txId) && internalWrites) { const writingContractTxId = this.tagsParser.getContractTag(missingInteraction); this.logger.debug(`${(0, utils_1.indent)(depth)}Internal Write - Loading writing contract`, writingContractTxId); const interactionCall = contract.getCallStack().addInteractionData({ @@ -22218,10 +22115,8 @@ wasm_bindgen__convert__closures__invoke2_mut__: null, _dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__: null } - }, wasmModule = await getWasmModule(wasmResponse, contractDefinition.srcBinary), moduleImports = WebAssembly.Module.imports(wasmModule), wbindgenImports = moduleImports.filter((imp)=>'__wbindgen_placeholder__' === imp.module).map((imp)=>imp.name), { imports, exports } = (0, rust_wasm_imports_1.rustWasmImports)(swGlobal, wbindgenImports, wasmInstanceExports, contractDefinition.metadata.dtor); - jsExports = exports, wasmInstance = await WebAssembly.instantiate(wasmModule, imports), wasmInstanceExports.exports = wasmInstance.exports; - const moduleExports = Object.keys(wasmInstance.exports); - moduleExports.forEach((moduleExport)=>{ + }, wasmModule = await getWasmModule(wasmResponse, contractDefinition.srcBinary), wbindgenImports = WebAssembly.Module.imports(wasmModule).filter((imp)=>'__wbindgen_placeholder__' === imp.module).map((imp)=>imp.name), { imports, exports } = (0, rust_wasm_imports_1.rustWasmImports)(swGlobal, wbindgenImports, wasmInstanceExports, contractDefinition.metadata.dtor); + jsExports = exports, wasmInstance = await WebAssembly.instantiate(wasmModule, imports), wasmInstanceExports.exports = wasmInstance.exports, Object.keys(wasmInstance.exports).forEach((moduleExport)=>{ moduleExport.startsWith('wasm_bindgen__convert__closures__invoke2_mut__') && (wasmInstanceExports.modifiedExports.wasm_bindgen__convert__closures__invoke2_mut__ = wasmInstance.exports[moduleExport]), moduleExport.startsWith('_dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__') && (wasmInstanceExports.modifiedExports._dyn_core__ops__function__FnMut__A____Output___R_as_wasm_bindgen__closure__WasmClosure___describe__invoke__ = wasmInstance.exports[moduleExport]); }); break; @@ -22269,7 +22164,7 @@ return new JsHandlerApi_1.JsHandlerApi(swGlobal, contractDefinition, vm.run(vmScript)); } { - const contractFunction = Function(normalizedSource), handler = contractFunction(swGlobal, bignumber_js_1.default, LoggerFactory_1.LoggerFactory.INST.create(swGlobal.contract.id)); + const handler = Function(normalizedSource)(swGlobal, bignumber_js_1.default, LoggerFactory_1.LoggerFactory.INST.create(swGlobal.contract.id)); return new JsHandlerApi_1.JsHandlerApi(swGlobal, contractDefinition, handler); } } @@ -22375,8 +22270,8 @@ return null === (_a = interactionTransaction.tags.find((tag)=>tag.name === SmartWeaveTags_1.SmartWeaveTags.CONTRACT_TX_ID)) || void 0 === _a ? void 0 : _a.value; } getContractsWithInputs(interactionTransaction) { - const result = new Map(), contractTags = interactionTransaction.tags.filter((tag)=>tag.name === SmartWeaveTags_1.SmartWeaveTags.CONTRACT_TX_ID); - return contractTags.forEach((contractTag)=>{ + const result = new Map(); + return interactionTransaction.tags.filter((tag)=>tag.name === SmartWeaveTags_1.SmartWeaveTags.CONTRACT_TX_ID).forEach((contractTag)=>{ result.set(contractTag.value, this.getInputTag(interactionTransaction, contractTag.value)); }), result; } @@ -22692,8 +22587,8 @@ switch(this.contractDefinition.srcWasmLang){ case 'assemblyscript': { - const actionPtr = this.wasmExports.__newString((0, safe_stable_stringify_1.default)(action.input)), resultPtr = this.wasmExports.handle(actionPtr), result = this.wasmExports.__getString(resultPtr); - return JSON.parse(result); + const actionPtr = this.wasmExports.__newString((0, safe_stable_stringify_1.default)(action.input)), resultPtr = this.wasmExports.handle(actionPtr); + return JSON.parse(this.wasmExports.__getString(resultPtr)); } case 'rust': { @@ -22709,10 +22604,7 @@ } } case 'go': - { - const result = await this.wasmExports.handle((0, safe_stable_stringify_1.default)(action.input)); - return JSON.parse(result); - } + return JSON.parse(await this.wasmExports.handle((0, safe_stable_stringify_1.default)(action.input))); default: throw Error(`Support for ${this.contractDefinition.srcWasmLang} not implemented yet.`); } @@ -22727,10 +22619,7 @@ case 'rust': return this.wasmExports.currentState(); case 'go': - { - const result = this.wasmExports.currentState(); - return JSON.parse(result); - } + return JSON.parse(this.wasmExports.currentState()); default: throw Error(`Support for ${this.contractDefinition.srcWasmLang} not implemented yet.`); } @@ -23047,8 +22936,7 @@ } }, 'syscall/js.stringVal': (ret_ptr, value_ptr, value_len)=>{ - const s = loadString(value_ptr, value_len); - storeValue(ret_ptr, s); + storeValue(ret_ptr, loadString(value_ptr, value_len)); }, 'syscall/js.valueGet': (retval, v_addr, p_ptr, p_len)=>{ let prop = loadString(p_ptr, p_len), value = loadValue(v_addr); @@ -23398,7 +23286,7 @@ } if (offset !== len) { 0 !== offset && (arg = arg.slice(offset)), ptr = realloc(ptr, len, len = offset + 3 * arg.length); - const view = getUint8Memory0().subarray(ptr + offset, ptr + len), ret = encodeString(arg, view); + const ret = encodeString(arg, getUint8Memory0().subarray(ptr + offset, ptr + len)); offset += ret.written; } return WASM_VECTOR_LEN = offset, ptr; @@ -23522,8 +23410,8 @@ 4742: function(__unused_webpack_module, exports) { "use strict"; function matchMutClosureDtor(source) { - const regexp = /var ret = makeMutClosure\(arg0, arg1, (\d+?), __wbg_adapter/, match = source.match(regexp); - return match[1]; + const regexp = /var ret = makeMutClosure\(arg0, arg1, (\d+?), __wbg_adapter/; + return source.match(regexp)[1]; } Object.defineProperty(exports, "__esModule", { value: !0 @@ -23749,8 +23637,7 @@ 3633: function(__unused_webpack_module, exports) { "use strict"; function getTag(tx, name) { - const tags = tx.get('tags'); - for (const tag of tags)try { + for (const tag of tx.get('tags'))try { if (tag.get('name', { decode: !0, string: !0 @@ -24050,20 +23937,20 @@ const data = JSON.stringify({ query: query, variables: variables - }), response = await fetch(`${this.baseUrl}/graphql`, { - method: 'POST', - body: data, - headers: { - 'Accept-Encoding': 'gzip, deflate, br', - 'Content-Type': 'application/json', - Accept: 'application/json' - } - }).then((res)=>res.ok ? res.json() : Promise.reject(res)).catch((error)=>{ - var _a, _b; - throw (null === (_a = error.body) || void 0 === _a ? void 0 : _a.message) && this.logger.error(error.body.message), Error(`Unable to retrieve gql page. ${error.status}: ${null === (_b = error.body) || void 0 === _b ? void 0 : _b.message}`); }); return { - data: response, + data: await fetch(`${this.baseUrl}/graphql`, { + method: 'POST', + body: data, + headers: { + 'Accept-Encoding': 'gzip, deflate, br', + 'Content-Type': 'application/json', + Accept: 'application/json' + } + }).then((res)=>res.ok ? res.json() : Promise.reject(res)).catch((error)=>{ + var _a, _b; + throw (null === (_a = error.body) || void 0 === _a ? void 0 : _a.message) && this.logger.error(error.body.message), Error(`Unable to retrieve gql page. ${error.status}: ${null === (_b = error.body) || void 0 === _b ? void 0 : _b.message}`); + }), status: 200 }; } catch (e) { @@ -24099,11 +23986,10 @@ } async doFetchInfo(url) { try { - const response = await fetch(url).then((res)=>res.ok ? res.json() : Promise.reject(res)).catch((error)=>{ + return await fetch(url).then((res)=>res.ok ? res.json() : Promise.reject(res)).catch((error)=>{ var _a, _b; throw (null === (_a = error.body) || void 0 === _a ? void 0 : _a.message) && this.logger.error(error.body.message), Error(`Unable to retrieve info. ${error.status}: ${null === (_b = error.body) || void 0 === _b ? void 0 : _b.message}`); }); - return response; } catch (e) { throw this.logger.error('Error while loading info', e), e; } @@ -24249,13 +24135,13 @@ } function __newArrayBuffer(buf) { if (null == buf) return 0; - const bufview = new Uint8Array(buf), ptr = __new(bufview.length, ARRAYBUFFER_ID), U8 = new Uint8Array(memory.buffer); - return U8.set(bufview, ptr), ptr; + const bufview = new Uint8Array(buf), ptr = __new(bufview.length, ARRAYBUFFER_ID); + return new Uint8Array(memory.buffer).set(bufview, ptr), ptr; } function __getString(ptr) { if (!ptr) return null; - const buffer = memory.buffer, id = new Uint32Array(buffer)[ptr + ID_OFFSET >>> 2]; - if (id !== STRING_ID) throw Error(`not a string: ${ptr}`); + const buffer = memory.buffer; + if (new Uint32Array(buffer)[ptr + ID_OFFSET >>> 2] !== STRING_ID) throw Error(`not a string: ${ptr}`); return getStringImpl(buffer, ptr); } function getView(alignLog2, signed, float) { @@ -24297,7 +24183,7 @@ return result; } function __getArrayView(arr) { - const U32 = new Uint32Array(memory.buffer), id = U32[arr + ID_OFFSET >>> 2], info = getArrayInfo(id), align = getValueAlign(info); + const U32 = new Uint32Array(memory.buffer), info = getArrayInfo(U32[arr + ID_OFFSET >>> 2]), align = getValueAlign(info); let buf = info & STATICARRAY ? arr : U32[arr + ARRAYBUFFERVIEW_DATASTART_OFFSET >>> 2]; const length = info & ARRAY ? U32[arr + ARRAY_LENGTH_OFFSET >>> 2] : U32[buf + SIZE_OFFSET >>> 2] >>> align; return getView(align, info & VAL_SIGNED, info & VAL_FLOAT).subarray(buf >>>= align, buf + length); diff --git a/crates/swc_ecma_minifier/tests/full/feedback-mapbox/785-e1932cc99ac3bb67/output.js b/crates/swc_ecma_minifier/tests/full/feedback-mapbox/785-e1932cc99ac3bb67/output.js index 4e6337a0d431..583c270ce567 100644 --- a/crates/swc_ecma_minifier/tests/full/feedback-mapbox/785-e1932cc99ac3bb67/output.js +++ b/crates/swc_ecma_minifier/tests/full/feedback-mapbox/785-e1932cc99ac3bb67/output.js @@ -1 +1 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[785],{840:function(t,e,n){var r;!function(i,o,a,s){"use strict";var c,u=["","webkit","Moz","MS","ms","o"],l=o.createElement("div"),h=Math.round,p=Math.abs,f=Date.now;function d(t,e,n){return setTimeout(O(t,n),e)}function v(t,e,n){return!!Array.isArray(t)&&(g(t,n[e],n),!0)}function g(t,e,n){var r;if(t){if(t.forEach)t.forEach(e,n);else if(s!==t.length)for(r=0;r\s*\(/gm,"{anonymous}()@"):"Unknown Stack Trace",o=i.console&&(i.console.warn||i.console.log);return o&&o.call(i.console,r,n),t.apply(this,arguments)}}c="function"!=typeof Object.assign?function(t){if(null==t)throw TypeError("Cannot convert undefined or null to object");for(var e=Object(t),n=1;n-1}function S(t){return t.trim().split(/\s+/g)}function T(t,e,n){if(t.indexOf&&!n)return t.indexOf(e);for(var r=0;rT(i,a)&&r.push(t[o]),i[o]=a,o++}return n&&(r=e?r.sort(function(t,n){return t[e]>n[e]}):r.sort()),r}function D(t,e){for(var n,r,i=e[0].toUpperCase()+e.slice(1),o=0;o1&&!r.firstMultiple?r.firstMultiple=U(n):1===o&&(r.firstMultiple=!1),a=r.firstInput,u=(c=r.firstMultiple)?c.center:a.center,l=n.center=q(i),n.timeStamp=f(),n.deltaTime=n.timeStamp-a.timeStamp,n.angle=X(u,l),n.distance=Y(u,l),h=n.center,d=r.offsetDelta||{},v=r.prevDelta||{},g=r.prevInput||{},(1===n.eventType||4===g.eventType)&&(v=r.prevDelta={x:g.deltaX||0,y:g.deltaY||0},d=r.offsetDelta={x:h.x,y:h.y}),n.deltaX=v.x+(h.x-d.x),n.deltaY=v.y+(h.y-d.y),n.offsetDirection=W(n.deltaX,n.deltaY),m=H(n.deltaTime,n.deltaX,n.deltaY),n.overallVelocityX=m.x,n.overallVelocityY=m.y,n.overallVelocity=p(m.x)>p(m.y)?m.x:m.y,n.scale=c?(b=c.pointers,Y(i[0],i[1],V)/Y(b[0],b[1],V)):1,n.rotation=c?(y=c.pointers,X(i[1],i[0],V)+X(y[1],y[0],V)):0,n.maxPointers=r.prevInput?n.pointers.length>r.prevInput.maxPointers?n.pointers.length:r.prevInput.maxPointers:n.pointers.length,function(t,e){var n,r,i,o,a=t.lastInterval||e,c=e.timeStamp-a.timeStamp;if(8!=e.eventType&&(c>25||s===a.velocity)){var u=e.deltaX-a.deltaX,l=e.deltaY-a.deltaY,h=H(c,u,l);r=h.x,i=h.y,n=p(h.x)>p(h.y)?h.x:h.y,o=W(u,l),t.lastInterval=e}else n=a.velocity,r=a.velocityX,i=a.velocityY,o=a.direction;e.velocity=n,e.velocityX=r,e.velocityY=i,e.direction=o}(r,n),w=t.element,M(n.srcEvent.target,w)&&(w=n.srcEvent.target),n.target=w,t.emit("hammer.input",n),t.recognize(n),t.session.prevInput=n}function U(t){for(var e=[],n=0;n=p(e)?t<0?2:4:e<0?8:16}function Y(t,e,n){n||(n=F);var r=e[n[0]]-t[n[0]],i=e[n[1]]-t[n[1]];return Math.sqrt(r*r+i*i)}function X(t,e,n){n||(n=F);var r=e[n[0]]-t[n[0]];return 180*Math.atan2(e[n[1]]-t[n[1]],r)/Math.PI}Z.prototype={handler:function(){},init:function(){this.evEl&&_(this.element,this.evEl,this.domHandler),this.evTarget&&_(this.target,this.evTarget,this.domHandler),this.evWin&&_(R(this.element),this.evWin,this.domHandler)},destroy:function(){this.evEl&&P(this.element,this.evEl,this.domHandler),this.evTarget&&P(this.target,this.evTarget,this.domHandler),this.evWin&&P(R(this.element),this.evWin,this.domHandler)}};var K={mousedown:1,mousemove:2,mouseup:4};function G(){this.evEl="mousedown",this.evWin="mousemove mouseup",this.pressed=!1,Z.apply(this,arguments)}w(G,Z,{handler:function(t){var e=K[t.type];1&e&&0===t.button&&(this.pressed=!0),2&e&&1!==t.which&&(e=4),this.pressed&&(4&e&&(this.pressed=!1),this.callback(this.manager,e,{pointers:[t],changedPointers:[t],pointerType:z,srcEvent:t}))}});var $={pointerdown:1,pointermove:2,pointerup:4,pointercancel:8,pointerout:8},J={2:N,3:"pen",4:z,5:"kinect"},Q="pointerdown",tt="pointermove pointerup pointercancel";function te(){this.evEl=Q,this.evWin=tt,Z.apply(this,arguments),this.store=this.manager.session.pointerEvents=[]}i.MSPointerEvent&&!i.PointerEvent&&(Q="MSPointerDown",tt="MSPointerMove MSPointerUp MSPointerCancel"),w(te,Z,{handler:function(t){var e=this.store,n=!1,r=$[t.type.toLowerCase().replace("ms","")],i=J[t.pointerType]||t.pointerType,o=i==N,a=T(e,t.pointerId,"pointerId");1&r&&(0===t.button||o)?a<0&&(e.push(t),a=e.length-1):12&r&&(n=!0),!(a<0)&&(e[a]=t,this.callback(this.manager,r,{pointers:e,changedPointers:[t],pointerType:i,srcEvent:t}),n&&e.splice(a,1))}});var tn={touchstart:1,touchmove:2,touchend:4,touchcancel:8};function tr(){this.evTarget="touchstart",this.evWin="touchstart touchmove touchend touchcancel",this.started=!1,Z.apply(this,arguments)}function ti(t,e){var n=k(t.touches),r=k(t.changedTouches);return 12&e&&(n=x(n.concat(r),"identifier",!0)),[n,r]}w(tr,Z,{handler:function(t){var e=tn[t.type];if(1===e&&(this.started=!0),this.started){var n=ti.call(this,t,e);12&e&&n[0].length-n[1].length==0&&(this.started=!1),this.callback(this.manager,e,{pointers:n[0],changedPointers:n[1],pointerType:N,srcEvent:t})}}});var to={touchstart:1,touchmove:2,touchend:4,touchcancel:8};function ta(){this.evTarget="touchstart touchmove touchend touchcancel",this.targetIds={},Z.apply(this,arguments)}function ts(t,e){var n=k(t.touches),r=this.targetIds;if(3&e&&1===n.length)return r[n[0].identifier]=!0,[n,n];var i,o,a=k(t.changedTouches),s=[],c=this.target;if(o=n.filter(function(t){return M(t.target,c)}),1===e)for(i=0;i-1&&r.splice(t,1)},2500)}}function th(t){for(var e=t.srcEvent.clientX,n=t.srcEvent.clientY,r=0;r-1&&this.requireFail.splice(e,1),this},hasRequireFailures:function(){return this.requireFail.length>0},canRecognizeWith:function(t){return!!this.simultaneous[t.id]},emit:function(t){var e=this,n=this.state;function r(n){e.manager.emit(n,t)}n<8&&r(e.options.event+t_(n)),r(e.options.event),t.additionalEvent&&r(t.additionalEvent),n>=8&&r(e.options.event+t_(n))},tryEmit:function(t){if(this.canEmit())return this.emit(t);this.state=32},canEmit:function(){for(var t=0;te.threshold&&i&e.direction},attrTest:function(t){return tj.prototype.attrTest.call(this,t)&&(2&this.state||!(2&this.state)&&this.directionTest(t))},emit:function(t){this.pX=t.deltaX,this.pY=t.deltaY;var e=tP(t.direction);e&&(t.additionalEvent=this.options.event+e),this._super.emit.call(this,t)}}),w(tT,tj,{defaults:{event:"pinch",threshold:0,pointers:2},getTouchAction:function(){return[tm]},attrTest:function(t){return this._super.attrTest.call(this,t)&&(Math.abs(t.scale-1)>this.options.threshold||2&this.state)},emit:function(t){if(1!==t.scale){var e=t.scale<1?"in":"out";t.additionalEvent=this.options.event+e}this._super.emit.call(this,t)}}),w(tk,tE,{defaults:{event:"press",pointers:1,time:251,threshold:9},getTouchAction:function(){return[tv]},process:function(t){var e=this.options,n=t.pointers.length===e.pointers,r=t.distancee.time;if(this._input=t,r&&n&&(!(12&t.eventType)||i)){if(1&t.eventType)this.reset(),this._timer=d(function(){this.state=8,this.tryEmit()},e.time,this);else if(4&t.eventType)return 8}else this.reset();return 32},reset:function(){clearTimeout(this._timer)},emit:function(t){8===this.state&&(t&&4&t.eventType?this.manager.emit(this.options.event+"up",t):(this._input.timeStamp=f(),this.manager.emit(this.options.event,this._input)))}}),w(tx,tj,{defaults:{event:"rotate",threshold:0,pointers:2},getTouchAction:function(){return[tm]},attrTest:function(t){return this._super.attrTest.call(this,t)&&(Math.abs(t.rotation)>this.options.threshold||2&this.state)}}),w(tD,tj,{defaults:{event:"swipe",threshold:10,velocity:.3,direction:30,pointers:1},getTouchAction:function(){return tS.prototype.getTouchAction.call(this)},attrTest:function(t){var e,n=this.options.direction;return 30&n?e=t.overallVelocity:6&n?e=t.overallVelocityX:24&n&&(e=t.overallVelocityY),this._super.attrTest.call(this,t)&&n&t.offsetDirection&&t.distance>this.options.threshold&&t.maxPointers==this.options.pointers&&p(e)>this.options.velocity&&4&t.eventType},emit:function(t){var e=tP(t.offsetDirection);e&&this.manager.emit(this.options.event+e,t),this.manager.emit(this.options.event,t)}}),w(tC,tE,{defaults:{event:"tap",pointers:1,taps:1,interval:300,time:250,threshold:9,posThreshold:10},getTouchAction:function(){return[tg]},process:function(t){var e=this.options,n=t.pointers.length===e.pointers,r=t.distance1)for(var n=1;nt.length)&&(e=t.length);for(var n=0,r=Array(e);n=-90&&e<=90,"invalid latitude");const n=512*(j+Math.log(Math.tan(S+.5*(e*T))))/(2*j);return[512*(t*T+j)/(2*j),n]}function C([t,e]){const n=2*(Math.atan(Math.exp(e/512*(2*j)-j))-S);return[(t/512*(2*j)-j)*k,n*k]}function R(t){return 2*Math.atan(.5/t)*k}function A(t){return .5/Math.tan(.5*t*T)}function I(t,e,n=0){const[r,i,o]=t;if(M(Number.isFinite(r)&&Number.isFinite(i),"invalid pixel coordinate"),Number.isFinite(o)){const t=g(e,[r,i,o,1]);return t}const a=g(e,[r,i,0,1]),s=g(e,[r,i,1,1]),c=a[2],u=s[2];return P([],a,s,c===u?0:((n||0)-c)/(u-c))}const L=Math.PI/180;function N(t,e,n){const{pixelUnprojectionMatrix:r}=t,i=g(r,[e,0,1,1]),o=g(r,[e,t.height,1,1]),a=n*t.distanceScales.unitsPerMeter[2],s=(a-i[2])/(o[2]-i[2]),c=P([],i,o,s),u=C(c);return u[2]=n,u}class z{constructor({width:t,height:e,latitude:n=0,longitude:r=0,zoom:i=0,pitch:o=0,bearing:a=0,altitude:s=null,fovy:c=null,position:u=null,nearZMultiplier:l=.02,farZMultiplier:h=1.01}={width:1,height:1}){t=t||1,e=e||1,null===c&&null===s?c=R(s=1.5):null===c?c=R(s):null===s&&(s=A(c));const p=x(i);s=Math.max(.75,s);const f=function({latitude:t,longitude:e,highPrecision:n=!1}){M(Number.isFinite(t)&&Number.isFinite(e));const r={},i=Math.cos(t*T),o=512/360,a=o/i,s=512/4003e4/i;if(r.unitsPerMeter=[s,s,s],r.metersPerUnit=[1/s,1/s,1/s],r.unitsPerDegree=[o,a,s],r.degreesPerUnit=[1/o,1/a,1/s],n){const e=T*Math.tan(t*T)/i,n=512/4003e4*e,c=n/a*s;r.unitsPerDegree2=[0,o*e/2,n],r.unitsPerMeter2=[c,0,c]}return r}({longitude:r,latitude:n}),d=D([r,n]);if(d[2]=0,u){var g,m;g=[],m=f.unitsPerMeter,g[0]=u[0]*m[0],g[1]=u[1]*m[1],g[2]=u[2]*m[2],d[0]=d[0]+g[0],d[1]=d[1]+g[1],d[2]=d[2]+g[2]}this.projectionMatrix=function({width:t,height:e,pitch:n,altitude:r,fovy:i,nearZMultiplier:o,farZMultiplier:a}){var s,c,u;const{fov:l,aspect:h,near:p,far:f}=function({width:t,height:e,fovy:n=R(1.5),altitude:r,pitch:i=0,nearZMultiplier:o=1,farZMultiplier:a=1}){void 0!==r&&(n=R(r));const s=.5*n*T,c=A(n),u=i*T,l=Math.sin(s)*c/Math.sin(Math.min(Math.max(Math.PI/2-u-s,.01),Math.PI-.01)),h=Math.sin(u)*l+c;return{fov:2*s,aspect:t/e,focalDistance:c,near:o,far:h*a}}({width:t,height:e,altitude:r,fovy:i,pitch:n,nearZMultiplier:o,farZMultiplier:a}),d=(s=[],u=1/Math.tan(l/2),s[0]=u/h,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=u,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[11]=-1,s[12]=0,s[13]=0,s[15]=0,null!=f&&f!==1/0?(c=1/(p-f),s[10]=(f+p)*c,s[14]=2*f*p*c):(s[10]=-1,s[14]=-2*p),s);return d}({width:t,height:e,pitch:o,fovy:c,nearZMultiplier:l,farZMultiplier:h}),this.viewMatrix=function({height:t,pitch:e,bearing:n,altitude:r,scale:i,center:o=null}){var a,s,c,u,l,h,p,f,d,g,m,b,y,E,_,P,M,j,S,k,x,D,C;const R=v();return w(R,R,[0,0,-r]),s=Math.sin(a=-e*T),c=Math.cos(a),u=R[4],l=R[5],h=R[6],p=R[7],f=R[8],d=R[9],g=R[10],m=R[11],R!=R&&(R[0]=R[0],R[1]=R[1],R[2]=R[2],R[3]=R[3],R[12]=R[12],R[13]=R[13],R[14]=R[14],R[15]=R[15]),R[4]=u*c+f*s,R[5]=l*c+d*s,R[6]=h*c+g*s,R[7]=p*c+m*s,R[8]=f*c-u*s,R[9]=d*c-l*s,R[10]=g*c-h*s,R[11]=m*c-p*s,y=Math.sin(b=n*T),E=Math.cos(b),_=R[0],P=R[1],M=R[2],j=R[3],S=R[4],k=R[5],x=R[6],D=R[7],R!=R&&(R[8]=R[8],R[9]=R[9],R[10]=R[10],R[11]=R[11],R[12]=R[12],R[13]=R[13],R[14]=R[14],R[15]=R[15]),R[0]=_*E+S*y,R[1]=P*E+k*y,R[2]=M*E+x*y,R[3]=j*E+D*y,R[4]=S*E-_*y,R[5]=k*E-P*y,R[6]=x*E-M*y,R[7]=D*E-j*y,O(R,R,[i/=t,i,i]),o&&w(R,R,((C=[])[0]=-o[0],C[1]=-o[1],C[2]=-o[2],C)),R}({height:e,scale:p,center:d,pitch:o,bearing:a,altitude:s}),this.width=t,this.height=e,this.scale=p,this.latitude=n,this.longitude=r,this.zoom=i,this.pitch=o,this.bearing=a,this.altitude=s,this.fovy=c,this.center=d,this.meterOffset=u||[0,0,0],this.distanceScales=f,this._initMatrices(),this.equals=this.equals.bind(this),this.project=this.project.bind(this),this.unproject=this.unproject.bind(this),this.projectPosition=this.projectPosition.bind(this),this.unprojectPosition=this.unprojectPosition.bind(this),Object.freeze(this)}_initMatrices(){var t,e,n,r,i,o,a,s,c,u,l,h,p,f,d,g,m,b,E,_,P,M,j,S,T,k,x,D,C,R;const{width:A,height:I,projectionMatrix:L,viewMatrix:N}=this,z=v();y(z,z,L),y(z,z,N),this.viewProjectionMatrix=z;const F=v();O(F,F,[A/2,-I/2,1]),w(F,F,[1,-1,0]),y(F,F,z);const V=(t=v(),e=F[0],n=F[1],r=F[2],i=F[3],o=F[4],a=F[5],s=F[6],c=F[7],u=F[8],l=F[9],h=F[10],p=F[11],f=F[12],d=F[13],g=F[14],m=F[15],b=e*a-n*o,E=e*s-r*o,_=e*c-i*o,P=n*s-r*a,M=n*c-i*a,j=r*c-i*s,S=u*d-l*f,T=u*g-h*f,k=u*m-p*f,x=l*g-h*d,D=l*m-p*d,(R=b*(C=h*m-p*g)-E*D+_*x+P*k-M*T+j*S)?(R=1/R,t[0]=(a*C-s*D+c*x)*R,t[1]=(r*D-n*C-i*x)*R,t[2]=(d*j-g*M+m*P)*R,t[3]=(h*M-l*j-p*P)*R,t[4]=(s*k-o*C-c*T)*R,t[5]=(e*C-r*k+i*T)*R,t[6]=(g*_-f*j-m*E)*R,t[7]=(u*j-h*_+p*E)*R,t[8]=(o*D-a*k+c*S)*R,t[9]=(n*k-e*D-i*S)*R,t[10]=(f*M-d*_+m*b)*R,t[11]=(l*_-u*M-p*b)*R,t[12]=(a*T-o*x-s*S)*R,t[13]=(e*x-n*T+r*S)*R,t[14]=(d*E-f*P-g*b)*R,t[15]=(u*P-l*E+h*b)*R,t):null);if(!V)throw Error("Pixel project matrix not invertible");this.pixelProjectionMatrix=F,this.pixelUnprojectionMatrix=V}equals(t){return t instanceof z&&t.width===this.width&&t.height===this.height&&E(t.projectionMatrix,this.projectionMatrix)&&E(t.viewMatrix,this.viewMatrix)}project(t,{topLeft:e=!0}={}){const n=this.projectPosition(t),r=function(t,e){const[n,r,i=0]=t;return M(Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(i)),g(e,[n,r,i,1])}(n,this.pixelProjectionMatrix),[i,o]=r,a=e?o:this.height-o;return 2===t.length?[i,a]:[i,a,r[2]]}unproject(t,{topLeft:e=!0,targetZ:n}={}){const[r,i,o]=t,a=e?i:this.height-i,s=n&&n*this.distanceScales.unitsPerMeter[2],c=I([r,a,o],this.pixelUnprojectionMatrix,s),[u,l,h]=this.unprojectPosition(c);return Number.isFinite(o)?[u,l,h]:Number.isFinite(n)?[u,l,n]:[u,l]}projectPosition(t){const[e,n]=D(t),r=(t[2]||0)*this.distanceScales.unitsPerMeter[2];return[e,n,r]}unprojectPosition(t){const[e,n]=C(t),r=(t[2]||0)*this.distanceScales.metersPerUnit[2];return[e,n,r]}projectFlat(t){return D(t)}unprojectFlat(t){return C(t)}getMapCenterByLngLatPosition({lngLat:t,pos:e}){var n;const r=I(e,this.pixelUnprojectionMatrix),i=D(t),o=_([],i,((n=[])[0]=-r[0],n[1]=-r[1],n)),a=_([],this.center,o);return C(a)}getLocationAtPoint({lngLat:t,pos:e}){return this.getMapCenterByLngLatPosition({lngLat:t,pos:e})}fitBounds(t,e={}){const{width:n,height:r}=this,{longitude:i,latitude:o,zoom:a}=function({width:t,height:e,bounds:n,minExtent:r=0,maxZoom:i=24,padding:o=0,offset:a=[0,0]}){const[[s,c],[u,l]]=n;if(Number.isFinite(o)){const t=o;o={top:t,bottom:t,left:t,right:t}}else M(Number.isFinite(o.top)&&Number.isFinite(o.bottom)&&Number.isFinite(o.left)&&Number.isFinite(o.right));const h=D([s,l<-85.051129?-85.051129:l>85.051129?85.051129:l]),p=D([u,c<-85.051129?-85.051129:c>85.051129?85.051129:c]),f=[Math.max(Math.abs(p[0]-h[0]),r),Math.max(Math.abs(p[1]-h[1]),r)],d=[t-o.left-o.right-2*Math.abs(a[0]),e-o.top-o.bottom-2*Math.abs(a[1])];M(d[0]>0&&d[1]>0);const v=d[0]/f[0],g=d[1]/f[1],m=(o.right-o.left)/2/v,y=(o.bottom-o.top)/2/g,w=[(p[0]+h[0])/2+m,(p[1]+h[1])/2+y],O=C(w),E=Math.min(i,b(Math.abs(Math.min(v,g))));return M(Number.isFinite(E)),{longitude:O[0],latitude:O[1],zoom:E}}(Object.assign({width:n,height:r,bounds:t},e));return new z({width:n,height:r,longitude:i,latitude:o,zoom:a})}getBounds(t){const e=this.getBoundingRegion(t),n=Math.min(...e.map(t=>t[0])),r=Math.max(...e.map(t=>t[0])),i=Math.min(...e.map(t=>t[1])),o=Math.max(...e.map(t=>t[1]));return[[n,i],[r,o]]}getBoundingRegion(t={}){return function(t,e=0){let n,r;const{width:i,height:o,unproject:a}=t,s={targetZ:e},c=a([0,o],s),u=a([i,o],s),l=t.fovy?.5*t.fovy*L:Math.atan(.5/t.altitude),h=(90-t.pitch)*L;return l>h-.01?(n=N(t,0,e),r=N(t,i,e)):(n=a([0,0],s),r=a([i,0],s)),[c,u,r,n]}(this,t.z||0)}}const F=["longitude","latitude","zoom"],V={curve:1.414,speed:1.2};function Z(t,e,n){var r;n=Object.assign({},V,n);const i=n.curve,o=t.zoom,a=[t.longitude,t.latitude],s=x(o),c=e.zoom,u=[e.longitude,e.latitude],l=x(c-o),h=D(a),p=D(u),f=((r=[])[0]=p[0]-h[0],r[1]=p[1]-h[1],r),d=Math.max(t.width,t.height),v=d/l,g=Math.hypot(f[0],f[1])*s,m=Math.max(g,.01),b=i*i,y=(v*v-d*d+b*b*m*m)/(2*d*b*m),w=(v*v-d*d-b*b*m*m)/(2*v*b*m),O=Math.log(Math.sqrt(y*y+1)-y),E=Math.log(Math.sqrt(w*w+1)-w);return{startZoom:o,startCenterXY:h,uDelta:f,w0:d,u1:g,S:(E-O)/i,rho:i,rho2:b,r0:O,r1:E}}var B=function(){if("undefined"!=typeof Map)return Map;function t(t,e){var n=-1;return t.some(function(t,r){return t[0]===e&&(n=r,!0)}),n}return function(){function e(){this.__entries__=[]}return Object.defineProperty(e.prototype,"size",{get:function(){return this.__entries__.length},enumerable:!0,configurable:!0}),e.prototype.get=function(e){var n=t(this.__entries__,e),r=this.__entries__[n];return r&&r[1]},e.prototype.set=function(e,n){var r=t(this.__entries__,e);~r?this.__entries__[r][1]=n:this.__entries__.push([e,n])},e.prototype.delete=function(e){var n=this.__entries__,r=t(n,e);~r&&n.splice(r,1)},e.prototype.has=function(e){return!!~t(this.__entries__,e)},e.prototype.clear=function(){this.__entries__.splice(0)},e.prototype.forEach=function(t,e){void 0===e&&(e=null);for(var n=0,r=this.__entries__;n0},t.prototype.connect_=function(){U&&!this.connected_&&(document.addEventListener("transitionend",this.onTransitionEnd_),window.addEventListener("resize",this.refresh),Y?(this.mutationsObserver_=new MutationObserver(this.refresh),this.mutationsObserver_.observe(document,{attributes:!0,childList:!0,characterData:!0,subtree:!0})):(document.addEventListener("DOMSubtreeModified",this.refresh),this.mutationEventsAdded_=!0),this.connected_=!0)},t.prototype.disconnect_=function(){U&&this.connected_&&(document.removeEventListener("transitionend",this.onTransitionEnd_),window.removeEventListener("resize",this.refresh),this.mutationsObserver_&&this.mutationsObserver_.disconnect(),this.mutationEventsAdded_&&document.removeEventListener("DOMSubtreeModified",this.refresh),this.mutationsObserver_=null,this.mutationEventsAdded_=!1,this.connected_=!1)},t.prototype.onTransitionEnd_=function(t){var e=t.propertyName,n=void 0===e?"":e;W.some(function(t){return!!~n.indexOf(t)})&&this.refresh()},t.getInstance=function(){return this.instance_||(this.instance_=new t),this.instance_},t.instance_=null,t}(),K=function(t,e){for(var n=0,r=Object.keys(e);n0},t}(),ti="undefined"!=typeof WeakMap?new WeakMap:new B,ResizeObserver=function ResizeObserver(t){if(!(this instanceof ResizeObserver))throw TypeError("Cannot call a class as a function.");if(!arguments.length)throw TypeError("1 argument required, but only 0 present.");var e=new tr(t,X.getInstance(),this);ti.set(this,e)};["observe","unobserve","disconnect"].forEach(function(t){ResizeObserver.prototype[t]=function(){var e;return(e=ti.get(this))[t].apply(e,arguments)}});var to=void 0!==q.ResizeObserver?q.ResizeObserver:ResizeObserver;function ta(t,e){if(!(t instanceof e))throw TypeError("Cannot call a class as a function")}function ts(t,e){for(var n=0;n=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:r}}throw TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o,a=!0,s=!1;return{s:function(){i=t[Symbol.iterator]()},n:function(){var t=i.next();return a=t.done,t},e:function(t){s=!0,o=t},f:function(){try{a||null==i.return||i.return()}finally{if(s)throw o}}}}function tf(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n1&&void 0!==arguments[1]?arguments[1]:"component";t.debug&&p.checkPropTypes(tm,t,"prop",e)}var tw=function(){function t(e){var n=this;if(ta(this,t),a(this,"props",tb),a(this,"width",0),a(this,"height",0),a(this,"_fireLoadEvent",function(){n.props.onLoad({type:"load",target:n._map})}),a(this,"_handleError",function(t){n.props.onError(t)}),!e.mapboxgl)throw Error("Mapbox not available");this.mapboxgl=e.mapboxgl,t.initialized||(t.initialized=!0,this._checkStyleSheet(this.mapboxgl.version)),this._initialize(e)}return tc(t,[{key:"finalize",value:function(){return this._destroy(),this}},{key:"setProps",value:function(t){return this._update(this.props,t),this}},{key:"redraw",value:function(){var t=this._map;t.style&&(t._frame&&(t._frame.cancel(),t._frame=null),t._render())}},{key:"getMap",value:function(){return this._map}},{key:"_reuse",value:function(e){this._map=t.savedMap;var n=this._map.getContainer(),r=e.container;for(r.classList.add("mapboxgl-map");n.childNodes.length>0;)r.appendChild(n.childNodes[0]);this._map._container=r,t.savedMap=null,e.mapStyle&&this._map.setStyle(tv(e.mapStyle),{diff:!1}),this._map.isStyleLoaded()?this._fireLoadEvent():this._map.once("styledata",this._fireLoadEvent)}},{key:"_create",value:function(e){if(e.reuseMaps&&t.savedMap)this._reuse(e);else{if(e.gl){var n=HTMLCanvasElement.prototype.getContext;HTMLCanvasElement.prototype.getContext=function(){return HTMLCanvasElement.prototype.getContext=n,e.gl}}var r={container:e.container,center:[0,0],zoom:8,pitch:0,bearing:0,maxZoom:24,style:tv(e.mapStyle),interactive:!1,trackResize:!1,attributionControl:e.attributionControl,preserveDrawingBuffer:e.preserveDrawingBuffer};e.transformRequest&&(r.transformRequest=e.transformRequest),this._map=new this.mapboxgl.Map(Object.assign({},r,e.mapOptions)),this._map.once("load",this._fireLoadEvent),this._map.on("error",this._handleError)}return this}},{key:"_destroy",value:function(){this._map&&(this.props.reuseMaps&&!t.savedMap?(t.savedMap=this._map,this._map.off("load",this._fireLoadEvent),this._map.off("error",this._handleError),this._map.off("styledata",this._fireLoadEvent)):this._map.remove(),this._map=null)}},{key:"_initialize",value:function(t){var e=this;ty(t=Object.assign({},tb,t),"Mapbox"),this.mapboxgl.accessToken=t.mapboxApiAccessToken||tb.mapboxApiAccessToken,this.mapboxgl.baseApiUrl=t.mapboxApiUrl,this._create(t);var n=t.container;Object.defineProperty(n,"offsetWidth",{configurable:!0,get:function(){return e.width}}),Object.defineProperty(n,"clientWidth",{configurable:!0,get:function(){return e.width}}),Object.defineProperty(n,"offsetHeight",{configurable:!0,get:function(){return e.height}}),Object.defineProperty(n,"clientHeight",{configurable:!0,get:function(){return e.height}});var r=this._map.getCanvas();r&&(r.style.outline="none"),this._updateMapViewport({},t),this._updateMapSize({},t),this.props=t}},{key:"_update",value:function(t,e){if(this._map){ty(e=Object.assign({},this.props,e),"Mapbox");var n=this._updateMapViewport(t,e),r=this._updateMapSize(t,e);this._updateMapStyle(t,e),!e.asyncRender&&(n||r)&&this.redraw(),this.props=e}}},{key:"_updateMapStyle",value:function(t,e){t.mapStyle!==e.mapStyle&&this._map.setStyle(tv(e.mapStyle),{diff:!e.preventStyleDiffing})}},{key:"_updateMapSize",value:function(t,e){var n=t.width!==e.width||t.height!==e.height;return n&&(this.width=e.width,this.height=e.height,this._map.resize()),n}},{key:"_updateMapViewport",value:function(t,e){var n=this._getViewState(t),r=this._getViewState(e),i=r.latitude!==n.latitude||r.longitude!==n.longitude||r.zoom!==n.zoom||r.pitch!==n.pitch||r.bearing!==n.bearing||r.altitude!==n.altitude;return i&&(this._map.jumpTo(this._viewStateToMapboxProps(r)),r.altitude!==n.altitude&&(this._map.transform.altitude=r.altitude)),i}},{key:"_getViewState",value:function(t){var e=t.viewState||t,n=e.longitude,r=e.latitude,i=e.zoom,o=e.pitch,a=e.bearing,s=e.altitude;return{longitude:n,latitude:r,zoom:i,pitch:void 0===o?0:o,bearing:void 0===a?0:a,altitude:void 0===s?1.5:s}}},{key:"_checkStyleSheet",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"0.47.0";if(void 0!==tu)try{var e=tu.createElement("div");if(e.className="mapboxgl-map",e.style.display="none",tu.body.appendChild(e),!("static"!==window.getComputedStyle(e).position)){var n=tu.createElement("link");n.setAttribute("rel","stylesheet"),n.setAttribute("type","text/css"),n.setAttribute("href","https://api.tiles.mapbox.com/mapbox-gl-js/v".concat(t,"/mapbox-gl.css")),tu.head.appendChild(n)}}catch(t){}}},{key:"_viewStateToMapboxProps",value:function(t){return{center:[t.longitude,t.latitude],zoom:t.zoom,bearing:t.bearing,pitch:t.pitch}}}]),t}();a(tw,"initialized",!1),a(tw,"propTypes",tm),a(tw,"defaultProps",tb),a(tw,"savedMap",null);var tO=n(6158),tE=n.n(tO);function t_(t){return Array.isArray(t)||ArrayBuffer.isView(t)}function tP(t,e,n){return Math.max(e,Math.min(n,t))}function tM(t,e,n){return t_(t)?t.map(function(t,r){return tM(t,e[r],n)}):n*e+(1-n)*t}function tj(t,e){if(!t)throw Error(e||"react-map-gl: assertion failed.")}function tS(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,r)}return n}function tT(t){for(var e=1;e0,"`scale` must be a positive number");var i=this._state,o=i.startZoom,a=i.startZoomLngLat;Number.isFinite(o)||(o=this._viewportProps.zoom,a=this._unproject(n)||this._unproject(e)),tj(a,"`startZoomLngLat` prop is required for zoom behavior to calculate where to position the map.");var s=this._calculateNewZoom({scale:r,startZoom:o||0}),c=f(new z(Object.assign({},this._viewportProps,{zoom:s})).getMapCenterByLngLatPosition({lngLat:a,pos:e}),2),u=c[0],l=c[1];return this._getUpdatedMapState({zoom:s,longitude:u,latitude:l})}},{key:"zoomEnd",value:function(){return this._getUpdatedMapState({startZoomLngLat:null,startZoom:null})}},{key:"_getUpdatedMapState",value:function(e){return new t(Object.assign({},this._viewportProps,this._state,e))}},{key:"_applyConstraints",value:function(t){var e=t.maxZoom,n=t.minZoom,r=t.zoom;t.zoom=tP(r,n,e);var i=t.maxPitch,o=t.minPitch,a=t.pitch;return t.pitch=tP(a,o,i),Object.assign(t,function({width:t,height:e,longitude:n,latitude:r,zoom:i,pitch:o=0,bearing:a=0}){(n<-180||n>180)&&(n=m(n+180,360)-180),(a<-180||a>180)&&(a=m(a+180,360)-180);const s=b(e/512);if(i<=s)i=s,r=0;else{const t=e/2/Math.pow(2,i),n=C([0,t])[1];if(re&&(r=e)}}return{width:t,height:e,longitude:n,latitude:r,zoom:i,pitch:o,bearing:a}}(t)),t}},{key:"_unproject",value:function(t){var e=new z(this._viewportProps);return t&&e.unproject(t)}},{key:"_calculateNewLngLat",value:function(t){var e=t.startPanLngLat,n=t.pos;return new z(this._viewportProps).getMapCenterByLngLatPosition({lngLat:e,pos:n})}},{key:"_calculateNewZoom",value:function(t){var e=t.scale,n=t.startZoom,r=this._viewportProps,i=r.maxZoom;return tP(n+Math.log2(e),r.minZoom,i)}},{key:"_calculateNewPitchAndBearing",value:function(t){var e=t.deltaScaleX,n=t.deltaScaleY,r=t.startBearing,i=t.startPitch;n=tP(n,-1,1);var o=this._viewportProps,a=o.minPitch,s=o.maxPitch,c=i;return n>0?c=i+n*(s-i):n<0&&(c=i-n*(a-i)),{pitch:c,bearing:r+180*e}}},{key:"_getRotationParams",value:function(t,e){var n=t[0]-e[0],r=t[1]-e[1],i=t[1],o=e[1],a=this._viewportProps,s=a.width,c=a.height,u=0;return r>0?Math.abs(c-o)>5&&(u=r/(o-c)*1.2):r<0&&o>5&&(u=1-i/o),{deltaScaleX:n/s,deltaScaleY:u=Math.min(1,Math.max(-1,u))}}}]),t}();function tC(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,r)}return n}function tR(t){for(var e=1;e1&&void 0!==arguments[1]?arguments[1]:{},n=c.current&&c.current.getMap();return n&&n.queryRenderedFeatures(t,e)}}},[]);var g=(0,h.useCallback)(function(t){var e=t.target;e===p.current&&e.scrollTo(0,0)},[]),m=v&&h.createElement(tI,{value:tF(tF({},d),{},{viewport:d.viewport||tZ(tF({map:v,props:t},a)),map:v,container:d.container||l.current})},h.createElement("div",{key:"map-overlays",className:"overlays",ref:p,style:tB,onScroll:g},t.children)),b=t.className,y=t.width,w=t.height,O=t.style,E=t.visibilityConstraints,_=Object.assign({position:"relative"},O,{width:y,height:w}),P=Object.assign({},tB,{visibility:t.visible&&function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tk;for(var n in e){var r,i=n.slice(0,3),o=(r=n.slice(3))[0].toLowerCase()+r.slice(1);if("min"===i&&t[o]e[n])return!1}return!0}(t.viewState||t,E)?"inherit":"hidden"});return h.createElement("div",{key:"map-container",ref:l,style:_},h.createElement("div",{key:"map-mapbox",ref:u,style:P,className:b}),m,!r&&!t.disableTokenWarning&&h.createElement(tH,null))});function tY(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:r}}throw TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o,a=!0,s=!1;return{s:function(){i=t[Symbol.iterator]()},n:function(){var t=i.next();return a=t.done,t},e:function(t){s=!0,o=t},f:function(){try{a||null==i.return||i.return()}finally{if(s)throw o}}}}(this.propNames||[]);try{for(r.s();!(n=r.n()).done;){var i=n.value;if(!function t(e,n){if(e===n)return!0;if(t_(e)&&t_(n)){if(e.length!==n.length)return!1;for(var r=0;r=Math.abs(e-n)}(t[i],e[i]))return!1}}catch(t){r.e(t)}finally{r.f()}return!0}},{key:"initializeProps",value:function(t,e){return{start:t,end:e}}},{key:"interpolateProps",value:function(t,e,n){tj(!1,"interpolateProps is not implemented")}},{key:"getDuration",value:function(t,e){return e.transitionDuration}}]),t}();function tK(t){if(void 0===t)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function tG(t,e){return(tG=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function t$(t,e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&tG(t,e)}function tJ(t){return(tJ="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function tQ(t,e){if(e&&("object"===tJ(e)||"function"==typeof e))return e;if(void 0!==e)throw TypeError("Derived constructors may only return object or undefined");return tK(t)}function t0(t){return(t0=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var t1={longitude:1,bearing:1};function t2(t){return Number.isFinite(t)||Array.isArray(t)}function t4(t,e,n){return t in t1&&Math.abs(n-e)>180&&(n=n<0?n+360:n-360),n}function t5(t,e){if("undefined"==typeof Symbol||null==t[Symbol.iterator]){if(Array.isArray(t)||(i=function(t,e){if(t){if("string"==typeof t)return t3(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);if("Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n)return Array.from(t);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return t3(t,e)}}(t))||e&&t&&"number"==typeof t.length){i&&(t=i);var n=0,r=function(){};return{s:r,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:r}}throw TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o,a=!0,s=!1;return{s:function(){i=t[Symbol.iterator]()},n:function(){var t=i.next();return a=t.done,t},e:function(t){s=!0,o=t},f:function(){try{a||null==i.return||i.return()}finally{if(s)throw o}}}}function t3(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:r}}throw TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o,a=!0,s=!1;return{s:function(){i=t[Symbol.iterator]()},n:function(){var t=i.next();return a=t.done,t},e:function(t){s=!0,o=t},f:function(){try{a||null==i.return||i.return()}finally{if(s)throw o}}}}function ee(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n0&&void 0!==arguments[0]?arguments[0]:{};return ta(this,r),a(tK(t=n.call(this)),"propNames",t8),t.props=Object.assign({},t7,e),t}tc(r,[{key:"initializeProps",value:function(t,e){var n,r={},i={},o=t5(t6);try{for(o.s();!(n=o.n()).done;){var a=n.value,s=t[a],c=e[a];tj(t2(s)&&t2(c),"".concat(a," must be supplied for transition")),r[a]=s,i[a]=t4(a,s,c)}}catch(t){o.e(t)}finally{o.f()}var u,l=t5(t9);try{for(l.s();!(u=l.n()).done;){var h=u.value,p=t[h]||0,f=e[h]||0;r[h]=p,i[h]=t4(h,p,f)}}catch(t){l.e(t)}finally{l.f()}return{start:r,end:i}}},{key:"interpolateProps",value:function(t,e,n){var r,i=function(t,e,n,r={}){var i,o;const a={},{startZoom:s,startCenterXY:c,uDelta:u,w0:l,u1:h,S:p,rho:f,rho2:d,r0:v}=Z(t,e,r);if(h<.01){for(const r of F){const i=t[r],o=e[r];a[r]=n*o+(1-n)*i}return a}const g=n*p,m=Math.cosh(v)/Math.cosh(v+f*g),y=s+b(1/m),w=(i=[],o=l*((Math.cosh(v)*Math.tanh(v+f*g)-Math.sinh(v))/d)/h,i[0]=u[0]*o,i[1]=u[1]*o,i);_(w,w,c);const O=C(w);return a.longitude=O[0],a.latitude=O[1],a.zoom=y,a}(t,e,n,this.props),o=t5(t9);try{for(o.s();!(r=o.n()).done;){var a=r.value;i[a]=tM(t[a],e[a],n)}}catch(t){o.e(t)}finally{o.f()}return i}},{key:"getDuration",value:function(t,e){var n=e.transitionDuration;return"auto"===n&&(n=function(t,e,n={}){let r;n=Object.assign({},V,n);const{screenSpeed:i,speed:o,maxDuration:a}=n,{S:s,rho:c}=Z(t,e,n),u=1e3*s;return r=Number.isFinite(i)?u/(i/c):u/o,Number.isFinite(a)&&r>a?0:r}(t,e,this.props)),n}}])}(tX);var en=["longitude","latitude","zoom","bearing","pitch"],er=function(t){t$(r,t);var e,n=(e=function(){if("undefined"==typeof Reflect||!Reflect.construct||Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch(t){return!1}}(),function(){var t,n=t0(r);if(e){var i=t0(this).constructor;t=Reflect.construct(n,arguments,i)}else t=n.apply(this,arguments);return tQ(this,t)});function r(){var t,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return ta(this,r),t=n.call(this),Array.isArray(e)&&(e={transitionProps:e}),t.propNames=e.transitionProps||en,e.around&&(t.around=e.around),t}return tc(r,[{key:"initializeProps",value:function(t,e){var n={},r={};if(this.around){n.around=this.around;var i=new z(t).unproject(this.around);Object.assign(r,e,{around:new z(e).project(i),aroundLngLat:i})}var o,a=et(this.propNames);try{for(a.s();!(o=a.n()).done;){var s=o.value,c=t[s],u=e[s];tj(t2(c)&&t2(u),"".concat(s," must be supplied for transition")),n[s]=c,r[s]=t4(s,c,u)}}catch(t){a.e(t)}finally{a.f()}return{start:n,end:r}}},{key:"interpolateProps",value:function(t,e,n){var r,i={},o=et(this.propNames);try{for(o.s();!(r=o.n()).done;){var a=r.value;i[a]=tM(t[a],e[a],n)}}catch(t){o.e(t)}finally{o.f()}if(e.around){var s=f(new z(Object.assign({},e,i)).getMapCenterByLngLatPosition({lngLat:e.aroundLngLat,pos:tM(t.around,e.around,n)}),2),c=s[0],u=s[1];i.longitude=c,i.latitude=u}return i}}]),r}(tX),ei=function(){},eo={BREAK:1,SNAP_TO_END:2,IGNORE:3,UPDATE:4},ea={transitionDuration:0,transitionEasing:function(t){return t},transitionInterpolator:new er,transitionInterruption:eo.BREAK,onTransitionStart:ei,onTransitionInterrupt:ei,onTransitionEnd:ei},es=function(){function t(){var e=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};ta(this,t),a(this,"_animationFrame",null),a(this,"_onTransitionFrame",function(){e._animationFrame=requestAnimationFrame(e._onTransitionFrame),e._updateViewport()}),this.props=null,this.onViewportChange=n.onViewportChange||ei,this.onStateChange=n.onStateChange||ei,this.time=n.getTime||Date.now}return tc(t,[{key:"getViewportInTransition",value:function(){return this._animationFrame?this.state.propsInTransition:null}},{key:"processViewportChange",value:function(t){var e=this.props;if(this.props=t,!e||this._shouldIgnoreViewportChange(e,t))return!1;if(this._isTransitionEnabled(t)){var n=Object.assign({},e),r=Object.assign({},t);if(this._isTransitionInProgress()&&(e.onTransitionInterrupt(),this.state.interruption===eo.SNAP_TO_END?Object.assign(n,this.state.endProps):Object.assign(n,this.state.propsInTransition),this.state.interruption===eo.UPDATE)){var i,o,a=this.time(),s=(a-this.state.startTime)/this.state.duration;r.transitionDuration=this.state.duration-(a-this.state.startTime),r.transitionEasing=(o=(i=this.state.easing)(s),function(t){return 1/(1-o)*(i(t*(1-s)+s)-o)}),r.transitionInterpolator=n.transitionInterpolator}return r.onTransitionStart(),this._triggerTransition(n,r),!0}return this._isTransitionInProgress()&&(e.onTransitionInterrupt(),this._endTransition()),!1}},{key:"_isTransitionInProgress",value:function(){return!!this._animationFrame}},{key:"_isTransitionEnabled",value:function(t){var e=t.transitionDuration,n=t.transitionInterpolator;return(e>0||"auto"===e)&&!!n}},{key:"_isUpdateDueToCurrentTransition",value:function(t){return!!this.state.propsInTransition&&this.state.interpolator.arePropsEqual(t,this.state.propsInTransition)}},{key:"_shouldIgnoreViewportChange",value:function(t,e){return!t||(this._isTransitionInProgress()?this.state.interruption===eo.IGNORE||this._isUpdateDueToCurrentTransition(e):!this._isTransitionEnabled(e)||e.transitionInterpolator.arePropsEqual(t,e))}},{key:"_triggerTransition",value:function(t,e){tj(this._isTransitionEnabled(e)),this._animationFrame&&cancelAnimationFrame(this._animationFrame);var n=e.transitionInterpolator,r=n.getDuration?n.getDuration(t,e):e.transitionDuration;if(0!==r){var i=e.transitionInterpolator.initializeProps(t,e),o={inTransition:!0,isZooming:t.zoom!==e.zoom,isPanning:t.longitude!==e.longitude||t.latitude!==e.latitude,isRotating:t.bearing!==e.bearing||t.pitch!==e.pitch};this.state={duration:r,easing:e.transitionEasing,interpolator:e.transitionInterpolator,interruption:e.transitionInterruption,startTime:this.time(),startProps:i.start,endProps:i.end,animation:null,propsInTransition:{}},this._onTransitionFrame(),this.onStateChange(o)}}},{key:"_endTransition",value:function(){this._animationFrame&&(cancelAnimationFrame(this._animationFrame),this._animationFrame=null),this.onStateChange({inTransition:!1,isZooming:!1,isPanning:!1,isRotating:!1})}},{key:"_updateViewport",value:function(){var t=this.time(),e=this.state,n=e.startTime,r=e.duration,i=e.easing,o=e.interpolator,a=e.startProps,s=e.endProps,c=!1,u=(t-n)/r;u>=1&&(u=1,c=!0),u=i(u);var l=o.interpolateProps(a,s,u),h=new tD(Object.assign({},this.props,l));this.state.propsInTransition=h.getViewportProps(),this.onViewportChange(this.state.propsInTransition,this.props),c&&(this._endTransition(),this.props.onTransitionEnd())}}]),t}();a(es,"defaultProps",ea);var ec=n(840),eu=n.n(ec);const el={mousedown:1,mousemove:2,mouseup:4};!function(t){const e=t.prototype.handler;t.prototype.handler=function(t){const n=this.store;t.button>0&&"pointerdown"===t.type&&!function(t,e){for(let n=0;ne.pointerId===t.pointerId)&&n.push(t),e.call(this,t)}}(eu().PointerEventInput),eu().MouseInput.prototype.handler=function(t){let e=el[t.type];1&e&&t.button>=0&&(this.pressed=!0),2&e&&0===t.which&&(e=4),this.pressed&&(4&e&&(this.pressed=!1),this.callback(this.manager,e,{pointers:[t],changedPointers:[t],pointerType:"mouse",srcEvent:t}))};const eh=eu().Manager;var ep=eu();const ef=ep?[[ep.Pan,{event:"tripan",pointers:3,threshold:0,enable:!1}],[ep.Rotate,{enable:!1}],[ep.Pinch,{enable:!1}],[ep.Swipe,{enable:!1}],[ep.Pan,{threshold:0,enable:!1}],[ep.Press,{enable:!1}],[ep.Tap,{event:"doubletap",taps:2,enable:!1}],[ep.Tap,{event:"anytap",enable:!1}],[ep.Tap,{enable:!1}]]:null,ed={tripan:["rotate","pinch","pan"],rotate:["pinch"],pinch:["pan"],pan:["press","doubletap","anytap","tap"],doubletap:["anytap"],anytap:["tap"]},ev={doubletap:["tap"]},eg={pointerdown:"pointerdown",pointermove:"pointermove",pointerup:"pointerup",touchstart:"pointerdown",touchmove:"pointermove",touchend:"pointerup",mousedown:"pointerdown",mousemove:"pointermove",mouseup:"pointerup"},em={KEY_EVENTS:["keydown","keyup"],MOUSE_EVENTS:["mousedown","mousemove","mouseup","mouseover","mouseout","mouseleave"],WHEEL_EVENTS:["wheel","mousewheel"]},eb={tap:"tap",anytap:"anytap",doubletap:"doubletap",press:"press",pinch:"pinch",pinchin:"pinch",pinchout:"pinch",pinchstart:"pinch",pinchmove:"pinch",pinchend:"pinch",pinchcancel:"pinch",rotate:"rotate",rotatestart:"rotate",rotatemove:"rotate",rotateend:"rotate",rotatecancel:"rotate",tripan:"tripan",tripanstart:"tripan",tripanmove:"tripan",tripanup:"tripan",tripandown:"tripan",tripanleft:"tripan",tripanright:"tripan",tripanend:"tripan",tripancancel:"tripan",pan:"pan",panstart:"pan",panmove:"pan",panup:"pan",pandown:"pan",panleft:"pan",panright:"pan",panend:"pan",pancancel:"pan",swipe:"swipe",swipeleft:"swipe",swiperight:"swipe",swipeup:"swipe",swipedown:"swipe"},ey={click:"tap",anyclick:"anytap",dblclick:"doubletap",mousedown:"pointerdown",mousemove:"pointermove",mouseup:"pointerup",mouseover:"pointerover",mouseout:"pointerout",mouseleave:"pointerleave"},ew="undefined"!=typeof navigator&&navigator.userAgent?navigator.userAgent.toLowerCase():"",eO="undefined"!=typeof window?window:n.g;void 0!==n.g?n.g:window;let eE=!1;try{const t={get passive(){return eE=!0,!0}};eO.addEventListener("test",t,t),eO.removeEventListener("test",t,t)}catch(t){}const e_=-1!==ew.indexOf("firefox"),{WHEEL_EVENTS:eP}=em,eM="wheel";class ej{constructor(t,e,n={}){this.element=t,this.callback=e,this.options=Object.assign({enable:!0},n),this.events=eP.concat(n.events||[]),this.handleEvent=this.handleEvent.bind(this),this.events.forEach(e=>t.addEventListener(e,this.handleEvent,!!eE&&{passive:!1}))}destroy(){this.events.forEach(t=>this.element.removeEventListener(t,this.handleEvent))}enableEventType(t,e){t===eM&&(this.options.enable=e)}handleEvent(t){if(!this.options.enable)return;let e=t.deltaY;eO.WheelEvent&&(e_&&t.deltaMode===eO.WheelEvent.DOM_DELTA_PIXEL&&(e/=eO.devicePixelRatio),t.deltaMode===eO.WheelEvent.DOM_DELTA_LINE&&(e*=40));const n={x:t.clientX,y:t.clientY};0!==e&&e%4.000244140625==0&&(e=Math.floor(e/4.000244140625)),t.shiftKey&&e&&(e*=.25),this._onWheel(t,-e,n)}_onWheel(t,e,n){this.callback({type:eM,center:n,delta:e,srcEvent:t,pointerType:"mouse",target:t.target})}}const{MOUSE_EVENTS:eS}=em,eT="pointermove",ek="pointerover",ex="pointerout",eD="pointerleave";class eC{constructor(t,e,n={}){this.element=t,this.callback=e,this.pressed=!1,this.options=Object.assign({enable:!0},n),this.enableMoveEvent=this.options.enable,this.enableLeaveEvent=this.options.enable,this.enableOutEvent=this.options.enable,this.enableOverEvent=this.options.enable,this.events=eS.concat(n.events||[]),this.handleEvent=this.handleEvent.bind(this),this.events.forEach(e=>t.addEventListener(e,this.handleEvent))}destroy(){this.events.forEach(t=>this.element.removeEventListener(t,this.handleEvent))}enableEventType(t,e){t===eT&&(this.enableMoveEvent=e),t===ek&&(this.enableOverEvent=e),t===ex&&(this.enableOutEvent=e),t===eD&&(this.enableLeaveEvent=e)}handleEvent(t){this.handleOverEvent(t),this.handleOutEvent(t),this.handleLeaveEvent(t),this.handleMoveEvent(t)}handleOverEvent(t){this.enableOverEvent&&"mouseover"===t.type&&this.callback({type:ek,srcEvent:t,pointerType:"mouse",target:t.target})}handleOutEvent(t){this.enableOutEvent&&"mouseout"===t.type&&this.callback({type:ex,srcEvent:t,pointerType:"mouse",target:t.target})}handleLeaveEvent(t){this.enableLeaveEvent&&"mouseleave"===t.type&&this.callback({type:eD,srcEvent:t,pointerType:"mouse",target:t.target})}handleMoveEvent(t){if(this.enableMoveEvent)switch(t.type){case"mousedown":t.button>=0&&(this.pressed=!0);break;case"mousemove":0===t.which&&(this.pressed=!1),this.pressed||this.callback({type:eT,srcEvent:t,pointerType:"mouse",target:t.target});break;case"mouseup":this.pressed=!1}}}const{KEY_EVENTS:eR}=em,eA="keydown",eI="keyup";class eL{constructor(t,e,n={}){this.element=t,this.callback=e,this.options=Object.assign({enable:!0},n),this.enableDownEvent=this.options.enable,this.enableUpEvent=this.options.enable,this.events=eR.concat(n.events||[]),this.handleEvent=this.handleEvent.bind(this),t.tabIndex=n.tabIndex||0,t.style.outline="none",this.events.forEach(e=>t.addEventListener(e,this.handleEvent))}destroy(){this.events.forEach(t=>this.element.removeEventListener(t,this.handleEvent))}enableEventType(t,e){t===eA&&(this.enableDownEvent=e),t===eI&&(this.enableUpEvent=e)}handleEvent(t){const e=t.target||t.srcElement;("INPUT"!==e.tagName||"text"!==e.type)&&"TEXTAREA"!==e.tagName&&(this.enableDownEvent&&"keydown"===t.type&&this.callback({type:eA,srcEvent:t,key:t.key,target:t.target}),this.enableUpEvent&&"keyup"===t.type&&this.callback({type:eI,srcEvent:t,key:t.key,target:t.target}))}}const eN="contextmenu";class ez{constructor(t,e,n={}){this.element=t,this.callback=e,this.options=Object.assign({enable:!0},n),this.handleEvent=this.handleEvent.bind(this),t.addEventListener("contextmenu",this.handleEvent)}destroy(){this.element.removeEventListener("contextmenu",this.handleEvent)}enableEventType(t,e){t===eN&&(this.options.enable=e)}handleEvent(t){this.options.enable&&this.callback({type:eN,center:{x:t.clientX,y:t.clientY},srcEvent:t,pointerType:"mouse",target:t.target})}}const eF={pointerdown:1,pointermove:2,pointerup:4,mousedown:1,mousemove:2,mouseup:4},eV={srcElement:"root",priority:0};class eZ{constructor(t){this.eventManager=t,this.handlers=[],this.handlersByElement=new Map,this.handleEvent=this.handleEvent.bind(this),this._active=!1}isEmpty(){return!this._active}add(t,e,n,r=!1,i=!1){const{handlers:o,handlersByElement:a}=this;n&&("object"!=typeof n||n.addEventListener)&&(n={srcElement:n}),n=n?Object.assign({},eV,n):eV;let s=a.get(n.srcElement);s||(s=[],a.set(n.srcElement,s));const c={type:t,handler:e,srcElement:n.srcElement,priority:n.priority};r&&(c.once=!0),i&&(c.passive=!0),o.push(c),this._active=this._active||!c.passive;let u=s.length-1;for(;u>=0&&!(s[u].priority>=c.priority);)u--;s.splice(u+1,0,c)}remove(t,e){const{handlers:n,handlersByElement:r}=this;for(let i=n.length-1;i>=0;i--){const o=n[i];if(o.type===t&&o.handler===e){n.splice(i,1);const t=r.get(o.srcElement);t.splice(t.indexOf(o),1),0===t.length&&r.delete(o.srcElement)}}this._active=n.some(t=>!t.passive)}handleEvent(t){if(this.isEmpty())return;const e=this._normalizeEvent(t);let n=t.srcEvent.target;for(;n&&n!==e.rootElement;){if(this._emit(e,n),e.handled)return;n=n.parentNode}this._emit(e,"root")}_emit(t,e){const n=this.handlersByElement.get(e);if(n){let e=!1;const r=()=>{t.handled=!0},i=()=>{t.handled=!0,e=!0},o=[];for(let a=0;a{const e=this.manager.get(t);e&&ed[t].forEach(t=>{e.recognizeWith(t)})}),e.recognizerOptions){const t=this.manager.get(r);if(t){const n=e.recognizerOptions[r];delete n.enable,t.set(n)}}for(const[n,r]of(this.wheelInput=new ej(t,this._onOtherEvent,{enable:!1}),this.moveInput=new eC(t,this._onOtherEvent,{enable:!1}),this.keyInput=new eL(t,this._onOtherEvent,{enable:!1,tabIndex:e.tabIndex}),this.contextmenuInput=new ez(t,this._onOtherEvent,{enable:!1}),this.events))r.isEmpty()||(this._toggleRecognizer(r.recognizerName,!0),this.manager.on(n,r.handleEvent))}destroy(){this.element&&(this.wheelInput.destroy(),this.moveInput.destroy(),this.keyInput.destroy(),this.contextmenuInput.destroy(),this.manager.destroy(),this.wheelInput=null,this.moveInput=null,this.keyInput=null,this.contextmenuInput=null,this.manager=null,this.element=null)}on(t,e,n){this._addEventHandler(t,e,n,!1)}once(t,e,n){this._addEventHandler(t,e,n,!0)}watch(t,e,n){this._addEventHandler(t,e,n,!1,!0)}off(t,e){this._removeEventHandler(t,e)}_toggleRecognizer(t,e){const{manager:n}=this;if(!n)return;const r=n.get(t);if(r&&r.options.enable!==e){r.set({enable:e});const i=ev[t];i&&!this.options.recognizers&&i.forEach(i=>{const o=n.get(i);e?(o.requireFailure(t),r.dropRequireFailure(i)):o.dropRequireFailure(t)})}this.wheelInput.enableEventType(t,e),this.moveInput.enableEventType(t,e),this.keyInput.enableEventType(t,e),this.contextmenuInput.enableEventType(t,e)}_addEventHandler(t,e,n,r,i){if("string"!=typeof t){for(const o in n=e,t)this._addEventHandler(o,t[o],n,r,i);return}const{manager:o,events:a}=this,s=ey[t]||t;let c=a.get(s);!c&&(c=new eZ(this),a.set(s,c),c.recognizerName=eb[s]||s,o&&o.on(s,c.handleEvent)),c.add(t,e,n,r,i),c.isEmpty()||this._toggleRecognizer(c.recognizerName,!0)}_removeEventHandler(t,e){if("string"!=typeof t){for(const e in t)this._removeEventHandler(e,t[e]);return}const{events:n}=this,r=ey[t]||t,i=n.get(r);if(i&&(i.remove(t,e),i.isEmpty())){const{recognizerName:t}=i;let e=!1;for(const r of n.values())if(r.recognizerName===t&&!r.isEmpty()){e=!0;break}e||this._toggleRecognizer(t,!1)}}_onBasicInput(t){const{srcEvent:e}=t,n=eg[e.type];n&&this.manager.emit(n,t)}_onOtherEvent(t){this.manager.emit(t.type,t)}}function eq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,r)}return n}function eH(t){for(var e=1;e0),a=o&&!this.state.isHovering,s=!o&&this.state.isHovering;(r||a)&&(t.features=e,r&&r(t)),a&&e4.call(this,"onMouseEnter",t),s&&e4.call(this,"onMouseLeave",t),(a||s)&&this.setState({isHovering:o})}}function e6(t){var e=this.props,n=e.onClick,r=e.onNativeClick,i=e.onDblClick,o=e.doubleClickZoom,a=[],s=i||o;switch(t.type){case"anyclick":a.push(r),s||a.push(n);break;case"click":s&&a.push(n)}(a=a.filter(Boolean)).length&&((t=e1.call(this,t)).features=e2.call(this,t.point),a.forEach(function(e){return e(t)}))}var e9=(0,h.forwardRef)(function(t,e){var n,a,s=(0,h.useContext)(tA),c=(0,h.useMemo)(function(){return t.controller||new eG},[]),u=(0,h.useMemo)(function(){return new eU(null,{touchAction:t.touchAction,recognizerOptions:t.eventRecognizerOptions})},[]),l=(0,h.useRef)(null),p=(0,h.useRef)(null),f=(0,h.useRef)({width:0,height:0,state:{isHovering:!1,isDragging:!1}}).current;f.props=t,f.map=p.current&&p.current.getMap(),f.setState=function(e){f.state=eJ(eJ({},f.state),e),l.current.style.cursor=t.getCursor(f.state)};var d=!0,v=function(t,e,r){if(d){n=[t,e,r];return}var i=f.props,o=i.onViewStateChange,a=i.onViewportChange;Object.defineProperty(t,"position",{get:function(){return[0,0,tN(f.map,t)]}}),o&&o({viewState:t,interactionState:e,oldViewState:r}),a&&a(t,e,r)};(0,h.useImperativeHandle)(e,function(){return{getMap:p.current&&p.current.getMap,queryRenderedFeatures:p.current&&p.current.queryRenderedFeatures}},[]);var g=(0,h.useMemo)(function(){return eJ(eJ({},s),{},{eventManager:u,container:s.container||l.current})},[s,l.current]);g.onViewportChange=v,g.viewport=s.viewport||tZ(f),f.viewport=g.viewport;var m=function(t){var e=t.isDragging,n=void 0!==e&&e;if(n!==f.state.isDragging&&f.setState({isDragging:n}),d){a=t;return}var r=f.props.onInteractionStateChange;r&&r(t)},b=function(){f.width&&f.height&&c.setOptions(eJ(eJ(eJ({},f.props),f.props.viewState),{},{isInteractive:!!(f.props.onViewStateChange||f.props.onViewportChange),onViewportChange:v,onStateChange:m,eventManager:u,width:f.width,height:f.height}))};(0,h.useEffect)(function(){return u.setElement(l.current),u.on({pointerdown:e5.bind(f),pointermove:e8.bind(f),pointerup:e3.bind(f),pointerleave:e4.bind(f,"onMouseOut"),click:e6.bind(f),anyclick:e6.bind(f),dblclick:e4.bind(f,"onDblClick"),wheel:e4.bind(f,"onWheel"),contextmenu:e4.bind(f,"onContextMenu")}),function(){u.destroy()}},[]),tL(function(){if(n){var t;v.apply(void 0,function(t){if(Array.isArray(t))return i(t)}(t=n)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||o(t)||function(){throw TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}())}a&&m(a)}),b();var y=t.width,w=t.height,O=t.style,E=t.getCursor,_=(0,h.useMemo)(function(){return eJ(eJ({position:"relative"},O),{},{width:y,height:w,cursor:E(f.state)})},[O,y,w,E,f.state]);return n&&f._child||(f._child=h.createElement(tI,{value:g},h.createElement("div",{key:"event-canvas",ref:l,style:_},h.createElement(tW,r({},t,{width:"100%",height:"100%",style:null,onResize:function(t){var e=t.width,n=t.height;f.width=e,f.height=n,b(),f.props.onResize({width:e,height:n})},ref:p}))))),d=!1,f._child});e9.supported=tW.supported,e9.propTypes=eQ,e9.defaultProps=e0;var e7=e9;p.string.isRequired,p.string,p.oneOf(["fill","line","symbol","circle","fill-extrusion","raster","background","heatmap","hillshade","sky"]).isRequired,p.string,p.string,p.string;var nt={captureScroll:!1,captureDrag:!0,captureClick:!0,captureDoubleClick:!0,capturePointerMove:!1},ne={captureScroll:p.bool,captureDrag:p.bool,captureClick:p.bool,captureDoubleClick:p.bool,capturePointerMove:p.bool};function nn(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=(0,h.useContext)(tA),n=(0,h.useRef)(null),r=(0,h.useRef)({props:t,state:{},context:e,containerRef:n}).current;return r.props=t,r.context=e,(0,h.useEffect)(function(){return function(t){var e=t.containerRef.current,n=t.context.eventManager;if(e&&n){var r={wheel:function(e){var n=t.props;n.captureScroll&&e.stopPropagation(),n.onScroll&&n.onScroll(e,t)},panstart:function(e){var n=t.props;n.captureDrag&&e.stopPropagation(),n.onDragStart&&n.onDragStart(e,t)},anyclick:function(e){var n=t.props;n.captureClick&&e.stopPropagation(),n.onNativeClick&&n.onNativeClick(e,t)},click:function(e){var n=t.props;n.captureClick&&e.stopPropagation(),n.onClick&&n.onClick(e,t)},dblclick:function(e){var n=t.props;n.captureDoubleClick&&e.stopPropagation(),n.onDoubleClick&&n.onDoubleClick(e,t)},pointermove:function(e){var n=t.props;n.capturePointerMove&&e.stopPropagation(),n.onPointerMove&&n.onPointerMove(e,t)}};return n.watch(r,e),function(){n.off(r)}}}(r)},[e.eventManager]),r}function nr(t){var e=t.instance,n=nn(t),r=n.context,i=n.containerRef;return e._context=r,e._containerRef=i,e._render()}var ni=function(t){t$(i,t);var e,n=(e=function(){if("undefined"==typeof Reflect||!Reflect.construct||Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch(t){return!1}}(),function(){var t,n=t0(i);if(e){var r=t0(this).constructor;t=Reflect.construct(n,arguments,r)}else t=n.apply(this,arguments);return tQ(this,t)});function i(){var t;ta(this,i);for(var e=arguments.length,r=Array(e),o=0;o2&&void 0!==arguments[2]?arguments[2]:"x";if(null===t)return e;var r="x"===n?t.offsetWidth:t.offsetHeight;return nf(e/100*r)/r*100};function nv(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,r)}return n}var ng=Object.assign({},ns,{className:p.string,longitude:p.number.isRequired,latitude:p.number.isRequired,style:p.object}),nm=Object.assign({},nc,{className:""});function nb(t){var e,n,r,i,o,s,c,u=(n=(e=f((0,h.useState)(null),2))[0],r=e[1],o=(i=f((0,h.useState)(null),2))[0],s=i[1],(c=nn(na(na({},t),{},{onDragStart:nh}))).callbacks=t,c.state.dragPos=n,c.state.setDragPos=r,c.state.dragOffset=o,c.state.setDragOffset=s,(0,h.useEffect)(function(){return function(t){var e=t.context.eventManager;if(e&&t.state.dragPos){var n={panmove:function(e){return function(t,e){var n=e.props,r=e.callbacks,i=e.state,o=e.context;t.stopPropagation();var a=nu(t);i.setDragPos(a);var s=i.dragOffset;if(r.onDrag&&s){var c=Object.assign({},t);c.lngLat=nl(a,s,n,o),r.onDrag(c)}}(e,t)},panend:function(e){return function(t,e){var n=e.props,r=e.callbacks,i=e.state,o=e.context;t.stopPropagation();var a=i.dragPos,s=i.dragOffset;if(i.setDragPos(null),i.setDragOffset(null),r.onDragEnd&&a&&s){var c=Object.assign({},t);c.lngLat=nl(a,s,n,o),r.onDragEnd(c)}}(e,t)},pancancel:function(e){var n;return n=t.state,void(e.stopPropagation(),n.setDragPos(null),n.setDragOffset(null))}};return e.watch(n),function(){e.off(n)}}}(c)},[c.context.eventManager,!!n]),c),l=u.state,p=u.containerRef,d=t.children,v=t.className,g=t.draggable,m=t.style,b=l.dragPos,y=function(t){var e=t.props,n=t.state,r=t.context,i=e.longitude,o=e.latitude,a=e.offsetLeft,s=e.offsetTop,c=n.dragPos,u=n.dragOffset,l=r.viewport,h=r.map;if(c&&u)return[c[0]+u[0],c[1]+u[1]];var p=tN(h,{longitude:i,latitude:o}),d=f(l.project([i,o,p]),2),v=d[0],g=d[1];return[v+=a,g+=s]}(u),w=f(y,2),O=w[0],E=w[1],_="translate(".concat(nf(O),"px, ").concat(nf(E),"px)"),P=g?b?"grabbing":"grab":"auto",M=(0,h.useMemo)(function(){var t=function(t){for(var e=1;e0){var g=p,m=v;for(p=0;p<=1;p+=.5)d=(f=n-p*a)+a,(v=Math.max(0,u-f)+Math.max(0,d-i+u))0){var E=h,_=O;for(h=0;h<=1;h+=b)w=(y=e-h*o)+o,(O=Math.max(0,u-y)+Math.max(0,w-r+u))<_&&(_=O,E=h);h=E}return nw.find(function(t){var e=ny[t];return e.x===h&&e.y===p})||s}({x:r,y:i,anchor:o,padding:s,width:S.width,height:S.height,selfWidth:e.clientWidth,selfHeight:e.clientHeight}):o),z=(c=M.current,l=(u=f(L,3))[0],p=u[1],d=u[2],v=t.offsetLeft,g=t.offsetTop,m=t.sortByDepth,y=nd(c,-(100*(b=ny[N]).x)),w=nd(c,-(100*b.y),"y"),O={position:"absolute",transform:"\n translate(".concat(y,"%, ").concat(w,"%)\n translate(").concat(nf(l+v),"px, ").concat(nf(p+g),"px)\n "),display:void 0,zIndex:void 0},m&&(d>1||d<-1||l<0||l>S.width||p<0||p>S.height?O.display="none":O.zIndex=Math.floor((1-d)/2*1e5)),O),F=(0,h.useCallback)(function(t){_.props.onClose();var e=_.context.eventManager;e&&e.once("click",function(t){return t.stopPropagation()},t.target)},[]);return h.createElement("div",{className:"mapboxgl-popup mapboxgl-popup-anchor-".concat(N," ").concat(k),style:z,ref:M},h.createElement("div",{key:"tip",className:"mapboxgl-popup-tip",style:{borderWidth:C}}),h.createElement("div",{key:"content",ref:E,className:"mapboxgl-popup-content"},R&&h.createElement("button",{key:"close-button",className:"mapboxgl-popup-close-button",type:"button",onClick:F},"×"),A))}function nP(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,r)}return n}n_.propTypes=nO,n_.defaultProps=nE,h.memo(n_);var nM=Object.assign({},ne,{toggleLabel:p.string,className:p.string,style:p.object,compact:p.bool,customAttribution:p.oneOfType([p.string,p.arrayOf(p.string)])}),nj=Object.assign({},nt,{className:"",toggleLabel:"Toggle Attribution"});function nS(t){var e=nn(t),n=e.context,r=e.containerRef,i=(0,h.useRef)(null),o=f((0,h.useState)(!1),2),s=o[0],c=o[1];(0,h.useEffect)(function(){var e,o,a,s,c,u;return n.map&&(o={customAttribution:t.customAttribution},a=n.map,s=r.current,c=i.current,(u=new(tE()).AttributionControl(o))._map=a,u._container=s,u._innerContainer=c,u._updateAttributions(),u._updateEditLink(),a.on("styledata",u._updateData),a.on("sourcedata",u._updateData),e=u),function(){var t;return e&&void((t=e)._map.off("styledata",t._updateData),t._map.off("sourcedata",t._updateData))}},[n.map]);var u=void 0===t.compact?n.viewport.width<=640:t.compact;(0,h.useEffect)(function(){!u&&s&&c(!1)},[u]);var l=(0,h.useCallback)(function(){return c(function(t){return!t})},[]),p=(0,h.useMemo)(function(){return function(t){for(var e=1;ea)return 1}return 0}(o.map.version,"1.6.0")>=0?2:1:2},[o.map]),n=o.viewport.bearing,r={transform:"rotate(".concat(-n,"deg)")},2===e?h.createElement("span",{className:"mapboxgl-ctrl-icon","aria-hidden":"true",style:r}):h.createElement("span",{className:"mapboxgl-ctrl-compass-arrow",style:r})))))}function nq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,r)}return n}nU.propTypes=nF,nU.defaultProps=nV,h.memo(nU);var nH=Object.assign({},ne,{className:p.string,style:p.object,maxWidth:p.number,unit:p.oneOf(["imperial","metric","nautical"])}),nW=Object.assign({},nt,{className:"",maxWidth:100,unit:"metric"});function nY(t){var e=nn(t),n=e.context,r=e.containerRef,i=f((0,h.useState)(null),2),o=i[0],s=i[1];(0,h.useEffect)(function(){if(n.map){var t=new(tE()).ScaleControl;t._map=n.map,t._container=r.current,s(t)}},[n.map]),o&&(o.options=t,o._onMove());var c=(0,h.useMemo)(function(){return function(t){for(var e=1;e\s*\(/gm,"{anonymous}()@"):"Unknown Stack Trace",o=i.console&&(i.console.warn||i.console.log);return o&&o.call(i.console,r,n),t.apply(this,arguments)}}c="function"!=typeof Object.assign?function(t){if(null==t)throw TypeError("Cannot convert undefined or null to object");for(var e=Object(t),n=1;n-1}function S(t){return t.trim().split(/\s+/g)}function T(t,e,n){if(t.indexOf&&!n)return t.indexOf(e);for(var r=0;rT(i,a)&&r.push(t[o]),i[o]=a,o++}return n&&(r=e?r.sort(function(t,n){return t[e]>n[e]}):r.sort()),r}function D(t,e){for(var n,r,i=e[0].toUpperCase()+e.slice(1),o=0;o1&&!r.firstMultiple?r.firstMultiple=U(n):1===o&&(r.firstMultiple=!1),a=r.firstInput,u=(c=r.firstMultiple)?c.center:a.center,l=n.center=q(i),n.timeStamp=f(),n.deltaTime=n.timeStamp-a.timeStamp,n.angle=X(u,l),n.distance=Y(u,l),h=n.center,d=r.offsetDelta||{},v=r.prevDelta||{},g=r.prevInput||{},(1===n.eventType||4===g.eventType)&&(v=r.prevDelta={x:g.deltaX||0,y:g.deltaY||0},d=r.offsetDelta={x:h.x,y:h.y}),n.deltaX=v.x+(h.x-d.x),n.deltaY=v.y+(h.y-d.y),n.offsetDirection=W(n.deltaX,n.deltaY),m=H(n.deltaTime,n.deltaX,n.deltaY),n.overallVelocityX=m.x,n.overallVelocityY=m.y,n.overallVelocity=p(m.x)>p(m.y)?m.x:m.y,n.scale=c?(b=c.pointers,Y(i[0],i[1],V)/Y(b[0],b[1],V)):1,n.rotation=c?(y=c.pointers,X(i[1],i[0],V)+X(y[1],y[0],V)):0,n.maxPointers=r.prevInput?n.pointers.length>r.prevInput.maxPointers?n.pointers.length:r.prevInput.maxPointers:n.pointers.length,function(t,e){var n,r,i,o,a=t.lastInterval||e,c=e.timeStamp-a.timeStamp;if(8!=e.eventType&&(c>25||s===a.velocity)){var u=e.deltaX-a.deltaX,l=e.deltaY-a.deltaY,h=H(c,u,l);r=h.x,i=h.y,n=p(h.x)>p(h.y)?h.x:h.y,o=W(u,l),t.lastInterval=e}else n=a.velocity,r=a.velocityX,i=a.velocityY,o=a.direction;e.velocity=n,e.velocityX=r,e.velocityY=i,e.direction=o}(r,n),w=t.element,M(n.srcEvent.target,w)&&(w=n.srcEvent.target),n.target=w,t.emit("hammer.input",n),t.recognize(n),t.session.prevInput=n}function U(t){for(var e=[],n=0;n=p(e)?t<0?2:4:e<0?8:16}function Y(t,e,n){n||(n=F);var r=e[n[0]]-t[n[0]],i=e[n[1]]-t[n[1]];return Math.sqrt(r*r+i*i)}function X(t,e,n){n||(n=F);var r=e[n[0]]-t[n[0]];return 180*Math.atan2(e[n[1]]-t[n[1]],r)/Math.PI}Z.prototype={handler:function(){},init:function(){this.evEl&&_(this.element,this.evEl,this.domHandler),this.evTarget&&_(this.target,this.evTarget,this.domHandler),this.evWin&&_(R(this.element),this.evWin,this.domHandler)},destroy:function(){this.evEl&&P(this.element,this.evEl,this.domHandler),this.evTarget&&P(this.target,this.evTarget,this.domHandler),this.evWin&&P(R(this.element),this.evWin,this.domHandler)}};var K={mousedown:1,mousemove:2,mouseup:4};function G(){this.evEl="mousedown",this.evWin="mousemove mouseup",this.pressed=!1,Z.apply(this,arguments)}w(G,Z,{handler:function(t){var e=K[t.type];1&e&&0===t.button&&(this.pressed=!0),2&e&&1!==t.which&&(e=4),this.pressed&&(4&e&&(this.pressed=!1),this.callback(this.manager,e,{pointers:[t],changedPointers:[t],pointerType:z,srcEvent:t}))}});var $={pointerdown:1,pointermove:2,pointerup:4,pointercancel:8,pointerout:8},J={2:N,3:"pen",4:z,5:"kinect"},Q="pointerdown",tt="pointermove pointerup pointercancel";function te(){this.evEl=Q,this.evWin=tt,Z.apply(this,arguments),this.store=this.manager.session.pointerEvents=[]}i.MSPointerEvent&&!i.PointerEvent&&(Q="MSPointerDown",tt="MSPointerMove MSPointerUp MSPointerCancel"),w(te,Z,{handler:function(t){var e=this.store,n=!1,r=$[t.type.toLowerCase().replace("ms","")],i=J[t.pointerType]||t.pointerType,o=i==N,a=T(e,t.pointerId,"pointerId");1&r&&(0===t.button||o)?a<0&&(e.push(t),a=e.length-1):12&r&&(n=!0),!(a<0)&&(e[a]=t,this.callback(this.manager,r,{pointers:e,changedPointers:[t],pointerType:i,srcEvent:t}),n&&e.splice(a,1))}});var tn={touchstart:1,touchmove:2,touchend:4,touchcancel:8};function tr(){this.evTarget="touchstart",this.evWin="touchstart touchmove touchend touchcancel",this.started=!1,Z.apply(this,arguments)}function ti(t,e){var n=k(t.touches),r=k(t.changedTouches);return 12&e&&(n=x(n.concat(r),"identifier",!0)),[n,r]}w(tr,Z,{handler:function(t){var e=tn[t.type];if(1===e&&(this.started=!0),this.started){var n=ti.call(this,t,e);12&e&&n[0].length-n[1].length==0&&(this.started=!1),this.callback(this.manager,e,{pointers:n[0],changedPointers:n[1],pointerType:N,srcEvent:t})}}});var to={touchstart:1,touchmove:2,touchend:4,touchcancel:8};function ta(){this.evTarget="touchstart touchmove touchend touchcancel",this.targetIds={},Z.apply(this,arguments)}function ts(t,e){var n=k(t.touches),r=this.targetIds;if(3&e&&1===n.length)return r[n[0].identifier]=!0,[n,n];var i,o,a=k(t.changedTouches),s=[],c=this.target;if(o=n.filter(function(t){return M(t.target,c)}),1===e)for(i=0;i-1&&r.splice(t,1)},2500)}}function th(t){for(var e=t.srcEvent.clientX,n=t.srcEvent.clientY,r=0;r-1&&this.requireFail.splice(e,1),this},hasRequireFailures:function(){return this.requireFail.length>0},canRecognizeWith:function(t){return!!this.simultaneous[t.id]},emit:function(t){var e=this,n=this.state;function r(n){e.manager.emit(n,t)}n<8&&r(e.options.event+t_(n)),r(e.options.event),t.additionalEvent&&r(t.additionalEvent),n>=8&&r(e.options.event+t_(n))},tryEmit:function(t){if(this.canEmit())return this.emit(t);this.state=32},canEmit:function(){for(var t=0;te.threshold&&i&e.direction},attrTest:function(t){return tj.prototype.attrTest.call(this,t)&&(2&this.state||!(2&this.state)&&this.directionTest(t))},emit:function(t){this.pX=t.deltaX,this.pY=t.deltaY;var e=tP(t.direction);e&&(t.additionalEvent=this.options.event+e),this._super.emit.call(this,t)}}),w(tT,tj,{defaults:{event:"pinch",threshold:0,pointers:2},getTouchAction:function(){return[tm]},attrTest:function(t){return this._super.attrTest.call(this,t)&&(Math.abs(t.scale-1)>this.options.threshold||2&this.state)},emit:function(t){if(1!==t.scale){var e=t.scale<1?"in":"out";t.additionalEvent=this.options.event+e}this._super.emit.call(this,t)}}),w(tk,tE,{defaults:{event:"press",pointers:1,time:251,threshold:9},getTouchAction:function(){return[tv]},process:function(t){var e=this.options,n=t.pointers.length===e.pointers,r=t.distancee.time;if(this._input=t,r&&n&&(!(12&t.eventType)||i)){if(1&t.eventType)this.reset(),this._timer=d(function(){this.state=8,this.tryEmit()},e.time,this);else if(4&t.eventType)return 8}else this.reset();return 32},reset:function(){clearTimeout(this._timer)},emit:function(t){8===this.state&&(t&&4&t.eventType?this.manager.emit(this.options.event+"up",t):(this._input.timeStamp=f(),this.manager.emit(this.options.event,this._input)))}}),w(tx,tj,{defaults:{event:"rotate",threshold:0,pointers:2},getTouchAction:function(){return[tm]},attrTest:function(t){return this._super.attrTest.call(this,t)&&(Math.abs(t.rotation)>this.options.threshold||2&this.state)}}),w(tD,tj,{defaults:{event:"swipe",threshold:10,velocity:.3,direction:30,pointers:1},getTouchAction:function(){return tS.prototype.getTouchAction.call(this)},attrTest:function(t){var e,n=this.options.direction;return 30&n?e=t.overallVelocity:6&n?e=t.overallVelocityX:24&n&&(e=t.overallVelocityY),this._super.attrTest.call(this,t)&&n&t.offsetDirection&&t.distance>this.options.threshold&&t.maxPointers==this.options.pointers&&p(e)>this.options.velocity&&4&t.eventType},emit:function(t){var e=tP(t.offsetDirection);e&&this.manager.emit(this.options.event+e,t),this.manager.emit(this.options.event,t)}}),w(tC,tE,{defaults:{event:"tap",pointers:1,taps:1,interval:300,time:250,threshold:9,posThreshold:10},getTouchAction:function(){return[tg]},process:function(t){var e=this.options,n=t.pointers.length===e.pointers,r=t.distance1)for(var n=1;nt.length)&&(e=t.length);for(var n=0,r=Array(e);n=-90&&e<=90,"invalid latitude");const n=512*(j+Math.log(Math.tan(S+.5*(e*T))))/(2*j);return[512*(t*T+j)/(2*j),n]}function C([t,e]){const n=2*(Math.atan(Math.exp(e/512*(2*j)-j))-S);return[(t/512*(2*j)-j)*k,n*k]}function R(t){return 2*Math.atan(.5/t)*k}function A(t){return .5/Math.tan(.5*t*T)}function I(t,e,n=0){const[r,i,o]=t;if(M(Number.isFinite(r)&&Number.isFinite(i),"invalid pixel coordinate"),Number.isFinite(o))return g(e,[r,i,o,1]);const a=g(e,[r,i,0,1]),s=g(e,[r,i,1,1]),c=a[2],u=s[2];return P([],a,s,c===u?0:((n||0)-c)/(u-c))}const L=Math.PI/180;function N(t,e,n){const{pixelUnprojectionMatrix:r}=t,i=g(r,[e,0,1,1]),o=g(r,[e,t.height,1,1]),a=(n*t.distanceScales.unitsPerMeter[2]-i[2])/(o[2]-i[2]),s=C(P([],i,o,a));return s[2]=n,s}class z{constructor({width:t,height:e,latitude:n=0,longitude:r=0,zoom:i=0,pitch:o=0,bearing:a=0,altitude:s=null,fovy:c=null,position:u=null,nearZMultiplier:l=.02,farZMultiplier:h=1.01}={width:1,height:1}){t=t||1,e=e||1,null===c&&null===s?c=R(s=1.5):null===c?c=R(s):null===s&&(s=A(c));const p=x(i);s=Math.max(.75,s);const f=function({latitude:t,longitude:e,highPrecision:n=!1}){M(Number.isFinite(t)&&Number.isFinite(e));const r={},i=Math.cos(t*T),o=512/360,a=512/360/i,s=512/4003e4/i;if(r.unitsPerMeter=[s,s,s],r.metersPerUnit=[1/s,1/s,1/s],r.unitsPerDegree=[o,a,s],r.degreesPerUnit=[1/o,1/a,1/s],n){const e=T*Math.tan(t*T)/i,n=512/4003e4*e,c=n/a*s;r.unitsPerDegree2=[0,o*e/2,n],r.unitsPerMeter2=[c,0,c]}return r}({longitude:r,latitude:n}),d=D([r,n]);if(d[2]=0,u){var g,m;g=[],m=f.unitsPerMeter,g[0]=u[0]*m[0],g[1]=u[1]*m[1],g[2]=u[2]*m[2],d[0]=d[0]+g[0],d[1]=d[1]+g[1],d[2]=d[2]+g[2]}this.projectionMatrix=function({width:t,height:e,pitch:n,altitude:r,fovy:i,nearZMultiplier:o,farZMultiplier:a}){var s,c,u;const{fov:l,aspect:h,near:p,far:f}=function({width:t,height:e,fovy:n=R(1.5),altitude:r,pitch:i=0,nearZMultiplier:o=1,farZMultiplier:a=1}){void 0!==r&&(n=R(r));const s=.5*n*T,c=A(n),u=i*T,l=Math.sin(s)*c/Math.sin(Math.min(Math.max(Math.PI/2-u-s,.01),Math.PI-.01)),h=Math.sin(u)*l+c;return{fov:2*s,aspect:t/e,focalDistance:c,near:o,far:h*a}}({width:t,height:e,altitude:r,fovy:i,pitch:n,nearZMultiplier:o,farZMultiplier:a});return s=[],u=1/Math.tan(l/2),s[0]=u/h,s[1]=0,s[2]=0,s[3]=0,s[4]=0,s[5]=u,s[6]=0,s[7]=0,s[8]=0,s[9]=0,s[11]=-1,s[12]=0,s[13]=0,s[15]=0,null!=f&&f!==1/0?(c=1/(p-f),s[10]=(f+p)*c,s[14]=2*f*p*c):(s[10]=-1,s[14]=-2*p),s}({width:t,height:e,pitch:o,fovy:c,nearZMultiplier:l,farZMultiplier:h}),this.viewMatrix=function({height:t,pitch:e,bearing:n,altitude:r,scale:i,center:o=null}){var a,s,c,u,l,h,p,f,d,g,m,b,y,E,_,P,M,j,S,k,x,D,C;const R=v();return w(R,R,[0,0,-r]),s=Math.sin(a=-e*T),c=Math.cos(a),u=R[4],l=R[5],h=R[6],p=R[7],f=R[8],d=R[9],g=R[10],m=R[11],R!=R&&(R[0]=R[0],R[1]=R[1],R[2]=R[2],R[3]=R[3],R[12]=R[12],R[13]=R[13],R[14]=R[14],R[15]=R[15]),R[4]=u*c+f*s,R[5]=l*c+d*s,R[6]=h*c+g*s,R[7]=p*c+m*s,R[8]=f*c-u*s,R[9]=d*c-l*s,R[10]=g*c-h*s,R[11]=m*c-p*s,y=Math.sin(b=n*T),E=Math.cos(b),_=R[0],P=R[1],M=R[2],j=R[3],S=R[4],k=R[5],x=R[6],D=R[7],R!=R&&(R[8]=R[8],R[9]=R[9],R[10]=R[10],R[11]=R[11],R[12]=R[12],R[13]=R[13],R[14]=R[14],R[15]=R[15]),R[0]=_*E+S*y,R[1]=P*E+k*y,R[2]=M*E+x*y,R[3]=j*E+D*y,R[4]=S*E-_*y,R[5]=k*E-P*y,R[6]=x*E-M*y,R[7]=D*E-j*y,O(R,R,[i/=t,i,i]),o&&w(R,R,((C=[])[0]=-o[0],C[1]=-o[1],C[2]=-o[2],C)),R}({height:e,scale:p,center:d,pitch:o,bearing:a,altitude:s}),this.width=t,this.height=e,this.scale=p,this.latitude=n,this.longitude=r,this.zoom=i,this.pitch=o,this.bearing=a,this.altitude=s,this.fovy=c,this.center=d,this.meterOffset=u||[0,0,0],this.distanceScales=f,this._initMatrices(),this.equals=this.equals.bind(this),this.project=this.project.bind(this),this.unproject=this.unproject.bind(this),this.projectPosition=this.projectPosition.bind(this),this.unprojectPosition=this.unprojectPosition.bind(this),Object.freeze(this)}_initMatrices(){var t,e,n,r,i,o,a,s,c,u,l,h,p,f,d,g,m,b,E,_,P,M,j,S,T,k,x,D,C,R;const{width:A,height:I,projectionMatrix:L,viewMatrix:N}=this,z=v();y(z,z,L),y(z,z,N),this.viewProjectionMatrix=z;const F=v();O(F,F,[A/2,-I/2,1]),w(F,F,[1,-1,0]),y(F,F,z);const V=(t=v(),e=F[0],n=F[1],r=F[2],i=F[3],o=F[4],a=F[5],s=F[6],c=F[7],u=F[8],l=F[9],h=F[10],p=F[11],f=F[12],d=F[13],g=F[14],m=F[15],b=e*a-n*o,E=e*s-r*o,_=e*c-i*o,P=n*s-r*a,M=n*c-i*a,j=r*c-i*s,S=u*d-l*f,T=u*g-h*f,k=u*m-p*f,x=l*g-h*d,D=l*m-p*d,(R=b*(C=h*m-p*g)-E*D+_*x+P*k-M*T+j*S)?(R=1/R,t[0]=(a*C-s*D+c*x)*R,t[1]=(r*D-n*C-i*x)*R,t[2]=(d*j-g*M+m*P)*R,t[3]=(h*M-l*j-p*P)*R,t[4]=(s*k-o*C-c*T)*R,t[5]=(e*C-r*k+i*T)*R,t[6]=(g*_-f*j-m*E)*R,t[7]=(u*j-h*_+p*E)*R,t[8]=(o*D-a*k+c*S)*R,t[9]=(n*k-e*D-i*S)*R,t[10]=(f*M-d*_+m*b)*R,t[11]=(l*_-u*M-p*b)*R,t[12]=(a*T-o*x-s*S)*R,t[13]=(e*x-n*T+r*S)*R,t[14]=(d*E-f*P-g*b)*R,t[15]=(u*P-l*E+h*b)*R,t):null);if(!V)throw Error("Pixel project matrix not invertible");this.pixelProjectionMatrix=F,this.pixelUnprojectionMatrix=V}equals(t){return t instanceof z&&t.width===this.width&&t.height===this.height&&E(t.projectionMatrix,this.projectionMatrix)&&E(t.viewMatrix,this.viewMatrix)}project(t,{topLeft:e=!0}={}){const n=function(t,e){const[n,r,i=0]=t;return M(Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(i)),g(e,[n,r,i,1])}(this.projectPosition(t),this.pixelProjectionMatrix),[r,i]=n,o=e?i:this.height-i;return 2===t.length?[r,o]:[r,o,n[2]]}unproject(t,{topLeft:e=!0,targetZ:n}={}){const[r,i,o]=t,a=e?i:this.height-i,s=n&&n*this.distanceScales.unitsPerMeter[2],c=I([r,a,o],this.pixelUnprojectionMatrix,s),[u,l,h]=this.unprojectPosition(c);return Number.isFinite(o)?[u,l,h]:Number.isFinite(n)?[u,l,n]:[u,l]}projectPosition(t){const[e,n]=D(t);return[e,n,(t[2]||0)*this.distanceScales.unitsPerMeter[2]]}unprojectPosition(t){const[e,n]=C(t);return[e,n,(t[2]||0)*this.distanceScales.metersPerUnit[2]]}projectFlat(t){return D(t)}unprojectFlat(t){return C(t)}getMapCenterByLngLatPosition({lngLat:t,pos:e}){var n;const r=I(e,this.pixelUnprojectionMatrix),i=_([],D(t),((n=[])[0]=-r[0],n[1]=-r[1],n));return C(_([],this.center,i))}getLocationAtPoint({lngLat:t,pos:e}){return this.getMapCenterByLngLatPosition({lngLat:t,pos:e})}fitBounds(t,e={}){const{width:n,height:r}=this,{longitude:i,latitude:o,zoom:a}=function({width:t,height:e,bounds:n,minExtent:r=0,maxZoom:i=24,padding:o=0,offset:a=[0,0]}){const[[s,c],[u,l]]=n;if(Number.isFinite(o)){const t=o;o={top:t,bottom:t,left:t,right:t}}else M(Number.isFinite(o.top)&&Number.isFinite(o.bottom)&&Number.isFinite(o.left)&&Number.isFinite(o.right));const h=D([s,l<-85.051129?-85.051129:l>85.051129?85.051129:l]),p=D([u,c<-85.051129?-85.051129:c>85.051129?85.051129:c]),f=[Math.max(Math.abs(p[0]-h[0]),r),Math.max(Math.abs(p[1]-h[1]),r)],d=[t-o.left-o.right-2*Math.abs(a[0]),e-o.top-o.bottom-2*Math.abs(a[1])];M(d[0]>0&&d[1]>0);const v=d[0]/f[0],g=d[1]/f[1],m=(o.right-o.left)/2/v,y=(o.bottom-o.top)/2/g,w=C([(p[0]+h[0])/2+m,(p[1]+h[1])/2+y]),O=Math.min(i,b(Math.abs(Math.min(v,g))));return M(Number.isFinite(O)),{longitude:w[0],latitude:w[1],zoom:O}}(Object.assign({width:n,height:r,bounds:t},e));return new z({width:n,height:r,longitude:i,latitude:o,zoom:a})}getBounds(t){const e=this.getBoundingRegion(t),n=Math.min(...e.map(t=>t[0])),r=Math.max(...e.map(t=>t[0]));return[[n,Math.min(...e.map(t=>t[1]))],[r,Math.max(...e.map(t=>t[1]))]]}getBoundingRegion(t={}){return function(t,e=0){let n,r;const{width:i,height:o,unproject:a}=t,s={targetZ:e},c=a([0,o],s),u=a([i,o],s);return(t.fovy?.5*t.fovy*L:Math.atan(.5/t.altitude))>(90-t.pitch)*L-.01?(n=N(t,0,e),r=N(t,i,e)):(n=a([0,0],s),r=a([i,0],s)),[c,u,r,n]}(this,t.z||0)}}const F=["longitude","latitude","zoom"],V={curve:1.414,speed:1.2};function Z(t,e,n){var r,i;const o=(n=Object.assign({},V,n)).curve,a=t.zoom,s=[t.longitude,t.latitude],c=x(a),u=e.zoom,l=[e.longitude,e.latitude],h=x(u-a),p=D(s),f=(r=[],i=D(l),r[0]=i[0]-p[0],r[1]=i[1]-p[1],r),d=Math.max(t.width,t.height),v=d/h,g=Math.hypot(f[0],f[1])*c,m=Math.max(g,.01),b=o*o,y=(v*v-d*d+b*b*m*m)/(2*d*b*m),w=(v*v-d*d-b*b*m*m)/(2*v*b*m),O=Math.log(Math.sqrt(y*y+1)-y),E=Math.log(Math.sqrt(w*w+1)-w);return{startZoom:a,startCenterXY:p,uDelta:f,w0:d,u1:g,S:(E-O)/o,rho:o,rho2:b,r0:O,r1:E}}var B=function(){if("undefined"!=typeof Map)return Map;function t(t,e){var n=-1;return t.some(function(t,r){return t[0]===e&&(n=r,!0)}),n}return function(){function e(){this.__entries__=[]}return Object.defineProperty(e.prototype,"size",{get:function(){return this.__entries__.length},enumerable:!0,configurable:!0}),e.prototype.get=function(e){var n=t(this.__entries__,e),r=this.__entries__[n];return r&&r[1]},e.prototype.set=function(e,n){var r=t(this.__entries__,e);~r?this.__entries__[r][1]=n:this.__entries__.push([e,n])},e.prototype.delete=function(e){var n=this.__entries__,r=t(n,e);~r&&n.splice(r,1)},e.prototype.has=function(e){return!!~t(this.__entries__,e)},e.prototype.clear=function(){this.__entries__.splice(0)},e.prototype.forEach=function(t,e){void 0===e&&(e=null);for(var n=0,r=this.__entries__;n0},t.prototype.connect_=function(){U&&!this.connected_&&(document.addEventListener("transitionend",this.onTransitionEnd_),window.addEventListener("resize",this.refresh),Y?(this.mutationsObserver_=new MutationObserver(this.refresh),this.mutationsObserver_.observe(document,{attributes:!0,childList:!0,characterData:!0,subtree:!0})):(document.addEventListener("DOMSubtreeModified",this.refresh),this.mutationEventsAdded_=!0),this.connected_=!0)},t.prototype.disconnect_=function(){U&&this.connected_&&(document.removeEventListener("transitionend",this.onTransitionEnd_),window.removeEventListener("resize",this.refresh),this.mutationsObserver_&&this.mutationsObserver_.disconnect(),this.mutationEventsAdded_&&document.removeEventListener("DOMSubtreeModified",this.refresh),this.mutationsObserver_=null,this.mutationEventsAdded_=!1,this.connected_=!1)},t.prototype.onTransitionEnd_=function(t){var e=t.propertyName,n=void 0===e?"":e;W.some(function(t){return!!~n.indexOf(t)})&&this.refresh()},t.getInstance=function(){return this.instance_||(this.instance_=new t),this.instance_},t.instance_=null,t}(),K=function(t,e){for(var n=0,r=Object.keys(e);n0},t}(),ti="undefined"!=typeof WeakMap?new WeakMap:new B,ResizeObserver=function ResizeObserver(t){if(!(this instanceof ResizeObserver))throw TypeError("Cannot call a class as a function.");if(!arguments.length)throw TypeError("1 argument required, but only 0 present.");var e=new tr(t,X.getInstance(),this);ti.set(this,e)};["observe","unobserve","disconnect"].forEach(function(t){ResizeObserver.prototype[t]=function(){var e;return(e=ti.get(this))[t].apply(e,arguments)}});var to=void 0!==q.ResizeObserver?q.ResizeObserver:ResizeObserver;function ta(t,e){if(!(t instanceof e))throw TypeError("Cannot call a class as a function")}function ts(t,e){for(var n=0;n=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:r}}throw TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o,a=!0,s=!1;return{s:function(){i=t[Symbol.iterator]()},n:function(){var t=i.next();return a=t.done,t},e:function(t){s=!0,o=t},f:function(){try{a||null==i.return||i.return()}finally{if(s)throw o}}}}function tf(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n1&&void 0!==arguments[1]?arguments[1]:"component";t.debug&&p.checkPropTypes(tm,t,"prop",e)}var tw=function(){function t(e){var n=this;if(ta(this,t),a(this,"props",tb),a(this,"width",0),a(this,"height",0),a(this,"_fireLoadEvent",function(){n.props.onLoad({type:"load",target:n._map})}),a(this,"_handleError",function(t){n.props.onError(t)}),!e.mapboxgl)throw Error("Mapbox not available");this.mapboxgl=e.mapboxgl,t.initialized||(t.initialized=!0,this._checkStyleSheet(this.mapboxgl.version)),this._initialize(e)}return tc(t,[{key:"finalize",value:function(){return this._destroy(),this}},{key:"setProps",value:function(t){return this._update(this.props,t),this}},{key:"redraw",value:function(){var t=this._map;t.style&&(t._frame&&(t._frame.cancel(),t._frame=null),t._render())}},{key:"getMap",value:function(){return this._map}},{key:"_reuse",value:function(e){this._map=t.savedMap;var n=this._map.getContainer(),r=e.container;for(r.classList.add("mapboxgl-map");n.childNodes.length>0;)r.appendChild(n.childNodes[0]);this._map._container=r,t.savedMap=null,e.mapStyle&&this._map.setStyle(tv(e.mapStyle),{diff:!1}),this._map.isStyleLoaded()?this._fireLoadEvent():this._map.once("styledata",this._fireLoadEvent)}},{key:"_create",value:function(e){if(e.reuseMaps&&t.savedMap)this._reuse(e);else{if(e.gl){var n=HTMLCanvasElement.prototype.getContext;HTMLCanvasElement.prototype.getContext=function(){return HTMLCanvasElement.prototype.getContext=n,e.gl}}var r={container:e.container,center:[0,0],zoom:8,pitch:0,bearing:0,maxZoom:24,style:tv(e.mapStyle),interactive:!1,trackResize:!1,attributionControl:e.attributionControl,preserveDrawingBuffer:e.preserveDrawingBuffer};e.transformRequest&&(r.transformRequest=e.transformRequest),this._map=new this.mapboxgl.Map(Object.assign({},r,e.mapOptions)),this._map.once("load",this._fireLoadEvent),this._map.on("error",this._handleError)}return this}},{key:"_destroy",value:function(){this._map&&(this.props.reuseMaps&&!t.savedMap?(t.savedMap=this._map,this._map.off("load",this._fireLoadEvent),this._map.off("error",this._handleError),this._map.off("styledata",this._fireLoadEvent)):this._map.remove(),this._map=null)}},{key:"_initialize",value:function(t){var e=this;ty(t=Object.assign({},tb,t),"Mapbox"),this.mapboxgl.accessToken=t.mapboxApiAccessToken||tb.mapboxApiAccessToken,this.mapboxgl.baseApiUrl=t.mapboxApiUrl,this._create(t);var n=t.container;Object.defineProperty(n,"offsetWidth",{configurable:!0,get:function(){return e.width}}),Object.defineProperty(n,"clientWidth",{configurable:!0,get:function(){return e.width}}),Object.defineProperty(n,"offsetHeight",{configurable:!0,get:function(){return e.height}}),Object.defineProperty(n,"clientHeight",{configurable:!0,get:function(){return e.height}});var r=this._map.getCanvas();r&&(r.style.outline="none"),this._updateMapViewport({},t),this._updateMapSize({},t),this.props=t}},{key:"_update",value:function(t,e){if(this._map){ty(e=Object.assign({},this.props,e),"Mapbox");var n=this._updateMapViewport(t,e),r=this._updateMapSize(t,e);this._updateMapStyle(t,e),!e.asyncRender&&(n||r)&&this.redraw(),this.props=e}}},{key:"_updateMapStyle",value:function(t,e){t.mapStyle!==e.mapStyle&&this._map.setStyle(tv(e.mapStyle),{diff:!e.preventStyleDiffing})}},{key:"_updateMapSize",value:function(t,e){var n=t.width!==e.width||t.height!==e.height;return n&&(this.width=e.width,this.height=e.height,this._map.resize()),n}},{key:"_updateMapViewport",value:function(t,e){var n=this._getViewState(t),r=this._getViewState(e),i=r.latitude!==n.latitude||r.longitude!==n.longitude||r.zoom!==n.zoom||r.pitch!==n.pitch||r.bearing!==n.bearing||r.altitude!==n.altitude;return i&&(this._map.jumpTo(this._viewStateToMapboxProps(r)),r.altitude!==n.altitude&&(this._map.transform.altitude=r.altitude)),i}},{key:"_getViewState",value:function(t){var e=t.viewState||t,n=e.longitude,r=e.latitude,i=e.zoom,o=e.pitch,a=e.bearing,s=e.altitude;return{longitude:n,latitude:r,zoom:i,pitch:void 0===o?0:o,bearing:void 0===a?0:a,altitude:void 0===s?1.5:s}}},{key:"_checkStyleSheet",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"0.47.0";if(void 0!==tu)try{var e=tu.createElement("div");if(e.className="mapboxgl-map",e.style.display="none",tu.body.appendChild(e),!("static"!==window.getComputedStyle(e).position)){var n=tu.createElement("link");n.setAttribute("rel","stylesheet"),n.setAttribute("type","text/css"),n.setAttribute("href","https://api.tiles.mapbox.com/mapbox-gl-js/v".concat(t,"/mapbox-gl.css")),tu.head.appendChild(n)}}catch(t){}}},{key:"_viewStateToMapboxProps",value:function(t){return{center:[t.longitude,t.latitude],zoom:t.zoom,bearing:t.bearing,pitch:t.pitch}}}]),t}();a(tw,"initialized",!1),a(tw,"propTypes",tm),a(tw,"defaultProps",tb),a(tw,"savedMap",null);var tO=n(6158),tE=n.n(tO);function t_(t){return Array.isArray(t)||ArrayBuffer.isView(t)}function tP(t,e,n){return Math.max(e,Math.min(n,t))}function tM(t,e,n){return t_(t)?t.map(function(t,r){return tM(t,e[r],n)}):n*e+(1-n)*t}function tj(t,e){if(!t)throw Error(e||"react-map-gl: assertion failed.")}function tS(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,r)}return n}function tT(t){for(var e=1;e0,"`scale` must be a positive number");var i=this._state,o=i.startZoom,a=i.startZoomLngLat;Number.isFinite(o)||(o=this._viewportProps.zoom,a=this._unproject(n)||this._unproject(e)),tj(a,"`startZoomLngLat` prop is required for zoom behavior to calculate where to position the map.");var s=this._calculateNewZoom({scale:r,startZoom:o||0}),c=f(new z(Object.assign({},this._viewportProps,{zoom:s})).getMapCenterByLngLatPosition({lngLat:a,pos:e}),2),u=c[0],l=c[1];return this._getUpdatedMapState({zoom:s,longitude:u,latitude:l})}},{key:"zoomEnd",value:function(){return this._getUpdatedMapState({startZoomLngLat:null,startZoom:null})}},{key:"_getUpdatedMapState",value:function(e){return new t(Object.assign({},this._viewportProps,this._state,e))}},{key:"_applyConstraints",value:function(t){var e=t.maxZoom,n=t.minZoom,r=t.zoom;t.zoom=tP(r,n,e);var i=t.maxPitch,o=t.minPitch,a=t.pitch;return t.pitch=tP(a,o,i),Object.assign(t,function({width:t,height:e,longitude:n,latitude:r,zoom:i,pitch:o=0,bearing:a=0}){(n<-180||n>180)&&(n=m(n+180,360)-180),(a<-180||a>180)&&(a=m(a+180,360)-180);const s=b(e/512);if(i<=s)i=s,r=0;else{const t=e/2/Math.pow(2,i),n=C([0,t])[1];if(re&&(r=e)}}return{width:t,height:e,longitude:n,latitude:r,zoom:i,pitch:o,bearing:a}}(t)),t}},{key:"_unproject",value:function(t){var e=new z(this._viewportProps);return t&&e.unproject(t)}},{key:"_calculateNewLngLat",value:function(t){var e=t.startPanLngLat,n=t.pos;return new z(this._viewportProps).getMapCenterByLngLatPosition({lngLat:e,pos:n})}},{key:"_calculateNewZoom",value:function(t){var e=t.scale,n=t.startZoom,r=this._viewportProps,i=r.maxZoom;return tP(n+Math.log2(e),r.minZoom,i)}},{key:"_calculateNewPitchAndBearing",value:function(t){var e=t.deltaScaleX,n=t.deltaScaleY,r=t.startBearing,i=t.startPitch;n=tP(n,-1,1);var o=this._viewportProps,a=o.minPitch,s=o.maxPitch,c=i;return n>0?c=i+n*(s-i):n<0&&(c=i-n*(a-i)),{pitch:c,bearing:r+180*e}}},{key:"_getRotationParams",value:function(t,e){var n=t[0]-e[0],r=t[1]-e[1],i=t[1],o=e[1],a=this._viewportProps,s=a.width,c=a.height,u=0;return r>0?Math.abs(c-o)>5&&(u=r/(o-c)*1.2):r<0&&o>5&&(u=1-i/o),{deltaScaleX:n/s,deltaScaleY:u=Math.min(1,Math.max(-1,u))}}}]),t}();function tC(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,r)}return n}function tR(t){for(var e=1;e1&&void 0!==arguments[1]?arguments[1]:{},n=c.current&&c.current.getMap();return n&&n.queryRenderedFeatures(t,e)}}},[]);var g=(0,h.useCallback)(function(t){var e=t.target;e===p.current&&e.scrollTo(0,0)},[]),m=v&&h.createElement(tI,{value:tF(tF({},d),{},{viewport:d.viewport||tZ(tF({map:v,props:t},a)),map:v,container:d.container||l.current})},h.createElement("div",{key:"map-overlays",className:"overlays",ref:p,style:tB,onScroll:g},t.children)),b=t.className,y=t.width,w=t.height,O=t.style,E=t.visibilityConstraints,_=Object.assign({position:"relative"},O,{width:y,height:w}),P=Object.assign({},tB,{visibility:t.visible&&function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:tk;for(var n in e){var r,i=n.slice(0,3),o=(r=n.slice(3))[0].toLowerCase()+r.slice(1);if("min"===i&&t[o]e[n])return!1}return!0}(t.viewState||t,E)?"inherit":"hidden"});return h.createElement("div",{key:"map-container",ref:l,style:_},h.createElement("div",{key:"map-mapbox",ref:u,style:P,className:b}),m,!r&&!t.disableTokenWarning&&h.createElement(tH,null))});function tY(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:r}}throw TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o,a=!0,s=!1;return{s:function(){i=t[Symbol.iterator]()},n:function(){var t=i.next();return a=t.done,t},e:function(t){s=!0,o=t},f:function(){try{a||null==i.return||i.return()}finally{if(s)throw o}}}}(this.propNames||[]);try{for(r.s();!(n=r.n()).done;){var i=n.value;if(!function t(e,n){if(e===n)return!0;if(t_(e)&&t_(n)){if(e.length!==n.length)return!1;for(var r=0;r=Math.abs(e-n)}(t[i],e[i]))return!1}}catch(t){r.e(t)}finally{r.f()}return!0}},{key:"initializeProps",value:function(t,e){return{start:t,end:e}}},{key:"interpolateProps",value:function(t,e,n){tj(!1,"interpolateProps is not implemented")}},{key:"getDuration",value:function(t,e){return e.transitionDuration}}]),t}();function tK(t){if(void 0===t)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function tG(t,e){return(tG=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function t$(t,e){if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&tG(t,e)}function tJ(t){return(tJ="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function tQ(t,e){if(e&&("object"===tJ(e)||"function"==typeof e))return e;if(void 0!==e)throw TypeError("Derived constructors may only return object or undefined");return tK(t)}function t0(t){return(t0=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var t1={longitude:1,bearing:1};function t2(t){return Number.isFinite(t)||Array.isArray(t)}function t5(t,e,n){return t in t1&&Math.abs(n-e)>180&&(n=n<0?n+360:n-360),n}function t4(t,e){if("undefined"==typeof Symbol||null==t[Symbol.iterator]){if(Array.isArray(t)||(i=function(t,e){if(t){if("string"==typeof t)return t3(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);if("Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n)return Array.from(t);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return t3(t,e)}}(t))||e&&t&&"number"==typeof t.length){i&&(t=i);var n=0,r=function(){};return{s:r,n:function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:r}}throw TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o,a=!0,s=!1;return{s:function(){i=t[Symbol.iterator]()},n:function(){var t=i.next();return a=t.done,t},e:function(t){s=!0,o=t},f:function(){try{a||null==i.return||i.return()}finally{if(s)throw o}}}}function t3(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n=t.length?{done:!0}:{done:!1,value:t[n++]}},e:function(t){throw t},f:r}}throw TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,o,a=!0,s=!1;return{s:function(){i=t[Symbol.iterator]()},n:function(){var t=i.next();return a=t.done,t},e:function(t){s=!0,o=t},f:function(){try{a||null==i.return||i.return()}finally{if(s)throw o}}}}function ee(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n0&&void 0!==arguments[0]?arguments[0]:{};return ta(this,r),a(tK(t=n.call(this)),"propNames",t8),t.props=Object.assign({},t7,e),t}tc(r,[{key:"initializeProps",value:function(t,e){var n,r={},i={},o=t4(t6);try{for(o.s();!(n=o.n()).done;){var a=n.value,s=t[a],c=e[a];tj(t2(s)&&t2(c),"".concat(a," must be supplied for transition")),r[a]=s,i[a]=t5(a,s,c)}}catch(t){o.e(t)}finally{o.f()}var u,l=t4(t9);try{for(l.s();!(u=l.n()).done;){var h=u.value,p=t[h]||0,f=e[h]||0;r[h]=p,i[h]=t5(h,p,f)}}catch(t){l.e(t)}finally{l.f()}return{start:r,end:i}}},{key:"interpolateProps",value:function(t,e,n){var r,i=function(t,e,n,r={}){var i,o;const a={},{startZoom:s,startCenterXY:c,uDelta:u,w0:l,u1:h,S:p,rho:f,rho2:d,r0:v}=Z(t,e,r);if(h<.01){for(const r of F){const i=t[r],o=e[r];a[r]=n*o+(1-n)*i}return a}const g=n*p,m=s+b(1/(Math.cosh(v)/Math.cosh(v+f*g))),y=(i=[],o=l*((Math.cosh(v)*Math.tanh(v+f*g)-Math.sinh(v))/d)/h,i[0]=u[0]*o,i[1]=u[1]*o,i);_(y,y,c);const w=C(y);return a.longitude=w[0],a.latitude=w[1],a.zoom=m,a}(t,e,n,this.props),o=t4(t9);try{for(o.s();!(r=o.n()).done;){var a=r.value;i[a]=tM(t[a],e[a],n)}}catch(t){o.e(t)}finally{o.f()}return i}},{key:"getDuration",value:function(t,e){var n=e.transitionDuration;return"auto"===n&&(n=function(t,e,n={}){let r;const{screenSpeed:i,speed:o,maxDuration:a}=n=Object.assign({},V,n),{S:s,rho:c}=Z(t,e,n),u=1e3*s;return r=Number.isFinite(i)?u/(i/c):u/o,Number.isFinite(a)&&r>a?0:r}(t,e,this.props)),n}}])}(tX);var en=["longitude","latitude","zoom","bearing","pitch"],er=function(t){t$(r,t);var e,n=(e=function(){if("undefined"==typeof Reflect||!Reflect.construct||Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch(t){return!1}}(),function(){var t,n=t0(r);if(e){var i=t0(this).constructor;t=Reflect.construct(n,arguments,i)}else t=n.apply(this,arguments);return tQ(this,t)});function r(){var t,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return ta(this,r),t=n.call(this),Array.isArray(e)&&(e={transitionProps:e}),t.propNames=e.transitionProps||en,e.around&&(t.around=e.around),t}return tc(r,[{key:"initializeProps",value:function(t,e){var n={},r={};if(this.around){n.around=this.around;var i=new z(t).unproject(this.around);Object.assign(r,e,{around:new z(e).project(i),aroundLngLat:i})}var o,a=et(this.propNames);try{for(a.s();!(o=a.n()).done;){var s=o.value,c=t[s],u=e[s];tj(t2(c)&&t2(u),"".concat(s," must be supplied for transition")),n[s]=c,r[s]=t5(s,c,u)}}catch(t){a.e(t)}finally{a.f()}return{start:n,end:r}}},{key:"interpolateProps",value:function(t,e,n){var r,i={},o=et(this.propNames);try{for(o.s();!(r=o.n()).done;){var a=r.value;i[a]=tM(t[a],e[a],n)}}catch(t){o.e(t)}finally{o.f()}if(e.around){var s=f(new z(Object.assign({},e,i)).getMapCenterByLngLatPosition({lngLat:e.aroundLngLat,pos:tM(t.around,e.around,n)}),2),c=s[0],u=s[1];i.longitude=c,i.latitude=u}return i}}]),r}(tX),ei=function(){},eo={BREAK:1,SNAP_TO_END:2,IGNORE:3,UPDATE:4},ea={transitionDuration:0,transitionEasing:function(t){return t},transitionInterpolator:new er,transitionInterruption:eo.BREAK,onTransitionStart:ei,onTransitionInterrupt:ei,onTransitionEnd:ei},es=function(){function t(){var e=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};ta(this,t),a(this,"_animationFrame",null),a(this,"_onTransitionFrame",function(){e._animationFrame=requestAnimationFrame(e._onTransitionFrame),e._updateViewport()}),this.props=null,this.onViewportChange=n.onViewportChange||ei,this.onStateChange=n.onStateChange||ei,this.time=n.getTime||Date.now}return tc(t,[{key:"getViewportInTransition",value:function(){return this._animationFrame?this.state.propsInTransition:null}},{key:"processViewportChange",value:function(t){var e=this.props;if(this.props=t,!e||this._shouldIgnoreViewportChange(e,t))return!1;if(this._isTransitionEnabled(t)){var n=Object.assign({},e),r=Object.assign({},t);if(this._isTransitionInProgress()&&(e.onTransitionInterrupt(),this.state.interruption===eo.SNAP_TO_END?Object.assign(n,this.state.endProps):Object.assign(n,this.state.propsInTransition),this.state.interruption===eo.UPDATE)){var i,o,a=this.time(),s=(a-this.state.startTime)/this.state.duration;r.transitionDuration=this.state.duration-(a-this.state.startTime),r.transitionEasing=(o=(i=this.state.easing)(s),function(t){return 1/(1-o)*(i(t*(1-s)+s)-o)}),r.transitionInterpolator=n.transitionInterpolator}return r.onTransitionStart(),this._triggerTransition(n,r),!0}return this._isTransitionInProgress()&&(e.onTransitionInterrupt(),this._endTransition()),!1}},{key:"_isTransitionInProgress",value:function(){return!!this._animationFrame}},{key:"_isTransitionEnabled",value:function(t){var e=t.transitionDuration,n=t.transitionInterpolator;return(e>0||"auto"===e)&&!!n}},{key:"_isUpdateDueToCurrentTransition",value:function(t){return!!this.state.propsInTransition&&this.state.interpolator.arePropsEqual(t,this.state.propsInTransition)}},{key:"_shouldIgnoreViewportChange",value:function(t,e){return!t||(this._isTransitionInProgress()?this.state.interruption===eo.IGNORE||this._isUpdateDueToCurrentTransition(e):!this._isTransitionEnabled(e)||e.transitionInterpolator.arePropsEqual(t,e))}},{key:"_triggerTransition",value:function(t,e){tj(this._isTransitionEnabled(e)),this._animationFrame&&cancelAnimationFrame(this._animationFrame);var n=e.transitionInterpolator,r=n.getDuration?n.getDuration(t,e):e.transitionDuration;if(0!==r){var i=e.transitionInterpolator.initializeProps(t,e),o={inTransition:!0,isZooming:t.zoom!==e.zoom,isPanning:t.longitude!==e.longitude||t.latitude!==e.latitude,isRotating:t.bearing!==e.bearing||t.pitch!==e.pitch};this.state={duration:r,easing:e.transitionEasing,interpolator:e.transitionInterpolator,interruption:e.transitionInterruption,startTime:this.time(),startProps:i.start,endProps:i.end,animation:null,propsInTransition:{}},this._onTransitionFrame(),this.onStateChange(o)}}},{key:"_endTransition",value:function(){this._animationFrame&&(cancelAnimationFrame(this._animationFrame),this._animationFrame=null),this.onStateChange({inTransition:!1,isZooming:!1,isPanning:!1,isRotating:!1})}},{key:"_updateViewport",value:function(){var t=this.time(),e=this.state,n=e.startTime,r=e.duration,i=e.easing,o=e.interpolator,a=e.startProps,s=e.endProps,c=!1,u=(t-n)/r;u>=1&&(u=1,c=!0),u=i(u);var l=o.interpolateProps(a,s,u),h=new tD(Object.assign({},this.props,l));this.state.propsInTransition=h.getViewportProps(),this.onViewportChange(this.state.propsInTransition,this.props),c&&(this._endTransition(),this.props.onTransitionEnd())}}]),t}();a(es,"defaultProps",ea);var ec=n(840),eu=n.n(ec);const el={mousedown:1,mousemove:2,mouseup:4};!function(t){const e=t.prototype.handler;t.prototype.handler=function(t){const n=this.store;t.button>0&&"pointerdown"===t.type&&!function(t,e){for(let n=0;ne.pointerId===t.pointerId)&&n.push(t),e.call(this,t)}}(eu().PointerEventInput),eu().MouseInput.prototype.handler=function(t){let e=el[t.type];1&e&&t.button>=0&&(this.pressed=!0),2&e&&0===t.which&&(e=4),this.pressed&&(4&e&&(this.pressed=!1),this.callback(this.manager,e,{pointers:[t],changedPointers:[t],pointerType:"mouse",srcEvent:t}))};const eh=eu().Manager;var ep=eu();const ef=ep?[[ep.Pan,{event:"tripan",pointers:3,threshold:0,enable:!1}],[ep.Rotate,{enable:!1}],[ep.Pinch,{enable:!1}],[ep.Swipe,{enable:!1}],[ep.Pan,{threshold:0,enable:!1}],[ep.Press,{enable:!1}],[ep.Tap,{event:"doubletap",taps:2,enable:!1}],[ep.Tap,{event:"anytap",enable:!1}],[ep.Tap,{enable:!1}]]:null,ed={tripan:["rotate","pinch","pan"],rotate:["pinch"],pinch:["pan"],pan:["press","doubletap","anytap","tap"],doubletap:["anytap"],anytap:["tap"]},ev={doubletap:["tap"]},eg={pointerdown:"pointerdown",pointermove:"pointermove",pointerup:"pointerup",touchstart:"pointerdown",touchmove:"pointermove",touchend:"pointerup",mousedown:"pointerdown",mousemove:"pointermove",mouseup:"pointerup"},em={KEY_EVENTS:["keydown","keyup"],MOUSE_EVENTS:["mousedown","mousemove","mouseup","mouseover","mouseout","mouseleave"],WHEEL_EVENTS:["wheel","mousewheel"]},eb={tap:"tap",anytap:"anytap",doubletap:"doubletap",press:"press",pinch:"pinch",pinchin:"pinch",pinchout:"pinch",pinchstart:"pinch",pinchmove:"pinch",pinchend:"pinch",pinchcancel:"pinch",rotate:"rotate",rotatestart:"rotate",rotatemove:"rotate",rotateend:"rotate",rotatecancel:"rotate",tripan:"tripan",tripanstart:"tripan",tripanmove:"tripan",tripanup:"tripan",tripandown:"tripan",tripanleft:"tripan",tripanright:"tripan",tripanend:"tripan",tripancancel:"tripan",pan:"pan",panstart:"pan",panmove:"pan",panup:"pan",pandown:"pan",panleft:"pan",panright:"pan",panend:"pan",pancancel:"pan",swipe:"swipe",swipeleft:"swipe",swiperight:"swipe",swipeup:"swipe",swipedown:"swipe"},ey={click:"tap",anyclick:"anytap",dblclick:"doubletap",mousedown:"pointerdown",mousemove:"pointermove",mouseup:"pointerup",mouseover:"pointerover",mouseout:"pointerout",mouseleave:"pointerleave"},ew="undefined"!=typeof navigator&&navigator.userAgent?navigator.userAgent.toLowerCase():"",eO="undefined"!=typeof window?window:n.g;void 0!==n.g?n.g:window;let eE=!1;try{const t={get passive(){return eE=!0,!0}};eO.addEventListener("test",t,t),eO.removeEventListener("test",t,t)}catch(t){}const e_=-1!==ew.indexOf("firefox"),{WHEEL_EVENTS:eP}=em,eM="wheel";class ej{constructor(t,e,n={}){this.element=t,this.callback=e,this.options=Object.assign({enable:!0},n),this.events=eP.concat(n.events||[]),this.handleEvent=this.handleEvent.bind(this),this.events.forEach(e=>t.addEventListener(e,this.handleEvent,!!eE&&{passive:!1}))}destroy(){this.events.forEach(t=>this.element.removeEventListener(t,this.handleEvent))}enableEventType(t,e){t===eM&&(this.options.enable=e)}handleEvent(t){if(!this.options.enable)return;let e=t.deltaY;eO.WheelEvent&&(e_&&t.deltaMode===eO.WheelEvent.DOM_DELTA_PIXEL&&(e/=eO.devicePixelRatio),t.deltaMode===eO.WheelEvent.DOM_DELTA_LINE&&(e*=40));const n={x:t.clientX,y:t.clientY};0!==e&&e%4.000244140625==0&&(e=Math.floor(e/4.000244140625)),t.shiftKey&&e&&(e*=.25),this._onWheel(t,-e,n)}_onWheel(t,e,n){this.callback({type:eM,center:n,delta:e,srcEvent:t,pointerType:"mouse",target:t.target})}}const{MOUSE_EVENTS:eS}=em,eT="pointermove",ek="pointerover",ex="pointerout",eD="pointerleave";class eC{constructor(t,e,n={}){this.element=t,this.callback=e,this.pressed=!1,this.options=Object.assign({enable:!0},n),this.enableMoveEvent=this.options.enable,this.enableLeaveEvent=this.options.enable,this.enableOutEvent=this.options.enable,this.enableOverEvent=this.options.enable,this.events=eS.concat(n.events||[]),this.handleEvent=this.handleEvent.bind(this),this.events.forEach(e=>t.addEventListener(e,this.handleEvent))}destroy(){this.events.forEach(t=>this.element.removeEventListener(t,this.handleEvent))}enableEventType(t,e){t===eT&&(this.enableMoveEvent=e),t===ek&&(this.enableOverEvent=e),t===ex&&(this.enableOutEvent=e),t===eD&&(this.enableLeaveEvent=e)}handleEvent(t){this.handleOverEvent(t),this.handleOutEvent(t),this.handleLeaveEvent(t),this.handleMoveEvent(t)}handleOverEvent(t){this.enableOverEvent&&"mouseover"===t.type&&this.callback({type:ek,srcEvent:t,pointerType:"mouse",target:t.target})}handleOutEvent(t){this.enableOutEvent&&"mouseout"===t.type&&this.callback({type:ex,srcEvent:t,pointerType:"mouse",target:t.target})}handleLeaveEvent(t){this.enableLeaveEvent&&"mouseleave"===t.type&&this.callback({type:eD,srcEvent:t,pointerType:"mouse",target:t.target})}handleMoveEvent(t){if(this.enableMoveEvent)switch(t.type){case"mousedown":t.button>=0&&(this.pressed=!0);break;case"mousemove":0===t.which&&(this.pressed=!1),this.pressed||this.callback({type:eT,srcEvent:t,pointerType:"mouse",target:t.target});break;case"mouseup":this.pressed=!1}}}const{KEY_EVENTS:eR}=em,eA="keydown",eI="keyup";class eL{constructor(t,e,n={}){this.element=t,this.callback=e,this.options=Object.assign({enable:!0},n),this.enableDownEvent=this.options.enable,this.enableUpEvent=this.options.enable,this.events=eR.concat(n.events||[]),this.handleEvent=this.handleEvent.bind(this),t.tabIndex=n.tabIndex||0,t.style.outline="none",this.events.forEach(e=>t.addEventListener(e,this.handleEvent))}destroy(){this.events.forEach(t=>this.element.removeEventListener(t,this.handleEvent))}enableEventType(t,e){t===eA&&(this.enableDownEvent=e),t===eI&&(this.enableUpEvent=e)}handleEvent(t){const e=t.target||t.srcElement;("INPUT"!==e.tagName||"text"!==e.type)&&"TEXTAREA"!==e.tagName&&(this.enableDownEvent&&"keydown"===t.type&&this.callback({type:eA,srcEvent:t,key:t.key,target:t.target}),this.enableUpEvent&&"keyup"===t.type&&this.callback({type:eI,srcEvent:t,key:t.key,target:t.target}))}}const eN="contextmenu";class ez{constructor(t,e,n={}){this.element=t,this.callback=e,this.options=Object.assign({enable:!0},n),this.handleEvent=this.handleEvent.bind(this),t.addEventListener("contextmenu",this.handleEvent)}destroy(){this.element.removeEventListener("contextmenu",this.handleEvent)}enableEventType(t,e){t===eN&&(this.options.enable=e)}handleEvent(t){this.options.enable&&this.callback({type:eN,center:{x:t.clientX,y:t.clientY},srcEvent:t,pointerType:"mouse",target:t.target})}}const eF={pointerdown:1,pointermove:2,pointerup:4,mousedown:1,mousemove:2,mouseup:4},eV={srcElement:"root",priority:0};class eZ{constructor(t){this.eventManager=t,this.handlers=[],this.handlersByElement=new Map,this.handleEvent=this.handleEvent.bind(this),this._active=!1}isEmpty(){return!this._active}add(t,e,n,r=!1,i=!1){const{handlers:o,handlersByElement:a}=this;n&&("object"!=typeof n||n.addEventListener)&&(n={srcElement:n}),n=n?Object.assign({},eV,n):eV;let s=a.get(n.srcElement);s||(s=[],a.set(n.srcElement,s));const c={type:t,handler:e,srcElement:n.srcElement,priority:n.priority};r&&(c.once=!0),i&&(c.passive=!0),o.push(c),this._active=this._active||!c.passive;let u=s.length-1;for(;u>=0&&!(s[u].priority>=c.priority);)u--;s.splice(u+1,0,c)}remove(t,e){const{handlers:n,handlersByElement:r}=this;for(let i=n.length-1;i>=0;i--){const o=n[i];if(o.type===t&&o.handler===e){n.splice(i,1);const t=r.get(o.srcElement);t.splice(t.indexOf(o),1),0===t.length&&r.delete(o.srcElement)}}this._active=n.some(t=>!t.passive)}handleEvent(t){if(this.isEmpty())return;const e=this._normalizeEvent(t);let n=t.srcEvent.target;for(;n&&n!==e.rootElement;){if(this._emit(e,n),e.handled)return;n=n.parentNode}this._emit(e,"root")}_emit(t,e){const n=this.handlersByElement.get(e);if(n){let e=!1;const r=()=>{t.handled=!0},i=()=>{t.handled=!0,e=!0},o=[];for(let a=0;a{const e=this.manager.get(t);e&&ed[t].forEach(t=>{e.recognizeWith(t)})}),e.recognizerOptions){const t=this.manager.get(r);if(t){const n=e.recognizerOptions[r];delete n.enable,t.set(n)}}for(const[n,r]of(this.wheelInput=new ej(t,this._onOtherEvent,{enable:!1}),this.moveInput=new eC(t,this._onOtherEvent,{enable:!1}),this.keyInput=new eL(t,this._onOtherEvent,{enable:!1,tabIndex:e.tabIndex}),this.contextmenuInput=new ez(t,this._onOtherEvent,{enable:!1}),this.events))r.isEmpty()||(this._toggleRecognizer(r.recognizerName,!0),this.manager.on(n,r.handleEvent))}destroy(){this.element&&(this.wheelInput.destroy(),this.moveInput.destroy(),this.keyInput.destroy(),this.contextmenuInput.destroy(),this.manager.destroy(),this.wheelInput=null,this.moveInput=null,this.keyInput=null,this.contextmenuInput=null,this.manager=null,this.element=null)}on(t,e,n){this._addEventHandler(t,e,n,!1)}once(t,e,n){this._addEventHandler(t,e,n,!0)}watch(t,e,n){this._addEventHandler(t,e,n,!1,!0)}off(t,e){this._removeEventHandler(t,e)}_toggleRecognizer(t,e){const{manager:n}=this;if(!n)return;const r=n.get(t);if(r&&r.options.enable!==e){r.set({enable:e});const i=ev[t];i&&!this.options.recognizers&&i.forEach(i=>{const o=n.get(i);e?(o.requireFailure(t),r.dropRequireFailure(i)):o.dropRequireFailure(t)})}this.wheelInput.enableEventType(t,e),this.moveInput.enableEventType(t,e),this.keyInput.enableEventType(t,e),this.contextmenuInput.enableEventType(t,e)}_addEventHandler(t,e,n,r,i){if("string"!=typeof t){for(const o in n=e,t)this._addEventHandler(o,t[o],n,r,i);return}const{manager:o,events:a}=this,s=ey[t]||t;let c=a.get(s);!c&&(c=new eZ(this),a.set(s,c),c.recognizerName=eb[s]||s,o&&o.on(s,c.handleEvent)),c.add(t,e,n,r,i),c.isEmpty()||this._toggleRecognizer(c.recognizerName,!0)}_removeEventHandler(t,e){if("string"!=typeof t){for(const e in t)this._removeEventHandler(e,t[e]);return}const{events:n}=this,r=ey[t]||t,i=n.get(r);if(i&&(i.remove(t,e),i.isEmpty())){const{recognizerName:t}=i;let e=!1;for(const r of n.values())if(r.recognizerName===t&&!r.isEmpty()){e=!0;break}e||this._toggleRecognizer(t,!1)}}_onBasicInput(t){const{srcEvent:e}=t,n=eg[e.type];n&&this.manager.emit(n,t)}_onOtherEvent(t){this.manager.emit(t.type,t)}}function eq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,r)}return n}function eH(t){for(var e=1;e0),a=o&&!this.state.isHovering,s=!o&&this.state.isHovering;(r||a)&&(t.features=e,r&&r(t)),a&&e5.call(this,"onMouseEnter",t),s&&e5.call(this,"onMouseLeave",t),(a||s)&&this.setState({isHovering:o})}}function e6(t){var e=this.props,n=e.onClick,r=e.onNativeClick,i=e.onDblClick,o=e.doubleClickZoom,a=[],s=i||o;switch(t.type){case"anyclick":a.push(r),s||a.push(n);break;case"click":s&&a.push(n)}(a=a.filter(Boolean)).length&&((t=e1.call(this,t)).features=e2.call(this,t.point),a.forEach(function(e){return e(t)}))}var e9=(0,h.forwardRef)(function(t,e){var n,a,s=(0,h.useContext)(tA),c=(0,h.useMemo)(function(){return t.controller||new eG},[]),u=(0,h.useMemo)(function(){return new eU(null,{touchAction:t.touchAction,recognizerOptions:t.eventRecognizerOptions})},[]),l=(0,h.useRef)(null),p=(0,h.useRef)(null),f=(0,h.useRef)({width:0,height:0,state:{isHovering:!1,isDragging:!1}}).current;f.props=t,f.map=p.current&&p.current.getMap(),f.setState=function(e){f.state=eJ(eJ({},f.state),e),l.current.style.cursor=t.getCursor(f.state)};var d=!0,v=function(t,e,r){if(d){n=[t,e,r];return}var i=f.props,o=i.onViewStateChange,a=i.onViewportChange;Object.defineProperty(t,"position",{get:function(){return[0,0,tN(f.map,t)]}}),o&&o({viewState:t,interactionState:e,oldViewState:r}),a&&a(t,e,r)};(0,h.useImperativeHandle)(e,function(){return{getMap:p.current&&p.current.getMap,queryRenderedFeatures:p.current&&p.current.queryRenderedFeatures}},[]);var g=(0,h.useMemo)(function(){return eJ(eJ({},s),{},{eventManager:u,container:s.container||l.current})},[s,l.current]);g.onViewportChange=v,g.viewport=s.viewport||tZ(f),f.viewport=g.viewport;var m=function(t){var e=t.isDragging,n=void 0!==e&&e;if(n!==f.state.isDragging&&f.setState({isDragging:n}),d){a=t;return}var r=f.props.onInteractionStateChange;r&&r(t)},b=function(){f.width&&f.height&&c.setOptions(eJ(eJ(eJ({},f.props),f.props.viewState),{},{isInteractive:!!(f.props.onViewStateChange||f.props.onViewportChange),onViewportChange:v,onStateChange:m,eventManager:u,width:f.width,height:f.height}))};(0,h.useEffect)(function(){return u.setElement(l.current),u.on({pointerdown:e4.bind(f),pointermove:e8.bind(f),pointerup:e3.bind(f),pointerleave:e5.bind(f,"onMouseOut"),click:e6.bind(f),anyclick:e6.bind(f),dblclick:e5.bind(f,"onDblClick"),wheel:e5.bind(f,"onWheel"),contextmenu:e5.bind(f,"onContextMenu")}),function(){u.destroy()}},[]),tL(function(){if(n){var t;v.apply(void 0,function(t){if(Array.isArray(t))return i(t)}(t=n)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||o(t)||function(){throw TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}())}a&&m(a)}),b();var y=t.width,w=t.height,O=t.style,E=t.getCursor,_=(0,h.useMemo)(function(){return eJ(eJ({position:"relative"},O),{},{width:y,height:w,cursor:E(f.state)})},[O,y,w,E,f.state]);return n&&f._child||(f._child=h.createElement(tI,{value:g},h.createElement("div",{key:"event-canvas",ref:l,style:_},h.createElement(tW,r({},t,{width:"100%",height:"100%",style:null,onResize:function(t){var e=t.width,n=t.height;f.width=e,f.height=n,b(),f.props.onResize({width:e,height:n})},ref:p}))))),d=!1,f._child});e9.supported=tW.supported,e9.propTypes=eQ,e9.defaultProps=e0;var e7=e9;p.string.isRequired,p.string,p.oneOf(["fill","line","symbol","circle","fill-extrusion","raster","background","heatmap","hillshade","sky"]).isRequired,p.string,p.string,p.string;var nt={captureScroll:!1,captureDrag:!0,captureClick:!0,captureDoubleClick:!0,capturePointerMove:!1},ne={captureScroll:p.bool,captureDrag:p.bool,captureClick:p.bool,captureDoubleClick:p.bool,capturePointerMove:p.bool};function nn(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=(0,h.useContext)(tA),n=(0,h.useRef)(null),r=(0,h.useRef)({props:t,state:{},context:e,containerRef:n}).current;return r.props=t,r.context=e,(0,h.useEffect)(function(){return function(t){var e=t.containerRef.current,n=t.context.eventManager;if(e&&n){var r={wheel:function(e){var n=t.props;n.captureScroll&&e.stopPropagation(),n.onScroll&&n.onScroll(e,t)},panstart:function(e){var n=t.props;n.captureDrag&&e.stopPropagation(),n.onDragStart&&n.onDragStart(e,t)},anyclick:function(e){var n=t.props;n.captureClick&&e.stopPropagation(),n.onNativeClick&&n.onNativeClick(e,t)},click:function(e){var n=t.props;n.captureClick&&e.stopPropagation(),n.onClick&&n.onClick(e,t)},dblclick:function(e){var n=t.props;n.captureDoubleClick&&e.stopPropagation(),n.onDoubleClick&&n.onDoubleClick(e,t)},pointermove:function(e){var n=t.props;n.capturePointerMove&&e.stopPropagation(),n.onPointerMove&&n.onPointerMove(e,t)}};return n.watch(r,e),function(){n.off(r)}}}(r)},[e.eventManager]),r}function nr(t){var e=t.instance,n=nn(t),r=n.context,i=n.containerRef;return e._context=r,e._containerRef=i,e._render()}var ni=function(t){t$(i,t);var e,n=(e=function(){if("undefined"==typeof Reflect||!Reflect.construct||Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch(t){return!1}}(),function(){var t,n=t0(i);if(e){var r=t0(this).constructor;t=Reflect.construct(n,arguments,r)}else t=n.apply(this,arguments);return tQ(this,t)});function i(){var t;ta(this,i);for(var e=arguments.length,r=Array(e),o=0;o2&&void 0!==arguments[2]?arguments[2]:"x";if(null===t)return e;var r="x"===n?t.offsetWidth:t.offsetHeight;return nf(e/100*r)/r*100};function nv(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,r)}return n}var ng=Object.assign({},ns,{className:p.string,longitude:p.number.isRequired,latitude:p.number.isRequired,style:p.object}),nm=Object.assign({},nc,{className:""});function nb(t){var e,n,r,i,o,s,c,u=(n=(e=f((0,h.useState)(null),2))[0],r=e[1],o=(i=f((0,h.useState)(null),2))[0],s=i[1],(c=nn(na(na({},t),{},{onDragStart:nh}))).callbacks=t,c.state.dragPos=n,c.state.setDragPos=r,c.state.dragOffset=o,c.state.setDragOffset=s,(0,h.useEffect)(function(){return function(t){var e=t.context.eventManager;if(e&&t.state.dragPos){var n={panmove:function(e){return function(t,e){var n=e.props,r=e.callbacks,i=e.state,o=e.context;t.stopPropagation();var a=nu(t);i.setDragPos(a);var s=i.dragOffset;if(r.onDrag&&s){var c=Object.assign({},t);c.lngLat=nl(a,s,n,o),r.onDrag(c)}}(e,t)},panend:function(e){return function(t,e){var n=e.props,r=e.callbacks,i=e.state,o=e.context;t.stopPropagation();var a=i.dragPos,s=i.dragOffset;if(i.setDragPos(null),i.setDragOffset(null),r.onDragEnd&&a&&s){var c=Object.assign({},t);c.lngLat=nl(a,s,n,o),r.onDragEnd(c)}}(e,t)},pancancel:function(e){var n;return n=t.state,void(e.stopPropagation(),n.setDragPos(null),n.setDragOffset(null))}};return e.watch(n),function(){e.off(n)}}}(c)},[c.context.eventManager,!!n]),c),l=u.state,p=u.containerRef,d=t.children,v=t.className,g=t.draggable,m=t.style,b=l.dragPos,y=function(t){var e=t.props,n=t.state,r=t.context,i=e.longitude,o=e.latitude,a=e.offsetLeft,s=e.offsetTop,c=n.dragPos,u=n.dragOffset,l=r.viewport,h=r.map;if(c&&u)return[c[0]+u[0],c[1]+u[1]];var p=tN(h,{longitude:i,latitude:o}),d=f(l.project([i,o,p]),2),v=d[0],g=d[1];return[v+=a,g+=s]}(u),w=f(y,2),O=w[0],E=w[1],_="translate(".concat(nf(O),"px, ").concat(nf(E),"px)"),P=g?b?"grabbing":"grab":"auto",M=(0,h.useMemo)(function(){var t=function(t){for(var e=1;e0){var g=p,m=v;for(p=0;p<=1;p+=.5)d=(f=n-p*a)+a,(v=Math.max(0,u-f)+Math.max(0,d-i+u))0){var E=h,_=O;for(h=0;h<=1;h+=b)w=(y=e-h*o)+o,(O=Math.max(0,u-y)+Math.max(0,w-r+u))<_&&(_=O,E=h);h=E}return nw.find(function(t){var e=ny[t];return e.x===h&&e.y===p})||s}({x:r,y:i,anchor:o,padding:s,width:S.width,height:S.height,selfWidth:e.clientWidth,selfHeight:e.clientHeight}):o),z=(c=M.current,l=(u=f(L,3))[0],p=u[1],d=u[2],v=t.offsetLeft,g=t.offsetTop,m=t.sortByDepth,y=nd(c,-(100*(b=ny[N]).x)),w=nd(c,-(100*b.y),"y"),O={position:"absolute",transform:"\n translate(".concat(y,"%, ").concat(w,"%)\n translate(").concat(nf(l+v),"px, ").concat(nf(p+g),"px)\n "),display:void 0,zIndex:void 0},m&&(d>1||d<-1||l<0||l>S.width||p<0||p>S.height?O.display="none":O.zIndex=Math.floor((1-d)/2*1e5)),O),F=(0,h.useCallback)(function(t){_.props.onClose();var e=_.context.eventManager;e&&e.once("click",function(t){return t.stopPropagation()},t.target)},[]);return h.createElement("div",{className:"mapboxgl-popup mapboxgl-popup-anchor-".concat(N," ").concat(k),style:z,ref:M},h.createElement("div",{key:"tip",className:"mapboxgl-popup-tip",style:{borderWidth:C}}),h.createElement("div",{key:"content",ref:E,className:"mapboxgl-popup-content"},R&&h.createElement("button",{key:"close-button",className:"mapboxgl-popup-close-button",type:"button",onClick:F},"×"),A))}function nP(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,r)}return n}n_.propTypes=nO,n_.defaultProps=nE,h.memo(n_);var nM=Object.assign({},ne,{toggleLabel:p.string,className:p.string,style:p.object,compact:p.bool,customAttribution:p.oneOfType([p.string,p.arrayOf(p.string)])}),nj=Object.assign({},nt,{className:"",toggleLabel:"Toggle Attribution"});function nS(t){var e=nn(t),n=e.context,r=e.containerRef,i=(0,h.useRef)(null),o=f((0,h.useState)(!1),2),s=o[0],c=o[1];(0,h.useEffect)(function(){var e,o,a,s,c,u;return n.map&&(o={customAttribution:t.customAttribution},a=n.map,s=r.current,c=i.current,(u=new(tE()).AttributionControl(o))._map=a,u._container=s,u._innerContainer=c,u._updateAttributions(),u._updateEditLink(),a.on("styledata",u._updateData),a.on("sourcedata",u._updateData),e=u),function(){var t;return e&&void((t=e)._map.off("styledata",t._updateData),t._map.off("sourcedata",t._updateData))}},[n.map]);var u=void 0===t.compact?n.viewport.width<=640:t.compact;(0,h.useEffect)(function(){!u&&s&&c(!1)},[u]);var l=(0,h.useCallback)(function(){return c(function(t){return!t})},[]),p=(0,h.useMemo)(function(){return function(t){for(var e=1;ea)return 1}return 0}(o.map.version,"1.6.0")>=0?2:1:2},[o.map]),n=o.viewport.bearing,r={transform:"rotate(".concat(-n,"deg)")},2===e?h.createElement("span",{className:"mapboxgl-ctrl-icon","aria-hidden":"true",style:r}):h.createElement("span",{className:"mapboxgl-ctrl-compass-arrow",style:r})))))}function nq(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,r)}return n}nU.propTypes=nF,nU.defaultProps=nV,h.memo(nU);var nH=Object.assign({},ne,{className:p.string,style:p.object,maxWidth:p.number,unit:p.oneOf(["imperial","metric","nautical"])}),nW=Object.assign({},nt,{className:"",maxWidth:100,unit:"metric"});function nY(t){var e=nn(t),n=e.context,r=e.containerRef,i=f((0,h.useState)(null),2),o=i[0],s=i[1];(0,h.useEffect)(function(){if(n.map){var t=new(tE()).ScaleControl;t._map=n.map,t._container=r.current,s(t)}},[n.map]),o&&(o.options=t,o._onMove());var c=(0,h.useMemo)(function(){return function(t){for(var e=1;e0)return function(e){if((e=String(e)).length>100)throw Error("Value exceeds the maximum length of 100 characters.");const s=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!s)return NaN;const r=parseFloat(s[1]),a=(s[2]||"ms").toLowerCase();switch(a){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*r;case"weeks":case"week":case"w":return 6048e5*r;case"days":case"day":case"d":return 864e5*r;case"hours":case"hour":case"hrs":case"hr":case"h":return 36e5*r;case"minutes":case"minute":case"mins":case"min":case"m":return 6e4*r;case"seconds":case"second":case"secs":case"sec":case"s":return 1e3*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:throw Error(`The unit ${a} was matched, but no matching case exists.`)}}(s);if("number"==typeof s&&isFinite(s))return r?.long?function(s){const r=Math.abs(s);return r>=864e5?e(s,r,864e5,"day"):r>=36e5?e(s,r,36e5,"hour"):r>=6e4?e(s,r,6e4,"minute"):r>=1e3?e(s,r,1e3,"second"):`${s} ms`}(s):function(e){const s=Math.abs(e);return s>=864e5?`${Math.round(e/864e5)}d`:s>=36e5?`${Math.round(e/36e5)}h`:s>=6e4?`${Math.round(e/6e4)}m`:s>=1e3?`${Math.round(e/1e3)}s`:`${e}ms`}(s);throw Error("Value is not a string or number.")}catch(r){const e="object"==typeof r&&null!==r&&"message"in r?`${r.message}. value=${JSON.stringify(s)}`:"An unknown error has occured.";throw Error(e)}}function e(e,s,r,a){return`${Math.round(e/r)} ${a}${s>=1.5*r?"s":""}`} +export default function(s,r){try{if("string"==typeof s&&s.length>0)return function(e){if((e=String(e)).length>100)throw Error("Value exceeds the maximum length of 100 characters.");const s=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!s)return NaN;const r=parseFloat(s[1]),a=(s[2]||"ms").toLowerCase();switch(a){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*r;case"weeks":case"week":case"w":return 6048e5*r;case"days":case"day":case"d":return 864e5*r;case"hours":case"hour":case"hrs":case"hr":case"h":return 36e5*r;case"minutes":case"minute":case"mins":case"min":case"m":return 6e4*r;case"seconds":case"second":case"secs":case"sec":case"s":return 1e3*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:throw Error(`The unit ${a} was matched, but no matching case exists.`)}}(s);if("number"==typeof s&&isFinite(s))return r?.long?function(s){const r=Math.abs(s);return r>=864e5?e(s,r,864e5,"day"):r>=36e5?e(s,r,36e5,"hour"):r>=6e4?e(s,r,6e4,"minute"):r>=1e3?e(s,r,1e3,"second"):`${s} ms`}(s):function(e){const s=Math.abs(e);return s>=864e5?`${Math.round(e/864e5)}d`:s>=36e5?`${Math.round(e/36e5)}h`:s>=6e4?`${Math.round(e/6e4)}m`:s>=1e3?`${Math.round(e/1e3)}s`:`${e}ms`}(s);throw Error("Value is not a string or number.")}catch(e){throw Error("object"==typeof e&&null!==e&&"message"in e?`${e.message}. value=${JSON.stringify(s)}`:"An unknown error has occured.")}}function e(e,s,r,a){return`${Math.round(e/r)} ${a}${s>=1.5*r?"s":""}`} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/drop_unused/issue_t161_top_retain_13/output.js b/crates/swc_ecma_minifier/tests/terser/compress/drop_unused/issue_t161_top_retain_13/output.js index c11b0842502f..345a6e561748 100644 --- a/crates/swc_ecma_minifier/tests/terser/compress/drop_unused/issue_t161_top_retain_13/output.js +++ b/crates/swc_ecma_minifier/tests/terser/compress/drop_unused/issue_t161_top_retain_13/output.js @@ -1,2 +1,2 @@ const g = ()=>y, y = 3; -console.log(2, y, 4, 2 * y, 8, 4 * y, 2, y, 4); +console.log(2, 3, 4, 6, 8, 12, 2, 3, 4); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/inline/inline_annotation_2/output.js b/crates/swc_ecma_minifier/tests/terser/compress/inline/inline_annotation_2/output.js index 1c740882ed42..d8e90e38b5d7 100644 --- a/crates/swc_ecma_minifier/tests/terser/compress/inline/inline_annotation_2/output.js +++ b/crates/swc_ecma_minifier/tests/terser/compress/inline/inline_annotation_2/output.js @@ -1,2 +1 @@ -const b = NaN; -console.log(42, b); +console.log(42, NaN); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/nullish/simplify_nullish_coalescing/output.js b/crates/swc_ecma_minifier/tests/terser/compress/nullish/simplify_nullish_coalescing/output.js index e0de561b68f4..4d8ab4b2beb0 100644 --- a/crates/swc_ecma_minifier/tests/terser/compress/nullish/simplify_nullish_coalescing/output.js +++ b/crates/swc_ecma_minifier/tests/terser/compress/nullish/simplify_nullish_coalescing/output.js @@ -1,3 +1,2 @@ -const y = id("one"); -console.log(y); +console.log(id("one")); console.log("two"); diff --git a/crates/swc_html_minifier/tests/fixture/attribute/exportparts/output.min.html b/crates/swc_html_minifier/tests/fixture/attribute/exportparts/output.min.html index 05e3d8909929..0ff10d128416 100644 --- a/crates/swc_html_minifier/tests/fixture/attribute/exportparts/output.min.html +++ b/crates/swc_html_minifier/tests/fixture/attribute/exportparts/output.min.html @@ -19,4 +19,4 @@ - \ No newline at end of file + \ No newline at end of file