diff --git a/crates/swc/tests/tsc-references/dependentDestructuredVariables_es2015.2.minified.js b/crates/swc/tests/tsc-references/dependentDestructuredVariables_es2015.2.minified.js index 630ce9adb51f..4ef56ceb0118 100644 --- a/crates/swc/tests/tsc-references/dependentDestructuredVariables_es2015.2.minified.js +++ b/crates/swc/tests/tsc-references/dependentDestructuredVariables_es2015.2.minified.js @@ -11,7 +11,6 @@ const reducer = (op, args)=>{ break; case "concat": console.log(args.firstArr.concat(args.secondArr)); - break; } }; reducer("add", { diff --git a/crates/swc/tests/tsc-references/dependentDestructuredVariables_es5.2.minified.js b/crates/swc/tests/tsc-references/dependentDestructuredVariables_es5.2.minified.js index a774abd671ed..c9883e6cceff 100644 --- a/crates/swc/tests/tsc-references/dependentDestructuredVariables_es5.2.minified.js +++ b/crates/swc/tests/tsc-references/dependentDestructuredVariables_es5.2.minified.js @@ -12,7 +12,6 @@ var reducer = function(op, args) { break; case "concat": console.log(args.firstArr.concat(args.secondArr)); - break; } }; reducer("add", { diff --git a/crates/swc/tests/tsc-references/parserRealSource6_es2015.2.minified.js b/crates/swc/tests/tsc-references/parserRealSource6_es2015.2.minified.js index 2982eec3655f..e064a1dd1a79 100644 --- a/crates/swc/tests/tsc-references/parserRealSource6_es2015.2.minified.js +++ b/crates/swc/tests/tsc-references/parserRealSource6_es2015.2.minified.js @@ -77,7 +77,6 @@ var TypeScript; context.skipNextFuncDeclForClass ? context.skipNextFuncDeclForClass = !1 : (context.scopeGetter = function() { return funcDecl.isConstructor && hasFlag(funcDecl.fncFlags, FncFlags.ClassMethod) && ast.type && ast.type.enclosingType ? ast.type.enclosingType.constructorScope : funcDecl.scopeType ? funcDecl.scopeType.containedScope : funcDecl.type ? funcDecl.type.containedScope : null; }, context.scopeStartAST = ast); - break; } walker.options.goChildren = !0; } else walker.options.goChildren = !1; diff --git a/crates/swc/tests/tsc-references/parserRealSource6_es5.2.minified.js b/crates/swc/tests/tsc-references/parserRealSource6_es5.2.minified.js index 1e503a595d6c..797d54b5ca1c 100644 --- a/crates/swc/tests/tsc-references/parserRealSource6_es5.2.minified.js +++ b/crates/swc/tests/tsc-references/parserRealSource6_es5.2.minified.js @@ -42,7 +42,6 @@ import * as swcHelpers from "@swc/helpers"; context.skipNextFuncDeclForClass ? context.skipNextFuncDeclForClass = !1 : (context.scopeGetter = function() { return funcDecl.isConstructor && hasFlag(funcDecl.fncFlags, FncFlags.ClassMethod) && ast.type && ast.type.enclosingType ? ast.type.enclosingType.constructorScope : funcDecl.scopeType ? funcDecl.scopeType.containedScope : funcDecl.type ? funcDecl.type.containedScope : null; }, context.scopeStartAST = ast); - break; } walker.options.goChildren = !0; } else walker.options.goChildren = !1; diff --git a/crates/swc/tests/tsc-references/parserindenter_es2015.2.minified.js b/crates/swc/tests/tsc-references/parserindenter_es2015.2.minified.js index 7e4be735e862..4382e8b8ded4 100644 --- a/crates/swc/tests/tsc-references/parserindenter_es2015.2.minified.js +++ b/crates/swc/tests/tsc-references/parserindenter_es2015.2.minified.js @@ -246,7 +246,6 @@ var Formatting; break; case AuthorTokenKind.atkLBrack: updateStartOffset = node.AuthorNode.Details.Kind == AuthorParseNodeKind.apnkArray; - break; } updateStartOffset && ParseNodeExtensions.SetNodeSpan(node, token.Span.startPosition(), node.AuthorNode.Details.EndOffset); } diff --git a/crates/swc/tests/tsc-references/parserindenter_es5.2.minified.js b/crates/swc/tests/tsc-references/parserindenter_es5.2.minified.js index d3d1fbbc9883..d202a95c2319 100644 --- a/crates/swc/tests/tsc-references/parserindenter_es5.2.minified.js +++ b/crates/swc/tests/tsc-references/parserindenter_es5.2.minified.js @@ -219,7 +219,6 @@ import * as swcHelpers from "@swc/helpers"; break; case AuthorTokenKind.atkLBrack: updateStartOffset = node.AuthorNode.Details.Kind == AuthorParseNodeKind.apnkArray; - break; } updateStartOffset && ParseNodeExtensions.SetNodeSpan(node, token.Span.startPosition(), node.AuthorNode.Details.EndOffset); } diff --git a/crates/swc/tests/tsc-references/stringLiteralMatchedInSwitch01_es2015.2.minified.js b/crates/swc/tests/tsc-references/stringLiteralMatchedInSwitch01_es2015.2.minified.js index 0a458489f2d9..292febe1edee 100644 --- a/crates/swc/tests/tsc-references/stringLiteralMatchedInSwitch01_es2015.2.minified.js +++ b/crates/swc/tests/tsc-references/stringLiteralMatchedInSwitch01_es2015.2.minified.js @@ -5,5 +5,4 @@ switch(foo){ break; default: foo = foo[0]; - break; } diff --git a/crates/swc/tests/tsc-references/stringLiteralMatchedInSwitch01_es5.2.minified.js b/crates/swc/tests/tsc-references/stringLiteralMatchedInSwitch01_es5.2.minified.js index 0a458489f2d9..292febe1edee 100644 --- a/crates/swc/tests/tsc-references/stringLiteralMatchedInSwitch01_es5.2.minified.js +++ b/crates/swc/tests/tsc-references/stringLiteralMatchedInSwitch01_es5.2.minified.js @@ -5,5 +5,4 @@ switch(foo){ break; default: foo = foo[0]; - break; } diff --git a/crates/swc/tests/tsc-references/switchBreakStatements_es2015.2.minified.js b/crates/swc/tests/tsc-references/switchBreakStatements_es2015.2.minified.js index e69de29bb2d1..872a4b1cc7f0 100644 --- a/crates/swc/tests/tsc-references/switchBreakStatements_es2015.2.minified.js +++ b/crates/swc/tests/tsc-references/switchBreakStatements_es2015.2.minified.js @@ -0,0 +1,6 @@ +''; +ONE: ''; +TWO: THREE: ''; +FOUR: ''; +''; +SEVEN: ''; diff --git a/crates/swc/tests/tsc-references/switchBreakStatements_es5.2.minified.js b/crates/swc/tests/tsc-references/switchBreakStatements_es5.2.minified.js index e69de29bb2d1..700463322f80 100644 --- a/crates/swc/tests/tsc-references/switchBreakStatements_es5.2.minified.js +++ b/crates/swc/tests/tsc-references/switchBreakStatements_es5.2.minified.js @@ -0,0 +1,6 @@ +""; +ONE: ""; +TWO: THREE: ""; +FOUR: ""; +""; +SEVEN: ""; diff --git a/crates/swc/tests/tsc-references/switchStatements_es2015.2.minified.js b/crates/swc/tests/tsc-references/switchStatements_es2015.2.minified.js index 02337d664162..48fafa369072 100644 --- a/crates/swc/tests/tsc-references/switchStatements_es2015.2.minified.js +++ b/crates/swc/tests/tsc-references/switchStatements_es2015.2.minified.js @@ -5,4 +5,5 @@ var M; } M1.fn = fn; }(M || (M = {})), new class { -}(), new Object(); +}(), new Object(), (x)=>'' +; diff --git a/crates/swc/tests/tsc-references/throwInEnclosingStatements_es2015.2.minified.js b/crates/swc/tests/tsc-references/throwInEnclosingStatements_es2015.2.minified.js index ca0f2235b0da..7c0b37df7d9b 100644 --- a/crates/swc/tests/tsc-references/throwInEnclosingStatements_es2015.2.minified.js +++ b/crates/swc/tests/tsc-references/throwInEnclosingStatements_es2015.2.minified.js @@ -1,11 +1 @@ -var y; -switch(y){ - case 'a': - throw y; - default: - throw y; -} -for(;;)throw 0; -for(;;)throw 0; -for(var idx in {})throw idx; -for(;;)throw null; +throw void 0; diff --git a/crates/swc/tests/tsc-references/throwInEnclosingStatements_es5.2.minified.js b/crates/swc/tests/tsc-references/throwInEnclosingStatements_es5.2.minified.js index 121d8fea41fa..74ea1fc27bd1 100644 --- a/crates/swc/tests/tsc-references/throwInEnclosingStatements_es5.2.minified.js +++ b/crates/swc/tests/tsc-references/throwInEnclosingStatements_es5.2.minified.js @@ -1,20 +1,3 @@ +var y; import * as swcHelpers from "@swc/helpers"; -switch(y){ - case "a": - throw y; - default: - throw y; -} -for(;;)throw 0; -for(;;)throw 0; -for(var idx in {})throw idx; -for(;;)throw null; -var y, C = function() { - "use strict"; - function C() { - throw swcHelpers.classCallCheck(this, C), this; - } - return C.prototype.biz = function() { - throw this.value; - }, C; -}(); +throw y; diff --git a/crates/swc/tests/tsc-references/typeGuardOfFormFunctionEquality_es2015.2.minified.js b/crates/swc/tests/tsc-references/typeGuardOfFormFunctionEquality_es2015.2.minified.js index 3d01e9dbaf6d..de5c4ada3a81 100644 --- a/crates/swc/tests/tsc-references/typeGuardOfFormFunctionEquality_es2015.2.minified.js +++ b/crates/swc/tests/tsc-references/typeGuardOfFormFunctionEquality_es2015.2.minified.js @@ -1 +1 @@ -isString1(0, ""), isString1(0, ""), isString2(""); +isString1(0, ""), isString2(""), isString1(0, ""), isString2(""); diff --git a/crates/swc/tests/tsc-references/typeGuardOfFormFunctionEquality_es5.2.minified.js b/crates/swc/tests/tsc-references/typeGuardOfFormFunctionEquality_es5.2.minified.js index 3d01e9dbaf6d..de5c4ada3a81 100644 --- a/crates/swc/tests/tsc-references/typeGuardOfFormFunctionEquality_es5.2.minified.js +++ b/crates/swc/tests/tsc-references/typeGuardOfFormFunctionEquality_es5.2.minified.js @@ -1 +1 @@ -isString1(0, ""), isString1(0, ""), isString2(""); +isString1(0, ""), isString2(""), isString1(0, ""), isString2(""); diff --git a/crates/swc_ecma_ast/src/stmt.rs b/crates/swc_ecma_ast/src/stmt.rs index 071efdd911e4..2e7edc2dc274 100644 --- a/crates/swc_ecma_ast/src/stmt.rs +++ b/crates/swc_ecma_ast/src/stmt.rs @@ -345,6 +345,16 @@ pub struct SwitchCase { pub cons: Vec, } +impl Take for SwitchCase { + fn dummy() -> Self { + Self { + span: DUMMY_SP, + test: None, + cons: Vec::new(), + } + } +} + #[ast_node("CatchClause")] #[derive(Eq, Hash, EqIgnoreSpan)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] diff --git a/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs b/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs index 29ee9bd75ca8..57d0cd944406 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/conditionals.rs @@ -3,14 +3,11 @@ use std::mem::swap; use swc_common::{util::take::Take, EqIgnoreSpan, Spanned, DUMMY_SP}; use swc_ecma_ast::*; use swc_ecma_transforms_base::ext::ExprRefExt; -use swc_ecma_utils::{ident::IdentLike, ExprExt, ExprFactory, StmtLike}; +use swc_ecma_utils::{ident::IdentLike, ExprExt, ExprFactory, StmtExt, StmtLike}; use super::Optimizer; use crate::{ - compress::{ - optimize::Ctx, - util::{always_terminates, negate_cost}, - }, + compress::{optimize::Ctx, util::negate_cost}, mode::Mode, DISABLE_BUGGY_PASSES, }; @@ -701,7 +698,7 @@ where cons, alt: Some(..), .. - })) => always_terminates(cons), + })) => cons.terminates(), _ => false, }); if !need_work { @@ -720,7 +717,7 @@ where cons, alt: Some(alt), .. - }) if always_terminates(&cons) => { + }) if cons.terminates() => { new_stmts.push(T::from_stmt(Stmt::If(IfStmt { span, test, diff --git a/crates/swc_ecma_minifier/src/compress/optimize/if_return.rs b/crates/swc_ecma_minifier/src/compress/optimize/if_return.rs index b83c7266af41..e7b706b8c8d3 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/if_return.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/if_return.rs @@ -1,15 +1,10 @@ use swc_common::{util::take::Take, Spanned, DUMMY_SP}; use swc_ecma_ast::*; -use swc_ecma_utils::{prepend, undefined, StmtLike}; +use swc_ecma_utils::{prepend, undefined, StmtExt, StmtLike}; use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; use super::Optimizer; -use crate::{ - compress::util::{always_terminates, is_pure_undefined}, - debug::dump, - mode::Mode, - util::ExprOptExt, -}; +use crate::{compress::util::is_pure_undefined, debug::dump, mode::Mode, util::ExprOptExt}; /// Methods related to the option `if_return`. All methods are noop if /// `if_return` is false. @@ -587,7 +582,7 @@ fn always_terminates_with_return_arg(s: &Stmt) -> bool { fn can_merge_as_if_return(s: &Stmt) -> bool { fn cost(s: &Stmt) -> Option { if let Stmt::Block(..) = s { - if !always_terminates(s) { + if !s.terminates() { return None; } } diff --git a/crates/swc_ecma_minifier/src/compress/optimize/mod.rs b/crates/swc_ecma_minifier/src/compress/optimize/mod.rs index 9917a34be46a..6a65073cf219 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/mod.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/mod.rs @@ -12,8 +12,8 @@ use swc_common::{ }; use swc_ecma_ast::*; use swc_ecma_utils::{ - ident::IdentLike, prepend_stmts, undefined, ExprExt, ExprFactory, Id, IsEmpty, ModuleItemLike, - StmtLike, Type, Value, + extract_var_ids, ident::IdentLike, prepend_stmts, undefined, ExprExt, ExprFactory, Id, IsEmpty, + ModuleItemLike, StmtLike, Type, Value, }; use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith, VisitWith}; use tracing::{debug, span, Level}; @@ -133,8 +133,6 @@ struct Ctx { /// `true` while handling `expr` of `!expr` in_bang_arg: bool, in_var_decl_of_for_in_or_of_loop: bool, - /// `true` while handling inner statements of a labelled statement. - stmt_labelled: bool, dont_use_negated_iife: bool, @@ -1551,7 +1549,6 @@ where #[cfg_attr(feature = "debug", tracing::instrument(skip_all))] fn visit_mut_block_stmt(&mut self, n: &mut BlockStmt) { let ctx = Ctx { - stmt_labelled: false, top_level: false, in_block: true, scope: n.span.ctxt, @@ -1957,13 +1954,7 @@ where #[cfg_attr(feature = "debug", tracing::instrument(skip_all))] fn visit_mut_function(&mut self, n: &mut Function) { - { - let ctx = Ctx { - stmt_labelled: false, - ..self.ctx - }; - n.decorators.visit_mut_with(&mut *self.with_ctx(ctx)); - } + n.decorators.visit_mut_with(self); let is_standalone = n.span.has_mark(self.marks.standalone); @@ -1978,7 +1969,6 @@ where { let ctx = Ctx { skip_standalone: self.ctx.skip_standalone || is_standalone, - stmt_labelled: false, in_fn_like: true, scope: n.span.ctxt, can_inline_arguments: true, @@ -2044,13 +2034,9 @@ where #[cfg_attr(feature = "debug", tracing::instrument(skip_all))] fn visit_mut_labeled_stmt(&mut self, n: &mut LabeledStmt) { - let ctx = Ctx { - stmt_labelled: true, - ..self.ctx - }; let old_label = self.label.take(); self.label = Some(n.label.to_id()); - n.visit_mut_children_with(&mut *self.with_ctx(ctx)); + n.visit_mut_children_with(self); if self.label.is_none() { report_change!("Removing label `{}`", n.label); @@ -2511,6 +2497,77 @@ where if cfg!(debug_assertions) { stmts.visit_with(&mut AssertValid); } + + if self.options.dead_code { + // copy from [Remover] + // TODO: make it better + let orig_len = stmts.len(); + + let mut new_stmts = Vec::with_capacity(stmts.len()); + + let mut iter = stmts.take().into_iter(); + while let Some(stmt) = iter.next() { + let stmt = match stmt { + // Remove empty statements. + Stmt::Empty(..) => continue, + + // Control flow + Stmt::Throw(..) + | Stmt::Return { .. } + | Stmt::Continue { .. } + | Stmt::Break { .. } => { + // Hoist function and `var` declarations above return. + let mut decls = vec![]; + let mut hoisted_fns = vec![]; + for t in iter { + match t.try_into_stmt() { + Ok(Stmt::Decl(Decl::Fn(f))) => { + hoisted_fns.push(Stmt::Decl(Decl::Fn(f))); + } + Ok(t) => { + let ids = + extract_var_ids(&t).into_iter().map(|i| VarDeclarator { + span: i.span, + name: i.into(), + init: None, + definite: false, + }); + decls.extend(ids); + } + Err(item) => new_stmts.push(item), + } + } + + if !decls.is_empty() { + new_stmts.push(Stmt::Decl(Decl::Var(VarDecl { + span: DUMMY_SP, + kind: VarDeclKind::Var, + decls, + declare: false, + }))); + } + + new_stmts.push(stmt); + new_stmts.extend(hoisted_fns); + + *stmts = new_stmts; + if stmts.len() != orig_len { + self.changed = true; + + report_change!("Dropping statements after a control keyword"); + } + + return; + } + + _ => stmt, + }; + + new_stmts.push(stmt); + } + + *stmts = new_stmts; + } } fn visit_mut_str(&mut self, s: &mut Str) { @@ -2540,8 +2597,6 @@ where fn visit_mut_switch_stmt(&mut self, n: &mut SwitchStmt) { n.discriminant.visit_mut_with(self); - self.drop_unreachable_cases(n); - n.cases.visit_mut_with(self); } diff --git a/crates/swc_ecma_minifier/src/compress/optimize/switches.rs b/crates/swc_ecma_minifier/src/compress/optimize/switches.rs index 8834cade3314..9774c4456284 100644 --- a/crates/swc_ecma_minifier/src/compress/optimize/switches.rs +++ b/crates/swc_ecma_minifier/src/compress/optimize/switches.rs @@ -1,12 +1,10 @@ -use std::mem::take; - -use swc_common::{util::take::Take, EqIgnoreSpan, DUMMY_SP}; +use swc_common::{util::take::Take, EqIgnoreSpan, Spanned, DUMMY_SP}; use swc_ecma_ast::*; -use swc_ecma_utils::{ident::IdentLike, prepend, ExprExt, StmtExt, Type, Value::Known}; +use swc_ecma_utils::{prepend, ExprExt, ExprFactory, StmtExt}; use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; use super::Optimizer; -use crate::{mode::Mode, util::ExprOptExt}; +use crate::{compress::util::is_primitive, mode::Mode}; /// Methods related to option `switches`. impl Optimizer<'_, M> @@ -16,171 +14,147 @@ where /// Handle switches in the case where we can know which branch will be /// taken. pub(super) fn optimize_const_switches(&mut self, s: &mut Stmt) { - if !self.options.switches || self.ctx.stmt_labelled { + if !self.options.switches || !self.options.dead_code { return; } - let (label, stmt) = match s { - Stmt::Switch(s) => (None, s), - Stmt::Labeled(l) => match &mut *l.body { - Stmt::Switch(s) => (Some(l.label.clone()), s), - _ => return, - }, + let stmt = match s { + Stmt::Switch(s) => s, _ => return, }; - let discriminant = &mut stmt.discriminant; - if let Expr::Update(..) = &**discriminant { - return; - } - - if stmt - .cases - .iter() - .any(|case| matches!(case.test.as_deref(), Some(Expr::Update(..)))) - { - return; + // TODO: evaluate + fn tail_expr(e: &Expr) -> &Expr { + match e { + Expr::Seq(s) => s.exprs.last().unwrap(), + _ => e, + } } - let matching_case = stmt.cases.iter_mut().position(|case| { - case.test - .as_ref() - .map(|test| discriminant.value_mut().eq_ignore_span(test)) - .unwrap_or(false) - }); + let discriminant = &mut stmt.discriminant; - if let Some(case_idx) = matching_case { - let mut var_ids = vec![]; - let mut stmts = vec![]; + let tail = if let Some(e) = is_primitive(tail_expr(discriminant)) { + e + } else { + return; + }; - let should_preserve_switch = stmt.cases.iter().skip(case_idx).any(|case| { - let mut v = BreakFinder { - found_unlabelled_break_for_stmt: false, - }; - case.visit_with(&mut v); - v.found_unlabelled_break_for_stmt - }); - if should_preserve_switch { - // Prevent infinite loop. - if stmt.cases.len() == 1 { - return; + let mut var_ids = vec![]; + let mut cases = Vec::new(); + let mut exact = None; + + for (idx, case) in stmt.cases.iter_mut().enumerate() { + if let Some(test) = case.test.as_ref() { + if let Some(e) = is_primitive(tail_expr(test)) { + if e.eq_ignore_span(tail) { + cases.push(case.take()); + exact = Some(idx); + break; + } else { + var_ids.extend(case.cons.extract_var_ids()) + } + } else { + cases.push(case.take()) } - - report_change!("switches: Removing unreachable cases from a constant switch"); } else { - report_change!("switches: Removing a constant switch"); + cases.push(case.take()) } + } - self.changed = true; - let mut preserved = vec![]; - if !should_preserve_switch && !discriminant.is_lit() { - preserved.push(Stmt::Expr(ExprStmt { - span: stmt.span, - expr: discriminant.take(), - })); - - if let Some(expr) = stmt.cases[case_idx].test.take() { - preserved.push(Stmt::Expr(ExprStmt { - span: stmt.cases[case_idx].span, - expr, - })); + if let Some(exact) = exact { + let exact_case = cases.last_mut().unwrap(); + let mut terminate = exact_case.cons.terminates(); + for case in stmt.cases[(exact + 1)..].iter_mut() { + if terminate { + var_ids.extend(case.cons.extract_var_ids()) + } else { + terminate |= case.cons.terminates(); + exact_case.cons.extend(case.cons.take()) } } + // remove default if there's an exact match + cases.retain(|case| case.test.is_some()); - for case in &stmt.cases[..case_idx] { - for cons in &case.cons { - var_ids.extend( - cons.extract_var_ids() - .into_iter() - .map(|name| VarDeclarator { - span: DUMMY_SP, - name: Pat::Ident(name.into()), - init: None, - definite: Default::default(), - }), - ); + if cases.len() == 2 { + let last = cases.last_mut().unwrap(); + + self.changed = true; + report_change!("switches: Turn exact match into default"); + // so that following pass could turn it into if else + if let Some(test) = last.test.take() { + prepend(&mut last.cons, test.into_stmt()) } } + } - for case in stmt.cases.iter_mut().skip(case_idx) { - let mut found_break = false; - case.cons.retain(|stmt| match stmt { - Stmt::Break(BreakStmt { label: None, .. }) => { - found_break = true; - false - } + if cases.len() == stmt.cases.len() { + stmt.cases = cases; + return; + } - // TODO: Search recursively. - Stmt::Break(BreakStmt { - label: Some(break_label), - .. - }) => { - if Some(break_label.to_id()) == label.as_ref().map(|label| label.to_id()) { - found_break = true; - false - } else { - !found_break - } - } - _ => !found_break, - }); - - for case_stmt in case.cons.take() { - match case_stmt { - Stmt::Decl(Decl::Var(v)) if v.decls.iter().all(|v| v.init.is_none()) => { - var_ids.extend(v.decls) - } - _ => { - stmts.push(case_stmt); - } - } - } - if found_break { - break; - } - } + self.optimize_switch_cases(&mut cases); + + let var_ids: Vec = var_ids + .into_iter() + .map(|name| VarDeclarator { + span: DUMMY_SP, + name: Pat::Ident(name.into()), + init: None, + definite: Default::default(), + }) + .collect(); + + self.changed = true; + + if cases.len() == 1 + && (cases[0].test.is_none() || exact.is_some()) + && !contains_nested_break(&cases[0]) + { + report_change!("switches: Removing a constant switch"); + + let mut stmts = Vec::new(); if !var_ids.is_empty() { - prepend( - &mut stmts, - Stmt::Decl(Decl::Var(VarDecl { - span: DUMMY_SP, - kind: VarDeclKind::Var, - declare: Default::default(), - decls: take(&mut var_ids), - })), - ) + stmts.push(Stmt::Decl(Decl::Var(VarDecl { + span: DUMMY_SP, + kind: VarDeclKind::Var, + declare: Default::default(), + decls: var_ids, + }))) } - let inner = if should_preserve_switch { - let mut cases = stmt.cases.take(); - let case = SwitchCase { - span: cases[case_idx].span, - test: cases[case_idx].test.take(), - cons: stmts, - }; + stmts.push(discriminant.take().into_stmt()); + let mut last = cases.pop().unwrap(); + remove_last_break(&mut last.cons); - Stmt::Switch(SwitchStmt { - span: stmt.span, - discriminant: stmt.discriminant.take(), - cases: vec![case], - }) - } else { - preserved.extend(stmts); - Stmt::Block(BlockStmt { - span: DUMMY_SP, - stmts: preserved, - }) - }; + if let Some(test) = last.test { + stmts.push(test.into_stmt()); + } + + stmts.extend(last.cons); + *s = Stmt::Block(BlockStmt { + span: DUMMY_SP, + stmts, + }) + } else { + report_change!("switches: Removing unreachable cases from a constant switch"); - *s = match label { - Some(label) => Stmt::Labeled(LabeledStmt { + stmt.cases = cases; + + if !var_ids.is_empty() { + *s = Stmt::Block(BlockStmt { span: DUMMY_SP, - label, - body: Box::new(inner), - }), - None => inner, - }; + stmts: vec![ + Stmt::Decl(Decl::Var(VarDecl { + span: DUMMY_SP, + kind: VarDeclKind::Var, + declare: Default::default(), + decls: var_ids, + })), + s.take(), + ], + }) + } } } @@ -189,183 +163,345 @@ where /// This method will /// /// - drop the empty cases at the end. + /// - drop break at last case + /// - merge branch with default at the end pub(super) fn optimize_switch_cases(&mut self, cases: &mut Vec) { - if !self.options.switches { + if !self.options.switches || !self.options.dead_code || cases.is_empty() { return; } - // If default is not last, we can't remove empty cases. - let has_default = cases.iter().any(|case| case.test.is_none()); - let all_ends_with_break = cases - .iter() - .all(|case| case.cons.is_empty() || case.cons.last().unwrap().is_break_stmt()); - let mut preserve_cases = false; - if !all_ends_with_break && has_default { - if let Some(last) = cases.last() { - if last.test.is_some() { - preserve_cases = true; - } - } - } - self.merge_cases_with_same_cons(cases); - let last_non_empty = cases.iter().rposition(|case| { - // We should preserve test cases if the test is not a literal. - match case.test.as_deref() { - Some(Expr::Lit(..)) | None => {} - _ => return true, - } + // last case with no empty body + let mut last = cases.len(); - if case.cons.is_empty() { - return false; - } + for (idx, case) in cases.iter_mut().enumerate().rev() { + self.changed |= remove_last_break(&mut case.cons); - if case.cons.len() == 1 { - if let Stmt::Break(BreakStmt { label: None, .. }) = case.cons[0] { - return false; - } + if !case.cons.is_empty() { + last = idx + 1; + break; } + } - true + let has_side_effect = cases.iter().skip(last).rposition(|case| { + case.test + .as_deref() + .map(|test| test.may_have_side_effects()) + .unwrap_or(false) }); - if !preserve_cases { - if let Some(last_non_empty) = last_non_empty { - if last_non_empty + 1 != cases.len() { - report_change!("switches: Removing empty cases at the end"); - self.changed = true; - cases.drain(last_non_empty + 1..); - } - } + if let Some(has_side_effect) = has_side_effect { + last += has_side_effect + 1 } - if let Some(last) = cases.last_mut() { - if let Some(Stmt::Break(BreakStmt { label: None, .. })) = last.cons.last() { - report_change!("switches: Removing `break` at the end"); - self.changed = true; - last.cons.pop(); + let default = cases.iter().position(|case| case.test.is_none()); + + // if default is before empty cases, we must ensure empty case is preserved + if last < cases.len() && default.map(|idx| idx >= last).unwrap_or(true) { + self.changed = true; + report_change!("switches: Removing empty cases at the end"); + cases.drain(last..); + } + + if let Some(default) = default { + let end = cases + .iter() + .skip(default) + .position(|case| !case.cons.is_empty()) + .unwrap_or(0) + + default; + + if end != cases.len() - 1 { + return; + } + let start = cases.iter().enumerate().rposition(|(idx, case)| { + case.test + .as_deref() + .map(|test| test.may_have_side_effects()) + .unwrap_or(false) + || (idx != end && !case.cons.is_empty()) + }); + + let start = start.map(|s| s + 1).unwrap_or(0); + + if start <= default { + if start < end { + cases[start].cons = cases[end].cons.take(); + cases.drain((start + 1)..); + cases[start].test = None; + } + } else { + if start <= end { + cases[start].cons = cases[end].cons.take(); + cases.drain(start..); + } } } } - /// If a case ends with break but content is same with the consecutive case - /// except the break statement, we merge them. + /// If a case ends with break but content is same with the another case + /// without break case order, except the break statement, we merge + /// them. fn merge_cases_with_same_cons(&mut self, cases: &mut Vec) { - let mut stop_pos_opt = cases - .iter() - .position(|case| matches!(case.test.as_deref(), Some(Expr::Update(..)))); + let mut i = 0; + let len = cases.len(); - let mut found = None; - 'l: for (li, l) in cases.iter().enumerate().rev() { - if l.cons.is_empty() { + // may some smarter person find a better solution + while i < len { + if cases[i].cons.is_empty() { + i += 1; continue; } - - if let Some(stop_pos) = stop_pos_opt { - if li == stop_pos { - // Look for next stop position - stop_pos_opt = cases - .iter() - .skip(li) - .position(|case| matches!(case.test.as_deref(), Some(Expr::Update(..)))) - .map(|v| v + li); + let mut block_start = i + 1; + let mut cannot_cross_block = false; + + for j in (i + 1)..len { + cannot_cross_block |= cases[j] + .test + .as_deref() + .map(|test| is_primitive(test).is_none()) + .unwrap_or(false) + || !(cases[j].cons.is_empty() + || cases[j].cons.terminates() + || j == cases.len() - 1); + + if cases[j].cons.is_empty() { continue; } - } - - if let Some(l_last) = l.cons.last() { - match l_last { - Stmt::Break(BreakStmt { label: None, .. }) => {} - _ => continue, - } - } - for r in cases.iter().skip(li + 1) { - if r.cons.is_empty() { - continue; + if cannot_cross_block && block_start != i + 1 { + break; } - let mut r_cons_slice = r.cons.len(); + block_start = j + 1; - if let Some(Stmt::Break(BreakStmt { label: None, .. })) = r.cons.last() { - r_cons_slice -= 1; - } + // first case with a body and don't cross non-primitive branch + let found = if j != len - 1 { + cases[i].cons.eq_ignore_span(&cases[j].cons) + } else { + if let Some(Stmt::Break(BreakStmt { label: None, .. })) = cases[i].cons.last() { + cases[i].cons[..(cases[i].cons.len() - 1)].eq_ignore_span(&cases[j].cons) + } else { + cases[i].cons.eq_ignore_span(&cases[j].cons) + } + }; - if l.cons[..l.cons.len() - 1].eq_ignore_span(&r.cons[..r_cons_slice]) { - found = Some(li); - break 'l; + if found { + self.changed = true; + report_change!("switches: Merging cases with same cons"); + let mut len = 1; + while len < j && cases[j - len].cons.is_empty() { + len += 1; + } + cases[j].cons = cases[i].cons.take(); + cases[(i + 1)..=j].rotate_right(len); + i += len; } } - } - if let Some(idx) = found { - self.changed = true; - report_change!("switches: Merging cases with same cons"); - cases[idx].cons.clear(); + i += 1; } } - /// Remove unreachable cases using discriminant. - pub(super) fn drop_unreachable_cases(&mut self, s: &mut SwitchStmt) { - if !self.options.switches { + /// Try turn switch into if and remove empty switch + pub(super) fn optimize_switches(&mut self, s: &mut Stmt) { + if !self.options.switches || !self.options.dead_code { return; } - let dt = s.discriminant.get_type(); - - if let Known(Type::Bool) = dt { - let db = s.discriminant.as_pure_bool(); - - if let Known(db) = db { - s.cases.retain(|case| match case.test.as_deref() { - Some(test) => { - let tb = test.as_pure_bool(); - !matches!(tb, Known(tb) if db != tb) + if let Stmt::Switch(sw) = s { + match &mut *sw.cases { + [] => { + self.changed = true; + report_change!("switches: Removing empty switch"); + *s = Stmt::Expr(ExprStmt { + span: sw.span, + expr: sw.discriminant.take(), + }) + } + [case] => { + if contains_nested_break(case) { + return; } - None => false, - }) + self.changed = true; + report_change!("switches: Turn one case switch into if"); + remove_last_break(&mut case.cons); + + let case = case.take(); + let discriminant = sw.discriminant.take(); + + if let Some(test) = case.test { + let test = Box::new(Expr::Bin(BinExpr { + left: discriminant, + right: test, + op: op!("==="), + span: DUMMY_SP, + })); + + *s = Stmt::If(IfStmt { + span: sw.span, + test, + cons: Box::new(Stmt::Block(BlockStmt { + span: DUMMY_SP, + stmts: case.cons, + })), + alt: None, + }) + } else { + // is default + let mut stmts = vec![Stmt::Expr(ExprStmt { + span: discriminant.span(), + expr: discriminant, + })]; + stmts.extend(case.cons); + *s = Stmt::Block(BlockStmt { + span: sw.span, + stmts, + }) + } + } + [first, second] if first.test.is_none() || second.test.is_none() => { + if contains_nested_break(first) || contains_nested_break(second) { + return; + } + self.changed = true; + report_change!("switches: Turn two cases switch into if else"); + let terminate = first.cons.terminates(); + + if terminate { + remove_last_break(&mut first.cons); + // they cannot both be default as that's syntax error + let (def, case) = if first.test.is_none() { + (first, second) + } else { + (second, first) + }; + *s = Stmt::If(IfStmt { + span: sw.span, + test: Expr::Bin(BinExpr { + span: DUMMY_SP, + op: op!("==="), + left: sw.discriminant.take(), + right: case.test.take().unwrap(), + }) + .into(), + cons: Stmt::Block(BlockStmt { + span: DUMMY_SP, + stmts: case.cons.take(), + }) + .into(), + alt: Some( + Stmt::Block(BlockStmt { + span: DUMMY_SP, + stmts: def.cons.take(), + }) + .into(), + ), + }) + } else { + let mut stmts = vec![Stmt::If(IfStmt { + span: DUMMY_SP, + test: Expr::Bin(if first.test.is_none() { + BinExpr { + span: DUMMY_SP, + op: op!("!=="), + left: sw.discriminant.take(), + right: second.test.take().unwrap(), + } + } else { + BinExpr { + span: DUMMY_SP, + op: op!("==="), + left: sw.discriminant.take(), + right: first.test.take().unwrap(), + } + }) + .into(), + cons: Stmt::Block(BlockStmt { + span: DUMMY_SP, + stmts: first.cons.take(), + }) + .into(), + alt: None, + })]; + stmts.extend(second.cons.take()); + *s = Stmt::Block(BlockStmt { + span: sw.span, + stmts, + }) + } + } + _ => (), } } } +} - pub(super) fn optimize_switches(&mut self, _s: &mut Stmt) { - if !self.options.switches || self.ctx.stmt_labelled {} - - // +fn remove_last_break(stmt: &mut Vec) -> bool { + if let Some(Stmt::Break(BreakStmt { label: None, .. })) = stmt.last() { + report_change!("switches: Removing `break` at the end"); + stmt.pop(); + true + } else { + false } } +fn contains_nested_break(case: &SwitchCase) -> bool { + let mut v = BreakFinder { + top_level: true, + nested_unlabelled_break: false, + }; + case.visit_with(&mut v); + v.nested_unlabelled_break +} + #[derive(Default)] struct BreakFinder { - found_unlabelled_break_for_stmt: bool, + top_level: bool, + nested_unlabelled_break: bool, } impl Visit for BreakFinder { noop_visit_type!(); fn visit_break_stmt(&mut self, s: &BreakStmt) { - if s.label.is_none() { - self.found_unlabelled_break_for_stmt = true; + if !self.top_level && s.label.is_none() { + self.nested_unlabelled_break = true; } } - /// We don't care about breaks in a lop[ + fn visit_if_stmt(&mut self, i: &IfStmt) { + if self.top_level { + self.top_level = false; + i.visit_children_with(self); + self.top_level = true; + } else { + i.visit_children_with(self); + } + } + + /// We don't care about breaks in a loop fn visit_for_stmt(&mut self, _: &ForStmt) {} - /// We don't care about breaks in a lop[ + /// We don't care about breaks in a loop fn visit_for_in_stmt(&mut self, _: &ForInStmt) {} - /// We don't care about breaks in a lop[ + /// We don't care about breaks in a loop fn visit_for_of_stmt(&mut self, _: &ForOfStmt) {} - /// We don't care about breaks in a lop[ + /// We don't care about breaks in a loop fn visit_do_while_stmt(&mut self, _: &DoWhileStmt) {} - /// We don't care about breaks in a lop[ + /// We don't care about breaks in a loop fn visit_while_stmt(&mut self, _: &WhileStmt) {} + fn visit_switch_stmt(&mut self, _: &SwitchStmt) {} + fn visit_function(&mut self, _: &Function) {} fn visit_arrow_expr(&mut self, _: &ArrowExpr) {} + + fn visit_class(&mut self, _: &Class) {} } diff --git a/crates/swc_ecma_minifier/src/compress/pure/dead_code.rs b/crates/swc_ecma_minifier/src/compress/pure/dead_code.rs index 56c615f9aa9f..72583c13b689 100644 --- a/crates/swc_ecma_minifier/src/compress/pure/dead_code.rs +++ b/crates/swc_ecma_minifier/src/compress/pure/dead_code.rs @@ -4,10 +4,7 @@ use swc_ecma_utils::{ExprExt, StmtExt, StmtLike, Value}; use swc_ecma_visit::{noop_visit_type, Visit, VisitWith}; use super::Pure; -use crate::{ - compress::util::{always_terminates, is_fine_for_if_cons}, - util::ModuleItemExt, -}; +use crate::{compress::util::is_fine_for_if_cons, util::ModuleItemExt}; /// Methods related to option `dead_code`. impl Pure<'_> { @@ -204,7 +201,7 @@ impl Pure<'_> { .iter() .enumerate() .find(|(_, stmt)| match stmt.as_stmt() { - Some(s) => always_terminates(s), + Some(s) => s.terminates(), _ => false, }); diff --git a/crates/swc_ecma_minifier/src/compress/util/mod.rs b/crates/swc_ecma_minifier/src/compress/util/mod.rs index 87d41ed32449..cf0a2a309dc9 100644 --- a/crates/swc_ecma_minifier/src/compress/util/mod.rs +++ b/crates/swc_ecma_minifier/src/compress/util/mod.rs @@ -381,6 +381,18 @@ pub(crate) fn is_pure_undefined(e: &Expr) -> bool { } } +pub(crate) fn is_primitive(e: &Expr) -> Option<&Expr> { + if is_pure_undefined(e) { + Some(e) + } else { + match e { + Expr::Lit(Lit::Regex(_)) => None, + Expr::Lit(_) => Some(e), + _ => None, + } + } +} + pub(crate) fn is_valid_identifier(s: &str, ascii_only: bool) -> bool { if ascii_only { if s.chars().any(|c| !c.is_ascii()) { @@ -533,18 +545,6 @@ pub(crate) fn eval_as_number(e: &Expr) -> Option { None } -pub(crate) fn always_terminates(s: &Stmt) -> bool { - match s { - Stmt::Return(..) | Stmt::Throw(..) | Stmt::Break(..) | Stmt::Continue(..) => true, - Stmt::If(IfStmt { cons, alt, .. }) => { - always_terminates(cons) && alt.as_deref().map(always_terminates).unwrap_or(false) - } - Stmt::Block(s) => s.stmts.iter().any(always_terminates), - - _ => false, - } -} - pub(crate) fn is_ident_used_by(id: Id, node: &N) -> bool where N: for<'aa> VisitWith>, diff --git a/crates/swc_ecma_minifier/src/option/mod.rs b/crates/swc_ecma_minifier/src/option/mod.rs index 9d4ed91f51db..9859a9af318b 100644 --- a/crates/swc_ecma_minifier/src/option/mod.rs +++ b/crates/swc_ecma_minifier/src/option/mod.rs @@ -254,7 +254,7 @@ pub struct CompressOptions { #[serde(alias = "side_effects")] pub side_effects: bool, - #[serde(default)] + #[serde(default = "true_by_default")] #[serde(alias = "switches")] pub switches: bool, diff --git a/crates/swc_ecma_minifier/src/option/terser.rs b/crates/swc_ecma_minifier/src/option/terser.rs index fb99f6e61638..300815df8158 100644 --- a/crates/swc_ecma_minifier/src/option/terser.rs +++ b/crates/swc_ecma_minifier/src/option/terser.rs @@ -370,8 +370,7 @@ impl TerserCompressorOptions { }) .unwrap_or(if self.defaults { 3 } else { 0 }), side_effects: self.side_effects.unwrap_or(self.defaults), - // TODO: Use self.defaults - switches: self.switches.unwrap_or(false), + switches: self.switches.unwrap_or(self.defaults), top_retain: self.top_retain.map(From::from).unwrap_or_default(), top_level: self.toplevel.map(From::from), typeofs: self.typeofs.unwrap_or(self.defaults), 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 5020437eb75c..15d76fac1fb5 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 @@ -1002,7 +1002,6 @@ value: value, done: !1 }); - break; } (front = front.next) ? resume(front.key, front.arg) : back = null; } @@ -3478,13 +3477,7 @@ if (!BUGGY_SAFARI_ITERATORS && KIND in IterablePrototype) return IterablePrototype[KIND]; switch(KIND){ case KEYS: - return function() { - return new IteratorConstructor(this, KIND); - }; case VALUES: - return function() { - return new IteratorConstructor(this, KIND); - }; case ENTRIES: return function() { return new IteratorConstructor(this, KIND); @@ -8906,7 +8899,6 @@ break; case FRAGMENT: chr != EOF && (url.fragment += percentEncode(chr, fragmentPercentEncodeSet)); - break; } pointer++; } @@ -12521,6 +12513,7 @@ if (ie) return "compositionend" === a || !ae && ge(a, b) ? (a = nd(), md = ld = kd = null, ie = !1, a) : null; switch(a){ case "paste": + default: return null; case "keypress": if (!(b.ctrlKey || b.altKey || b.metaKey) || b.ctrlKey && b.altKey) { @@ -12530,8 +12523,6 @@ return null; case "compositionend": return de && "ko" !== b.locale ? null : b.data; - default: - return null; } }(a12, c5)) && 0 < (d = oe(d, "onBeforeInput")).length && (e = new Ld("onBeforeInput", "beforeinput", null, c5, e), g.push({ event: e, @@ -13092,18 +13083,14 @@ a: { for(l2 = f.key, k2 = d; null !== k2;){ if (k2.key === l2) { - switch(k2.tag){ - case 7: - if (f.type === ua) { - c6(a15, k2.sibling), (d = e5(k2, f.props.children)).return = a15, a15 = d; - break a; - } - break; - default: - if (k2.elementType === f.type) { - c6(a15, k2.sibling), (d = e5(k2, f.props)).ref = Qg(a15, k2, f), d.return = a15, a15 = d; - break a; - } + if (7 === k2.tag) { + if (f.type === ua) { + c6(a15, k2.sibling), (d = e5(k2, f.props.children)).return = a15, a15 = d; + break a; + } + } else if (k2.elementType === f.type) { + c6(a15, k2.sibling), (d = e5(k2, f.props)).ref = Qg(a15, k2, f), d.return = a15, a15 = d; + break a; } c6(a15, k2); break; @@ -13245,8 +13232,6 @@ return null !== (b = 1 !== b.nodeType || c.toLowerCase() !== b.nodeName.toLowerCase() ? null : b) && (a.stateNode = b, !0); case 6: return null !== (b = "" === a.pendingProps || 3 !== b.nodeType ? null : b) && (a.stateNode = b, !0); - case 13: - return !1; default: return !1; } @@ -14010,6 +13995,7 @@ case 14: return null; case 1: + case 17: return Ff(b.type) && Gf(), null; case 3: return fh(), H(N), H(M), uh(), (d = b.stateNode).pendingContext && (d.context = d.pendingContext, d.pendingContext = null), (null === a || null === a.child) && (rh(b) ? b.flags |= 4 : d.hydrate || (b.flags |= 256)), Ci(b), null; @@ -14169,8 +14155,6 @@ return fh(), Ci(b), null === a && cf(b.stateNode.containerInfo), null; case 10: return rg(b), null; - case 17: - return Ff(b.type) && Gf(), null; case 19: if (H(P), null === (d = b.memoizedState)) return null; if (f = 0 != (64 & b.flags), null === (g = d.rendering)) { @@ -14364,6 +14348,10 @@ case 11: case 15: case 22: + case 5: + case 6: + case 4: + case 17: return; case 1: if (256 & b.flags && null !== a) { @@ -14374,11 +14362,6 @@ case 3: 256 & b.flags && qf(b.stateNode.containerInfo); return; - case 5: - case 6: - case 4: - case 17: - return; } throw Error(y(163)); } @@ -14413,8 +14396,6 @@ if (null !== (b = c.updateQueue)) { if (a = null, null !== c.child) switch(c.child.tag){ case 5: - a = c.child.stateNode; - break; case 1: a = c.child.stateNode; } @@ -14425,14 +14406,8 @@ a = c.stateNode, null === b && 4 & c.flags && mf(c.type, c.memoizedProps) && a.focus(); return; case 6: - return; case 4: - return; case 12: - return; - case 13: - null === c.memoizedState && null !== (c = c.alternate) && null !== (c = c.memoizedState) && null !== (c = c.dehydrated) && Cc(c); - return; case 19: case 17: case 20: @@ -14440,6 +14415,9 @@ case 23: case 24: return; + case 13: + null === c.memoizedState && null !== (c = c.alternate) && null !== (c = c.memoizedState) && null !== (c = c.dehydrated) && Cc(c); + return; } throw Error(y(163)); } @@ -14529,8 +14507,6 @@ var d = !1; break; case 3: - b = b.containerInfo, d = !0; - break; case 4: b = b.containerInfo, d = !0; break; @@ -14575,8 +14551,6 @@ f = !1; break a; case 3: - e = e.containerInfo, f = !0; - break a; case 4: e = e.containerInfo, f = !0; break a; @@ -14628,6 +14602,8 @@ } return; case 1: + case 12: + case 17: return; case 5: if (null != (c = b.stateNode)) { @@ -14660,16 +14636,12 @@ case 3: (c = b.stateNode).hydrate && (c.hydrate = !1, Cc(c.containerInfo)); return; - case 12: - return; case 13: null !== b.memoizedState && (jj = O(), aj(b.child, !0)), kj(b); return; case 19: kj(b); return; - case 17: - return; case 23: case 24: aj(b, null !== b.memoizedState); @@ -14810,6 +14782,7 @@ case 1: throw Error(y(345)); case 2: + case 5: Uj(a); break; case 3: @@ -14836,9 +14809,6 @@ } Uj(a); break; - case 5: - Uj(a); - break; default: throw Error(y(329)); } @@ -14903,8 +14873,6 @@ fh(); break; case 13: - H(P); - break; case 19: H(P); break; @@ -15187,14 +15155,7 @@ var Q = Z.ref; if (null !== Q) { var L = Z.stateNode; - switch(Z.tag){ - case 5: - q = L; - break; - default: - q = L; - } - "function" == typeof Q ? Q(q) : Q.current = q; + Z.tag, q = L, "function" == typeof Q ? Q(q) : Q.current = q; } } Z = Z.nextEffect; @@ -15422,13 +15383,7 @@ }, null !== (d = void 0 === d ? null : d) && (b.callback = d), Ag(e, b), Jg(e, g, f), g; } function mk(a) { - if (!(a = a.current).child) return null; - switch(a.child.tag){ - case 5: - return a.child.stateNode; - default: - return a.child.stateNode; - } + return (a = a.current).child ? (a.child.tag, a.child.stateNode) : null; } function nk(a, b) { if (null !== (a = a.memoizedState) && null !== a.dehydrated) { @@ -15613,7 +15568,6 @@ case 7: return fi(a23, b, b.pendingProps, c), b.child; case 8: - return fi(a23, b, b.pendingProps.children, c), b.child; case 12: return fi(a23, b, b.pendingProps.children, c), b.child; case 10: @@ -15667,7 +15621,6 @@ case 19: return Ai(a23, b, c); case 23: - return mi(a23, b, c); case 24: return mi(a23, b, c); } diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/emotion/react/1/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/emotion/react/1/output.js index 0f780bb68c14..becc1a784f8a 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/emotion/react/1/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/emotion/react/1/output.js @@ -156,7 +156,6 @@ break; case 92: next1(); - break; } return position; } @@ -571,9 +570,6 @@ var previousCursor = cursor, result = interpolation(mergedProps); return cursor = previousCursor, handleInterpolation(mergedProps, registered, result); } - break; - case 'string': - break; } if (null == registered) return interpolation; var cached = registered[interpolation]; diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/emotion/react/2/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/emotion/react/2/output.js index d7d13bc0b3a6..5e47eac1000d 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/emotion/react/2/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/emotion/react/2/output.js @@ -85,9 +85,6 @@ function handleInterpolation(mergedProps, registered, interpolation) { var previousCursor = cursor, result = interpolation(mergedProps); return cursor = previousCursor, handleInterpolation(mergedProps, registered, result); } - break; - case 'string': - break; } if (null == registered) return interpolation; var cached = registered[interpolation]; diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/moment/1/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/moment/1/output.js index 1a5fc5a023b9..33815b12f24c 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/moment/1/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/moment/1/output.js @@ -1303,7 +1303,6 @@ break; case 'second': time = this._d.valueOf(), time += 1000 - (time % (divisor2 = 1000) + divisor2) % divisor2 - 1; - break; } return this._d.setTime(time), hooks.updateOffset(this, !0), this; }, proto.format = function(inputString) { @@ -1394,7 +1393,6 @@ break; case 'second': time = this._d.valueOf(), time -= (time % (divisor4 = 1000) + divisor4) % divisor4; - break; } return this._d.setTime(time), hooks.updateOffset(this, !0), this; }, proto.subtract = subtract, proto.toArray = function() { @@ -1588,20 +1586,12 @@ this._config = config, this._dayOfMonthOrdinalParseLenient = new RegExp((this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + '|' + /\d{1,2}/.source); }, proto$1.eras = function(m, format) { var i, l, date, eras = this._eras || getLocale('en')._eras; - for(i = 0, l = eras.length; i < l; ++i){ - switch(typeof eras[i].since){ - case 'string': - date = hooks(eras[i].since).startOf('day'), eras[i].since = date.valueOf(); - break; - } - switch(typeof eras[i].until){ - case 'undefined': - eras[i].until = Infinity; - break; - case 'string': - date = hooks(eras[i].until).startOf('day').valueOf(), eras[i].until = date.valueOf(); - break; - } + for(i = 0, l = eras.length; i < l; ++i)switch('string' == typeof eras[i].since && (date = hooks(eras[i].since).startOf('day'), eras[i].since = date.valueOf()), typeof eras[i].until){ + case 'undefined': + eras[i].until = Infinity; + break; + case 'string': + date = hooks(eras[i].until).startOf('day').valueOf(), eras[i].until = date.valueOf(); } return eras; }, proto$1.erasParse = function(eraName, format, strict) { @@ -1617,7 +1607,6 @@ break; case 'NNNNN': if (narrow === eraName) return eras[i]; - break; } else if ([ name, diff --git a/crates/swc_ecma_minifier/tests/fixture/issues/quagga2/1.4.2/1/output.js b/crates/swc_ecma_minifier/tests/fixture/issues/quagga2/1.4.2/1/output.js index 784c1bf9efe5..6053b8b0de38 100644 --- a/crates/swc_ecma_minifier/tests/fixture/issues/quagga2/1.4.2/1/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/issues/quagga2/1.4.2/1/output.js @@ -1537,7 +1537,6 @@ break; case Rasterizer.CONTOUR_DIR.UNKNOWN_DIR: ctx.strokeStyle = 'green'; - break; } p = q.firstVertex, ctx.beginPath(), ctx.moveTo(p.x, p.y); do p = p.next, ctx.lineTo(p.x, p.y); @@ -4380,7 +4379,6 @@ break; case this.STOP_CODE: done = !0; - break; } break; case this.CODE_B: @@ -4397,7 +4395,6 @@ break; case this.STOP_CODE: done = !0; - break; } break; case this.CODE_C: @@ -4411,9 +4408,7 @@ break; case this.STOP_CODE: done = !0; - break; } - break; } else done = !0; unshift && (codeset = codeset === this.CODE_A ? this.CODE_B : this.CODE_A); @@ -6867,11 +6862,7 @@ } function readTagValue(file, entryOffset, tiffStart, dirStart, bigEnd) { var type = file.getUint16(entryOffset + 2, !bigEnd), numValues = file.getUint32(entryOffset + 4, !bigEnd); - switch(type){ - case 3: - if (1 === numValues) return file.getUint16(entryOffset + 8, !bigEnd); - } - return null; + return 3 === type && 1 === numValues ? file.getUint16(entryOffset + 8, !bigEnd) : null; } function getStringFromBuffer(buffer, start, length) { for(var outstr = '', n = start; n < start + length; n++)outstr += String.fromCharCode(buffer.getUint8(n)); @@ -7151,7 +7142,6 @@ break; case 8: drawAngle = -90 * TO_RADIANS; - break; } return 0 !== drawAngle ? (_ctx.translate(_canvasSize.x / 2, _canvasSize.y / 2), _ctx.rotate(drawAngle), _ctx.drawImage(drawable, -_canvasSize.y / 2, -_canvasSize.x / 2, _canvasSize.y, _canvasSize.x), _ctx.rotate(-drawAngle), _ctx.translate(-_canvasSize.x / 2, -_canvasSize.y / 2)) : _ctx.drawImage(drawable, 0, 0, _canvasSize.x, _canvasSize.y), ctxData = _ctx.getImageData(_sx, _sy, _size.x, _size.y).data, doHalfSample ? Object(cv_utils.e)(ctxData, _size, _data) : Object(cv_utils.c)(ctxData, _data, _streamConfig), !0; } diff --git a/crates/swc_ecma_minifier/tests/fixture/next/33265/static/chunks/d6e1aeb5-38a8d7ae57119c23/output.js b/crates/swc_ecma_minifier/tests/fixture/next/33265/static/chunks/d6e1aeb5-38a8d7ae57119c23/output.js index 94cacddd3a90..4499d0feee1d 100644 --- a/crates/swc_ecma_minifier/tests/fixture/next/33265/static/chunks/d6e1aeb5-38a8d7ae57119c23/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/next/33265/static/chunks/d6e1aeb5-38a8d7ae57119c23/output.js @@ -9700,7 +9700,6 @@ break; default: i += 3; - break; } buffer = buffer.subarray(syncPoint), i -= syncPoint, syncPoint = 0; }, this.reset = function() { @@ -9750,7 +9749,6 @@ break; case 0x09: event.nalUnitType = 'access_unit_delimiter_rbsp'; - break; } self.trigger('data', event); }), nalByteStream.on('done', function() { @@ -9890,7 +9888,6 @@ expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte(), expGolombDecoder.readUnsignedByte() << 8 | expGolombDecoder.readUnsignedByte() ]; - break; } sarRatio && (sarRatio[0], sarRatio[1]); } @@ -10345,7 +10342,6 @@ break; } result.seiNals.push(seiNal); - break; } return result; }, parseSamples = function(truns, baseMediaDecodeTime, tfhd) { @@ -10649,7 +10645,6 @@ break; default: frameI += 3; - break; } return frameBuffer = frameBuffer.subarray(frameSyncPoint), frameI -= frameSyncPoint, frameSyncPoint = 0, frameBuffer && frameBuffer.byteLength > 3 && 'slice_layer_without_partitioning_rbsp_idr' === parseNalUnitType(0x1f & frameBuffer[frameSyncPoint + 3]) && (foundKeyFrame = !0), foundKeyFrame; } @@ -10666,7 +10661,6 @@ pmt.table = pmt.table || {}, Object.keys(table).forEach(function(key) { pmt.table[key] = table[key]; }); - break; } startIndex += MP2T_PACKET_LENGTH, endIndex += MP2T_PACKET_LENGTH; continue; @@ -10676,12 +10670,7 @@ }, parseAudioPes_ = function(bytes, pmt, result) { for(var packet, pesType, pusi, parsed, startIndex = 0, endIndex = MP2T_PACKET_LENGTH, endLoop = !1; endIndex <= bytes.byteLength;){ if (0x47 === bytes[startIndex] && (0x47 === bytes[endIndex] || endIndex === bytes.byteLength)) { - switch(packet = bytes.subarray(startIndex, endIndex), probe.ts.parseType(packet, pmt.pid)){ - case 'pes': - pesType = probe.ts.parsePesType(packet, pmt.table), pusi = probe.ts.parsePayloadUnitStartIndicator(packet), 'audio' === pesType && pusi && (parsed = probe.ts.parsePesTime(packet)) && (parsed.type = 'audio', result.audio.push(parsed), endLoop = !0); - break; - } - if (endLoop) break; + if (packet = bytes.subarray(startIndex, endIndex), 'pes' === probe.ts.parseType(packet, pmt.pid) && (pesType = probe.ts.parsePesType(packet, pmt.table), pusi = probe.ts.parsePayloadUnitStartIndicator(packet), 'audio' === pesType && pusi && (parsed = probe.ts.parsePesTime(packet)) && (parsed.type = 'audio', result.audio.push(parsed), endLoop = !0)), endLoop) break; startIndex += MP2T_PACKET_LENGTH, endIndex += MP2T_PACKET_LENGTH; continue; } @@ -10689,12 +10678,7 @@ } for(startIndex = (endIndex = bytes.byteLength) - MP2T_PACKET_LENGTH, endLoop = !1; startIndex >= 0;){ if (0x47 === bytes[startIndex] && (0x47 === bytes[endIndex] || endIndex === bytes.byteLength)) { - switch(packet = bytes.subarray(startIndex, endIndex), probe.ts.parseType(packet, pmt.pid)){ - case 'pes': - pesType = probe.ts.parsePesType(packet, pmt.table), pusi = probe.ts.parsePayloadUnitStartIndicator(packet), 'audio' === pesType && pusi && (parsed = probe.ts.parsePesTime(packet)) && (parsed.type = 'audio', result.audio.push(parsed), endLoop = !0); - break; - } - if (endLoop) break; + if (packet = bytes.subarray(startIndex, endIndex), 'pes' === probe.ts.parseType(packet, pmt.pid) && (pesType = probe.ts.parsePesType(packet, pmt.table), pusi = probe.ts.parsePayloadUnitStartIndicator(packet), 'audio' === pesType && pusi && (parsed = probe.ts.parsePesTime(packet)) && (parsed.type = 'audio', result.audio.push(parsed), endLoop = !0)), endLoop) break; startIndex -= MP2T_PACKET_LENGTH, endIndex -= MP2T_PACKET_LENGTH; continue; } @@ -10706,20 +10690,16 @@ size: 0 }; endIndex < bytes.byteLength;){ if (0x47 === bytes[startIndex] && 0x47 === bytes[endIndex]) { - switch(packet = bytes.subarray(startIndex, endIndex), probe.ts.parseType(packet, pmt.pid)){ - case 'pes': - if (pesType = probe.ts.parsePesType(packet, pmt.table), pusi = probe.ts.parsePayloadUnitStartIndicator(packet), 'video' === pesType && (pusi && !endLoop && (parsed = probe.ts.parsePesTime(packet)) && (parsed.type = 'video', result.video.push(parsed), endLoop = !0), !result.firstKeyFrame)) { - if (pusi && 0 !== currentFrame.size) { - for(frame = new Uint8Array(currentFrame.size), i = 0; currentFrame.data.length;)pes = currentFrame.data.shift(), frame.set(pes, i), i += pes.byteLength; - if (probe.ts.videoPacketContainsKeyFrame(frame)) { - var firstKeyFrame = probe.ts.parsePesTime(frame); - firstKeyFrame ? (result.firstKeyFrame = firstKeyFrame, result.firstKeyFrame.type = 'video') : console.warn("Failed to extract PTS/DTS from PES at first keyframe. This could be an unusual TS segment, or else mux.js did not parse your TS segment correctly. If you know your TS segments do contain PTS/DTS on keyframes please file a bug report! You can try ffprobe to double check for yourself."); - } - currentFrame.size = 0; - } - currentFrame.data.push(packet), currentFrame.size += packet.byteLength; + if (packet = bytes.subarray(startIndex, endIndex), 'pes' === probe.ts.parseType(packet, pmt.pid) && (pesType = probe.ts.parsePesType(packet, pmt.table), pusi = probe.ts.parsePayloadUnitStartIndicator(packet), 'video' === pesType && (pusi && !endLoop && (parsed = probe.ts.parsePesTime(packet)) && (parsed.type = 'video', result.video.push(parsed), endLoop = !0), !result.firstKeyFrame))) { + if (pusi && 0 !== currentFrame.size) { + for(frame = new Uint8Array(currentFrame.size), i = 0; currentFrame.data.length;)pes = currentFrame.data.shift(), frame.set(pes, i), i += pes.byteLength; + if (probe.ts.videoPacketContainsKeyFrame(frame)) { + var firstKeyFrame = probe.ts.parsePesTime(frame); + firstKeyFrame ? (result.firstKeyFrame = firstKeyFrame, result.firstKeyFrame.type = 'video') : console.warn("Failed to extract PTS/DTS from PES at first keyframe. This could be an unusual TS segment, or else mux.js did not parse your TS segment correctly. If you know your TS segments do contain PTS/DTS on keyframes please file a bug report! You can try ffprobe to double check for yourself."); } - break; + currentFrame.size = 0; + } + currentFrame.data.push(packet), currentFrame.size += packet.byteLength; } if (endLoop && result.firstKeyFrame) break; startIndex += MP2T_PACKET_LENGTH, endIndex += MP2T_PACKET_LENGTH; @@ -10729,12 +10709,7 @@ } for(startIndex = (endIndex = bytes.byteLength) - MP2T_PACKET_LENGTH, endLoop = !1; startIndex >= 0;){ if (0x47 === bytes[startIndex] && 0x47 === bytes[endIndex]) { - switch(packet = bytes.subarray(startIndex, endIndex), probe.ts.parseType(packet, pmt.pid)){ - case 'pes': - pesType = probe.ts.parsePesType(packet, pmt.table), pusi = probe.ts.parsePayloadUnitStartIndicator(packet), 'video' === pesType && pusi && (parsed = probe.ts.parsePesTime(packet)) && (parsed.type = 'video', result.video.push(parsed), endLoop = !0); - break; - } - if (endLoop) break; + if (packet = bytes.subarray(startIndex, endIndex), 'pes' === probe.ts.parseType(packet, pmt.pid) && (pesType = probe.ts.parsePesType(packet, pmt.table), pusi = probe.ts.parsePayloadUnitStartIndicator(packet), 'video' === pesType && pusi && (parsed = probe.ts.parsePesTime(packet)) && (parsed.type = 'video', result.video.push(parsed), endLoop = !0)), endLoop) break; startIndex -= MP2T_PACKET_LENGTH, endIndex -= MP2T_PACKET_LENGTH; continue; } @@ -10776,7 +10751,6 @@ break; default: byteIndex++; - break; } if (endLoop) return null; } @@ -10809,7 +10783,6 @@ break; case streamTypes.ADTS_STREAM_TYPE: result.audio = [], parseAudioPes_(bytes, pmt, result), 0 === result.audio.length && delete result.audio; - break; } } return result; diff --git a/crates/swc_ecma_minifier/tests/fixture/next/33265/static/chunks/pages/index-cb36c1bf7f830e3c/output.js b/crates/swc_ecma_minifier/tests/fixture/next/33265/static/chunks/pages/index-cb36c1bf7f830e3c/output.js index 9ea011d45f8d..600a0b42697d 100644 --- a/crates/swc_ecma_minifier/tests/fixture/next/33265/static/chunks/pages/index-cb36c1bf7f830e3c/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/next/33265/static/chunks/pages/index-cb36c1bf7f830e3c/output.js @@ -1314,7 +1314,6 @@ break; case ATTRIBUTE_NODE: deep = !0; - break; } if (node2 || (node2 = node.cloneNode(!1)), node2.ownerDocument = doc, node2.parentNode = null, deep) for(var child = node.firstChild; child;)node2.appendChild(importNode(doc, child, deep)), child = child.nextSibling; return node2; @@ -2043,7 +2042,6 @@ errorHandler.warning('attribute "' + value1 + '" missed quot(")!!'), addAttribute(attrName, value1, start); case 5: s = 6; - break; } else switch(s){ case 2: @@ -2096,25 +2094,21 @@ for(var n in source)target[n] = source[n]; } function parseDCC(source, start, domBuilder, errorHandler) { - var next = source.charAt(start + 2); - switch(next){ - case '-': - if ('-' !== source.charAt(start + 3)) return -1; - var end = source.indexOf('-->', start + 4); - if (end > start) return domBuilder.comment(source, start + 4, end - start - 4), end + 3; - return errorHandler.error("Unclosed comment"), -1; - default: - if ('CDATA[' == source.substr(start + 3, 6)) { - var end = source.indexOf(']]>', start + 9); - return domBuilder.startCDATA(), domBuilder.characters(source, start + 9, end - start - 9), domBuilder.endCDATA(), end + 3; - } - var matchs = split(source, start), len = matchs.length; - if (len > 1 && /!doctype/i.test(matchs[0][0])) { - var name = matchs[1][0], pubid = !1, sysid = !1; - len > 3 && (/^public$/i.test(matchs[2][0]) ? (pubid = matchs[3][0], sysid = len > 4 && matchs[4][0]) : /^system$/i.test(matchs[2][0]) && (sysid = matchs[3][0])); - var lastMatch = matchs[len - 1]; - return domBuilder.startDTD(name, pubid, sysid), domBuilder.endDTD(), lastMatch.index + lastMatch[0].length; - } + if ('-' === source.charAt(start + 2)) { + if ('-' !== source.charAt(start + 3)) return -1; + var end = source.indexOf('-->', start + 4); + return end > start ? (domBuilder.comment(source, start + 4, end - start - 4), end + 3) : (errorHandler.error("Unclosed comment"), -1); + } + if ('CDATA[' == source.substr(start + 3, 6)) { + var end = source.indexOf(']]>', start + 9); + return domBuilder.startCDATA(), domBuilder.characters(source, start + 9, end - start - 9), domBuilder.endCDATA(), end + 3; + } + var matchs = split(source, start), len = matchs.length; + if (len > 1 && /!doctype/i.test(matchs[0][0])) { + var name = matchs[1][0], pubid = !1, sysid = !1; + len > 3 && (/^public$/i.test(matchs[2][0]) ? (pubid = matchs[3][0], sysid = len > 4 && matchs[4][0]) : /^system$/i.test(matchs[2][0]) && (sysid = matchs[3][0])); + var lastMatch = matchs[len - 1]; + return domBuilder.startDTD(name, pubid, sysid), domBuilder.endDTD(), lastMatch.index + lastMatch[0].length; } return -1; } @@ -3625,9 +3619,6 @@ case 'urn:mpeg:dash:utc:direct:2012': attributes.method = 'DIRECT', attributes.value = Date.parse(attributes.value); break; - case 'urn:mpeg:dash:utc:http-ntp:2014': - case 'urn:mpeg:dash:utc:ntp:2014': - case 'urn:mpeg:dash:utc:sntp:2014': default: throw new Error(errors.UNSUPPORTED_UTC_TIMING_SCHEME); } @@ -3948,7 +3939,6 @@ "left", "right" ]); - break; } }, /:/, /\s/), cue.region = settings.get("region", null), cue.vertical = settings.get("vertical", ""); try { @@ -4566,7 +4556,6 @@ break; case "end": textPos = cue.position - cue.size; - break; } "" === cue.vertical ? this.applyStyles({ left: this.formatStyle(textPos, "%"), @@ -4620,7 +4609,6 @@ "-x", "+x" ], size = "width"; - break; } var size, step = boxPosition.lineHeight, position = step * Math.round(linePos), maxPosition = containerBox[size] + step, initialAxis = axis1[0]; Math.abs(position) > maxPosition && (position = position < 0 ? -1 : 1, position *= Math.ceil(maxPosition / step) * step), linePos < 0 && (position += "" === cue2.vertical ? containerBox.height : containerBox.width, axis1 = axis1.reverse()), boxPosition.move(initialAxis, position); @@ -4632,7 +4620,6 @@ break; case "end": linePos -= calculatedPercentage; - break; } switch(cue2.vertical){ case "": @@ -4649,7 +4636,6 @@ styleBox.applyStyles({ right: styleBox.formatStyle(linePos, "%") }); - break; } axis1 = [ "+y", @@ -4687,7 +4673,6 @@ break; case "-y": this.top -= toMove, this.bottom -= toMove; - break; } }, BoxPosition.prototype.overlaps = function(b2) { return this.left < b2.right && this.right > b2.left && this.top < b2.bottom && this.bottom > b2.top; @@ -4774,64 +4759,56 @@ } function parseHeader(input3) { input3.match(/X-TIMESTAMP-MAP/) ? parseOptions(input3, function(k1, v1) { - switch(k1){ - case "X-TIMESTAMP-MAP": - var input, settings; - input = v1, settings = new Settings(), parseOptions(input, function(k, v) { - switch(k){ - case "MPEGT": - settings.integer(k + 'S', v); - break; - case "LOCA": - settings.set(k + 'L', parseTimeStamp(v)); - break; - } - }, /[^\d]:/, /,/), self.ontimestampmap && self.ontimestampmap({ - MPEGTS: settings.get("MPEGTS"), - LOCAL: settings.get("LOCAL") - }); - break; + if ("X-TIMESTAMP-MAP" === k1) { + var input, settings; + input = v1, settings = new Settings(), parseOptions(input, function(k, v) { + switch(k){ + case "MPEGT": + settings.integer(k + 'S', v); + break; + case "LOCA": + settings.set(k + 'L', parseTimeStamp(v)); + } + }, /[^\d]:/, /,/), self.ontimestampmap && self.ontimestampmap({ + MPEGTS: settings.get("MPEGTS"), + LOCAL: settings.get("LOCAL") + }); } }, /=/) : parseOptions(input3, function(k2, v2) { - switch(k2){ - case "Region": - !function(input) { - var settings = new Settings(); - if (parseOptions(input, function(k, v) { - switch(k){ - case "id": - settings.set(k, v); - break; - case "width": - settings.percent(k, v); - break; - case "lines": - settings.integer(k, v); - break; - case "regionanchor": - case "viewportanchor": - var xy = v.split(','); - if (2 !== xy.length) break; - var anchor = new Settings(); - if (anchor.percent("x", xy[0]), anchor.percent("y", xy[1]), !anchor.has("x") || !anchor.has("y")) break; - settings.set(k + "X", anchor.get("x")), settings.set(k + "Y", anchor.get("y")); - break; - case "scroll": - settings.alt(k, v, [ - "up" - ]); - break; - } - }, /=/, /\s/), settings.has("id")) { - var region = new (self.vttjs.VTTRegion || self.window.VTTRegion)(); - region.width = settings.get("width", 100), region.lines = settings.get("lines", 3), region.regionAnchorX = settings.get("regionanchorX", 0), region.regionAnchorY = settings.get("regionanchorY", 100), region.viewportAnchorX = settings.get("viewportanchorX", 0), region.viewportAnchorY = settings.get("viewportanchorY", 100), region.scroll = settings.get("scroll", ""), self.onregion && self.onregion(region), self.regionList.push({ - id: settings.get("id"), - region: region - }); - } - }(v2); - break; - } + "Region" === k2 && function(input) { + var settings = new Settings(); + if (parseOptions(input, function(k, v) { + switch(k){ + case "id": + settings.set(k, v); + break; + case "width": + settings.percent(k, v); + break; + case "lines": + settings.integer(k, v); + break; + case "regionanchor": + case "viewportanchor": + var xy = v.split(','); + if (2 !== xy.length) break; + var anchor = new Settings(); + if (anchor.percent("x", xy[0]), anchor.percent("y", xy[1]), !anchor.has("x") || !anchor.has("y")) break; + settings.set(k + "X", anchor.get("x")), settings.set(k + "Y", anchor.get("y")); + break; + case "scroll": + settings.alt(k, v, [ + "up" + ]); + } + }, /=/, /\s/), settings.has("id")) { + var region = new (self.vttjs.VTTRegion || self.window.VTTRegion)(); + region.width = settings.get("width", 100), region.lines = settings.get("lines", 3), region.regionAnchorX = settings.get("regionanchorX", 0), region.regionAnchorY = settings.get("regionanchorY", 100), region.viewportAnchorX = settings.get("viewportanchorX", 0), region.viewportAnchorY = settings.get("viewportanchorY", 100), region.scroll = settings.get("scroll", ""), self.onregion && self.onregion(region), self.regionList.push({ + id: settings.get("id"), + region: region + }); + } + }(v2); }, /:/); } data && (self.buffer += self.decoder.decode(data, { diff --git a/crates/swc_ecma_minifier/tests/fixture/next/react-ace/chunks/8a28b14e.d8fbda268ed281a1/output.js b/crates/swc_ecma_minifier/tests/fixture/next/react-ace/chunks/8a28b14e.d8fbda268ed281a1/output.js index 1b9599557277..37e57b5229c3 100644 --- a/crates/swc_ecma_minifier/tests/fixture/next/react-ace/chunks/8a28b14e.d8fbda268ed281a1/output.js +++ b/crates/swc_ecma_minifier/tests/fixture/next/react-ace/chunks/8a28b14e.d8fbda268ed281a1/output.js @@ -442,7 +442,6 @@ case e.DOM_DELTA_LINE: case e.DOM_DELTA_PAGE: e.wheelX = 5 * (e.deltaX || 0), e.wheelY = 5 * (e.deltaY || 0); - break; } callback(e); }, destroyer) : addListener(el, "DOMMouseScroll", function(e) { @@ -915,7 +914,6 @@ break; case 88: onCut(e); - break; } }, host); var onCompositionUpdate = function() { @@ -1328,7 +1326,6 @@ break; case "copy": range = editor.moveText(range, dragCursor, !0); - break; } else { var dropData = dataTransfer.getData('Text'); @@ -4515,7 +4512,6 @@ case "remove": var endColumn = delta.end.column, endRow = delta.end.row; row === endRow ? docLines[row] = line.substring(0, startColumn) + line.substring(endColumn) : docLines.splice(row, endRow - row + 1, line.substring(0, startColumn) + docLines[endRow].substring(endColumn)); - break; } }; }), ace.define("ace/anchor", [ @@ -7815,9 +7811,6 @@ case "selectionPart": var range = this.selection.getRange(), config = this.renderer.layerConfig; (range.start.row >= config.lastRow || range.end.row <= config.firstRow) && this.renderer.scrollSelectionIntoView(this.selection.anchor, this.selection.lead); - break; - default: - break; } "animate" == scrollIntoView && this.renderer.animateScrolling(this.curOp.scrollTop); } @@ -8572,7 +8565,6 @@ case ']': case '}': depth[bracketType]--, -1 === depth[bracketType] && (matchType = 'bracket', found = !0); - break; } } else -1 !== token.type.indexOf('tag-name') && (isNaN(depth[token.value]) && (depth[token.value] = 0), '<' === prevToken.value ? depth[token.value]++ : '\s*\(/gm,"{anonymous}()@"):"Unknown Stack Trace",b=g.console&&(g.console.warn||g.console.log);return b&&b.call(g.console,d,e),c.apply(this,arguments)}}m="function"!=typeof Object.assign?function(b){if(b===l||null===b)throw new TypeError("Cannot convert undefined or null to object");for(var e=Object(b),c=1;c -1}function _(a){return a.trim().split(/\s+/g)}function aa(a,d,c){if(a.indexOf&&!c)return a.indexOf(d);for(var b=0;baa(e,f)&&b.push(c[a]),e[a]=f,a++}return g&&(b=d?b.sort(function(a,b){return a[d]>b[d]}):b.sort()),b}function n(e,a){for(var c,d,f=a[0].toUpperCase()+a.slice(1),b=0;b1&&!b.firstMultiple?b.firstMultiple=an(a):1===h&&(b.firstMultiple=!1);var i=b.firstInput,c=b.firstMultiple,j=c?c.center:i.center,k=a.center=ao(e);a.timeStamp=U(),a.deltaTime=a.timeStamp-i.timeStamp,a.angle=as(j,k),a.distance=ar(j,k),al(b,a),a.offsetDirection=aq(a.deltaX,a.deltaY);var d=ap(a.deltaTime,a.deltaX,a.deltaY);a.overallVelocityX=d.x,a.overallVelocityY=d.y,a.overallVelocity=T(d.x)>T(d.y)?d.x:d.y,a.scale=c?au(c.pointers,e):1,a.rotation=c?at(c.pointers,e):0,a.maxPointers=b.prevInput?a.pointers.length>b.prevInput.maxPointers?a.pointers.length:b.prevInput.maxPointers:a.pointers.length,am(b,a);var f=g.element;Z(a.srcEvent.target,f)&&(f=a.srcEvent.target),a.target=f}function al(a,b){var c=b.center,d=a.offsetDelta||{},e=a.prevDelta||{},f=a.prevInput||{};(1===b.eventType||4===f.eventType)&&(e=a.prevDelta={x:f.deltaX||0,y:f.deltaY||0},d=a.offsetDelta={x:c.x,y:c.y}),b.deltaX=e.x+(c.x-d.x),b.deltaY=e.y+(c.y-d.y)}function am(h,a){var d,e,f,g,b=h.lastInterval||a,i=a.timeStamp-b.timeStamp;if(8!=a.eventType&&(i>25||l===b.velocity)){var j=a.deltaX-b.deltaX,k=a.deltaY-b.deltaY,c=ap(i,j,k);e=c.x,f=c.y,d=T(c.x)>T(c.y)?c.x:c.y,g=aq(j,k),h.lastInterval=a}else d=b.velocity,e=b.velocityX,f=b.velocityY,g=b.direction;a.velocity=d,a.velocityX=e,a.velocityY=f,a.direction=g}function an(a){for(var c=[],b=0;b=T(b)?a<0?2:4:b<0?8:16}function ar(b,c,a){a||(a=ah);var d=c[a[0]]-b[a[0]],e=c[a[1]]-b[a[1]];return Math.sqrt(d*d+e*e)}function as(b,c,a){a||(a=ah);var d=c[a[0]]-b[a[0]],e=c[a[1]]-b[a[1]];return 180*Math.atan2(e,d)/Math.PI}function at(a,b){return as(b[1],b[0],ai)+as(a[1],a[0],ai)}function au(a,b){return ar(b[0],b[1],ai)/ar(a[0],a[1],ai)}f.prototype={handler:function(){},init:function(){this.evEl&&H(this.element,this.evEl,this.domHandler),this.evTarget&&H(this.target,this.evTarget,this.domHandler),this.evWin&&H(ae(this.element),this.evWin,this.domHandler)},destroy:function(){this.evEl&&I(this.element,this.evEl,this.domHandler),this.evTarget&&I(this.target,this.evTarget,this.domHandler),this.evWin&&I(ae(this.element),this.evWin,this.domHandler)}};var av={mousedown:1,mousemove:2,mouseup:4};function u(){this.evEl="mousedown",this.evWin="mousemove mouseup",this.pressed=!1,f.apply(this,arguments)}e(u,f,{handler:function(a){var b=av[a.type];1&b&&0===a.button&&(this.pressed=!0),2&b&&1!==a.which&&(b=4),this.pressed&&(4&b&&(this.pressed=!1),this.callback(this.manager,b,{pointers:[a],changedPointers:[a],pointerType:L,srcEvent:a}))}});var aw={pointerdown:1,pointermove:2,pointerup:4,pointercancel:8,pointerout:8},ax={2:K,3:"pen",4:L,5:"kinect"},M="pointerdown",N="pointermove pointerup pointercancel";function v(){this.evEl=M,this.evWin=N,f.apply(this,arguments),this.store=this.manager.session.pointerEvents=[]}g.MSPointerEvent&&!g.PointerEvent&&(M="MSPointerDown",N="MSPointerMove MSPointerUp MSPointerCancel"),e(v,f,{handler:function(a){var b=this.store,e=!1,d=aw[a.type.toLowerCase().replace("ms","")],f=ax[a.pointerType]||a.pointerType,c=aa(b,a.pointerId,"pointerId");1&d&&(0===a.button||f==K)?c<0&&(b.push(a),c=b.length-1):12&d&&(e=!0),!(c<0)&&(b[c]=a,this.callback(this.manager,d,{pointers:b,changedPointers:[a],pointerType:f,srcEvent:a}),e&&b.splice(c,1))}});var ay={touchstart:1,touchmove:2,touchend:4,touchcancel:8};function w(){this.evTarget="touchstart",this.evWin="touchstart touchmove touchend touchcancel",this.started=!1,f.apply(this,arguments)}function az(b,d){var a=ab(b.touches),c=ab(b.changedTouches);return 12&d&&(a=ac(a.concat(c),"identifier",!0)),[a,c]}e(w,f,{handler:function(c){var a=ay[c.type];if(1===a&&(this.started=!0),this.started){var b=az.call(this,c,a);12&a&&b[0].length-b[1].length==0&&(this.started=!1),this.callback(this.manager,a,{pointers:b[0],changedPointers:b[1],pointerType:K,srcEvent:c})}}});var aA={touchstart:1,touchmove:2,touchend:4,touchcancel:8};function x(){this.evTarget="touchstart touchmove touchend touchcancel",this.targetIds={},f.apply(this,arguments)}function aB(h,g){var b=ab(h.touches),c=this.targetIds;if(3&g&&1===b.length)return c[b[0].identifier]=!0,[b,b];var a,d,e=ab(h.changedTouches),f=[],i=this.target;if(d=b.filter(function(a){return Z(a.target,i)}),1===g)for(a=0;a -1&&d.splice(a,1)},2500)}}function aE(b){for(var d=b.srcEvent.clientX,e=b.srcEvent.clientY,a=0;a -1&&this.requireFail.splice(b,1),this},hasRequireFailures:function(){return this.requireFail.length>0},canRecognizeWith:function(a){return!!this.simultaneous[a.id]},emit:function(d){var c=this,a=this.state;function b(a){c.manager.emit(a,d)}a<8&&b(c.options.event+aM(a)),b(c.options.event),d.additionalEvent&&b(d.additionalEvent),a>=8&&b(c.options.event+aM(a))},tryEmit:function(a){if(this.canEmit())return this.emit(a);this.state=32},canEmit:function(){for(var a=0;ac.threshold&&b&c.direction},attrTest:function(a){return h.prototype.attrTest.call(this,a)&&(2&this.state|| !(2&this.state)&&this.directionTest(a))},emit:function(a){this.pX=a.deltaX,this.pY=a.deltaY;var b=aN(a.direction);b&&(a.additionalEvent=this.options.event+b),this._super.emit.call(this,a)}}),e(p,h,{defaults:{event:"pinch",threshold:0,pointers:2},getTouchAction:function(){return[aI]},attrTest:function(a){return this._super.attrTest.call(this,a)&&(Math.abs(a.scale-1)>this.options.threshold||2&this.state)},emit:function(a){if(1!==a.scale){var b=a.scale<1?"in":"out";a.additionalEvent=this.options.event+b}this._super.emit.call(this,a)}}),e(q,i,{defaults:{event:"press",pointers:1,time:251,threshold:9},getTouchAction:function(){return[aG]},process:function(a){var b=this.options,c=a.pointers.length===b.pointers,d=a.distanceb.time;if(this._input=a,d&&c&&(!(12&a.eventType)||e)){if(1&a.eventType)this.reset(),this._timer=V(function(){this.state=8,this.tryEmit()},b.time,this);else if(4&a.eventType)return 8}else this.reset();return 32},reset:function(){clearTimeout(this._timer)},emit:function(a){8===this.state&&(a&&4&a.eventType?this.manager.emit(this.options.event+"up",a):(this._input.timeStamp=U(),this.manager.emit(this.options.event,this._input)))}}),e(r,h,{defaults:{event:"rotate",threshold:0,pointers:2},getTouchAction:function(){return[aI]},attrTest:function(a){return this._super.attrTest.call(this,a)&&(Math.abs(a.rotation)>this.options.threshold||2&this.state)}}),e(s,h,{defaults:{event:"swipe",threshold:10,velocity:.3,direction:30,pointers:1},getTouchAction:function(){return o.prototype.getTouchAction.call(this)},attrTest:function(a){var b,c=this.options.direction;return 30&c?b=a.overallVelocity:6&c?b=a.overallVelocityX:24&c&&(b=a.overallVelocityY),this._super.attrTest.call(this,a)&&c&a.offsetDirection&&a.distance>this.options.threshold&&a.maxPointers==this.options.pointers&&T(b)>this.options.velocity&&4&a.eventType},emit:function(a){var b=aN(a.offsetDirection);b&&this.manager.emit(this.options.event+b,a),this.manager.emit(this.options.event,a)}}),e(j,i,{defaults:{event:"tap",pointers:1,taps:1,interval:300,time:250,threshold:9,posThreshold:10},getTouchAction:function(){return[aH]},process:function(a){var b=this.options,c=a.pointers.length===b.pointers,d=a.distance1)for(var a=1;ac.length)&&(a=c.length);for(var b=0,d=new Array(a);bc?c:a}Math.hypot||(Math.hypot=function(){for(var b=0,a=arguments.length;a--;)b+=arguments[a]*arguments[a];return Math.sqrt(b)}),bc=new h(4),h!=Float32Array&&(bc[0]=0,bc[1]=0,bc[2]=0,bc[3]=0);const aF=Math.log2||function(a){return Math.log(a)*Math.LOG2E};function aG(e,f,g){var h=f[0],i=f[1],j=f[2],k=f[3],l=f[4],m=f[5],n=f[6],o=f[7],p=f[8],q=f[9],r=f[10],s=f[11],t=f[12],u=f[13],v=f[14],w=f[15],a=g[0],b=g[1],c=g[2],d=g[3];return e[0]=a*h+b*l+c*p+d*t,e[1]=a*i+b*m+c*q+d*u,e[2]=a*j+b*n+c*r+d*v,e[3]=a*k+b*o+c*s+d*w,a=g[4],b=g[5],c=g[6],d=g[7],e[4]=a*h+b*l+c*p+d*t,e[5]=a*i+b*m+c*q+d*u,e[6]=a*j+b*n+c*r+d*v,e[7]=a*k+b*o+c*s+d*w,a=g[8],b=g[9],c=g[10],d=g[11],e[8]=a*h+b*l+c*p+d*t,e[9]=a*i+b*m+c*q+d*u,e[10]=a*j+b*n+c*r+d*v,e[11]=a*k+b*o+c*s+d*w,a=g[12],b=g[13],c=g[14],d=g[15],e[12]=a*h+b*l+c*p+d*t,e[13]=a*i+b*m+c*q+d*u,e[14]=a*j+b*n+c*r+d*v,e[15]=a*k+b*o+c*s+d*w,e}function aH(b,a,f){var g,h,i,j,k,l,m,n,o,p,q,r,c=f[0],d=f[1],e=f[2];return a===b?(b[12]=a[0]*c+a[4]*d+a[8]*e+a[12],b[13]=a[1]*c+a[5]*d+a[9]*e+a[13],b[14]=a[2]*c+a[6]*d+a[10]*e+a[14],b[15]=a[3]*c+a[7]*d+a[11]*e+a[15]):(g=a[0],h=a[1],i=a[2],j=a[3],k=a[4],l=a[5],m=a[6],n=a[7],o=a[8],p=a[9],q=a[10],r=a[11],b[0]=g,b[1]=h,b[2]=i,b[3]=j,b[4]=k,b[5]=l,b[6]=m,b[7]=n,b[8]=o,b[9]=p,b[10]=q,b[11]=r,b[12]=g*c+k*d+o*e+a[12],b[13]=h*c+l*d+p*e+a[13],b[14]=i*c+m*d+q*e+a[14],b[15]=j*c+n*d+r*e+a[15]),b}function aI(a,b,f){var c=f[0],d=f[1],e=f[2];return a[0]=b[0]*c,a[1]=b[1]*c,a[2]=b[2]*c,a[3]=b[3]*c,a[4]=b[4]*d,a[5]=b[5]*d,a[6]=b[6]*d,a[7]=b[7]*d,a[8]=b[8]*e,a[9]=b[9]*e,a[10]=b[10]*e,a[11]=b[11]*e,a[12]=b[12],a[13]=b[13],a[14]=b[14],a[15]=b[15],a}function aJ(a,b){var c=a[0],d=a[1],e=a[2],f=a[3],g=a[4],h=a[5],i=a[6],j=a[7],k=a[8],l=a[9],m=a[10],n=a[11],o=a[12],p=a[13],q=a[14],r=a[15],s=b[0],t=b[1],u=b[2],v=b[3],w=b[4],x=b[5],y=b[6],z=b[7],A=b[8],B=b[9],C=b[10],D=b[11],E=b[12],F=b[13],G=b[14],H=b[15];return Math.abs(c-s)<=1e-6*Math.max(1,Math.abs(c),Math.abs(s))&&Math.abs(d-t)<=1e-6*Math.max(1,Math.abs(d),Math.abs(t))&&Math.abs(e-u)<=1e-6*Math.max(1,Math.abs(e),Math.abs(u))&&Math.abs(f-v)<=1e-6*Math.max(1,Math.abs(f),Math.abs(v))&&Math.abs(g-w)<=1e-6*Math.max(1,Math.abs(g),Math.abs(w))&&Math.abs(h-x)<=1e-6*Math.max(1,Math.abs(h),Math.abs(x))&&Math.abs(i-y)<=1e-6*Math.max(1,Math.abs(i),Math.abs(y))&&Math.abs(j-z)<=1e-6*Math.max(1,Math.abs(j),Math.abs(z))&&Math.abs(k-A)<=1e-6*Math.max(1,Math.abs(k),Math.abs(A))&&Math.abs(l-B)<=1e-6*Math.max(1,Math.abs(l),Math.abs(B))&&Math.abs(m-C)<=1e-6*Math.max(1,Math.abs(m),Math.abs(C))&&Math.abs(n-D)<=1e-6*Math.max(1,Math.abs(n),Math.abs(D))&&Math.abs(o-E)<=1e-6*Math.max(1,Math.abs(o),Math.abs(E))&&Math.abs(p-F)<=1e-6*Math.max(1,Math.abs(p),Math.abs(F))&&Math.abs(q-G)<=1e-6*Math.max(1,Math.abs(q),Math.abs(G))&&Math.abs(r-H)<=1e-6*Math.max(1,Math.abs(r),Math.abs(H))}function aK(a,b,c){return a[0]=b[0]+c[0],a[1]=b[1]+c[1],a}function aL(a,b,c,d){var e=b[0],f=b[1];return a[0]=e+d*(c[0]-e),a[1]=f+d*(c[1]-f),a}function aM(a,b){if(!a)throw new Error(b||"@math.gl/web-mercator: assertion failed.")}bd=new h(2),h!=Float32Array&&(bd[0]=0,bd[1]=0),be=new h(3),h!=Float32Array&&(be[0]=0,be[1]=0,be[2]=0);const n=Math.PI,aN=n/4,aO=n/180,aP=180/n;function aQ(a){return Math.pow(2,a)}function aR([b,a]){return aM(Number.isFinite(b)),aM(Number.isFinite(a)&&a>= -90&&a<=90,"invalid latitude"),[512*(b*aO+n)/(2*n),512*(n+Math.log(Math.tan(aN+.5*(a*aO))))/(2*n)]}function aS([a,b]){return[(a/512*(2*n)-n)*aP,2*(Math.atan(Math.exp(b/512*(2*n)-n))-aN)*aP]}function aT(a){return 2*Math.atan(.5/a)*aP}function aU(a){return .5/Math.tan(.5*a*aO)}function aV(i,c,j=0){const[a,b,e]=i;if(aM(Number.isFinite(a)&&Number.isFinite(b),"invalid pixel coordinate"),Number.isFinite(e)){const k=aC(c,[a,b,e,1]);return k}const f=aC(c,[a,b,0,1]),g=aC(c,[a,b,1,1]),d=f[2],h=g[2];return aL([],f,g,d===h?0:((j||0)-d)/(h-d))}const aW=Math.PI/180;function aX(a,c,d){const{pixelUnprojectionMatrix:e}=a,b=aC(e,[c,0,1,1]),f=aC(e,[c,a.height,1,1]),h=d*a.distanceScales.unitsPerMeter[2],i=(h-b[2])/(f[2]-b[2]),j=aL([],b,f,i),g=aS(j);return g[2]=d,g}class aY{constructor({width:f,height:c,latitude:l=0,longitude:m=0,zoom:p=0,pitch:n=0,bearing:q=0,altitude:a=null,fovy:b=null,position:o=null,nearZMultiplier:t=.02,farZMultiplier:u=1.01}={width:1,height:1}){f=f||1,c=c||1,null===b&&null===a?b=aT(a=1.5):null===b?b=aT(a):null===a&&(a=aU(b));const r=aQ(p);a=Math.max(.75,a);const s=function({latitude:c,longitude:i,highPrecision:j=!1}){aM(Number.isFinite(c)&&Number.isFinite(i));const b={},d=Math.cos(c*aO),e=1.4222222222222223/d,a=12790407194604047e-21/d;if(b.unitsPerMeter=[a,a,a],b.metersPerUnit=[1/a,1/a,1/a],b.unitsPerDegree=[1.4222222222222223,e,a],b.degreesPerUnit=[.703125,1/e,1/a],j){const f=aO*Math.tan(c*aO)/d,k=1.4222222222222223*f/2,g=12790407194604047e-21*f,h=g/e*a;b.unitsPerDegree2=[0,k,g],b.unitsPerMeter2=[h,0,h]}return b}({longitude:m,latitude:l}),d=aR([m,l]);if(d[2]=0,o){var e,g,h,i,j,k;i=d,j=d,k=(e=[],g=o,h=s.unitsPerMeter,e[0]=g[0]*h[0],e[1]=g[1]*h[1],e[2]=g[2]*h[2],e),i[0]=j[0]+k[0],i[1]=j[1]+k[1],i[2]=j[2]+k[2]}this.projectionMatrix=function({width:h,height:i,pitch:j,altitude:k,fovy:l,nearZMultiplier:m,farZMultiplier:n}){var a,f,g,c,b,d,e;const{fov:o,aspect:p,near:q,far:r}=function({width:f,height:g,fovy:a=aT(1.5),altitude:d,pitch:h=0,nearZMultiplier:i=1,farZMultiplier:j=1}){void 0!==d&&(a=aT(d));const b=.5*a*aO,c=aU(a),e=h*aO;return{fov:2*b,aspect:f/g,focalDistance:c,near:i,far:(Math.sin(e)*(Math.sin(b)*c/Math.sin(Math.min(Math.max(Math.PI/2-e-b,.01),Math.PI-.01)))+c)*j}}({width:h,height:i,altitude:k,fovy:l,pitch:j,nearZMultiplier:m,farZMultiplier:n}),s=(a=[],f=o,g=p,c=q,b=r,e=1/Math.tan(f/2),a[0]=e/g,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=e,a[6]=0,a[7]=0,a[8]=0,a[9]=0,a[11]=-1,a[12]=0,a[13]=0,a[15]=0,null!=b&&b!==1/0?(d=1/(c-b),a[10]=(b+c)*d,a[14]=2*b*c*d):(a[10]=-1,a[14]=-2*c),a);return s}({width:f,height:c,pitch:n,fovy:b,nearZMultiplier:t,farZMultiplier:u}),this.viewMatrix=function({height:F,pitch:G,bearing:H,altitude:I,scale:l,center:E=null}){var a,b,m,f,g,n,o,p,q,r,s,t,u,c,d,v,h,i,w,x,y,z,A,B,C,D,j,k;const e=aB();return aH(e,e,[0,0,-I]),a=e,b=e,m=-G*aO,f=Math.sin(m),g=Math.cos(m),n=b[4],o=b[5],p=b[6],q=b[7],r=b[8],s=b[9],t=b[10],u=b[11],b!==a&&(a[0]=b[0],a[1]=b[1],a[2]=b[2],a[3]=b[3],a[12]=b[12],a[13]=b[13],a[14]=b[14],a[15]=b[15]),a[4]=n*g+r*f,a[5]=o*g+s*f,a[6]=p*g+t*f,a[7]=q*g+u*f,a[8]=r*g-n*f,a[9]=s*g-o*f,a[10]=t*g-p*f,a[11]=u*g-q*f,c=e,d=e,v=H*aO,h=Math.sin(v),i=Math.cos(v),w=d[0],x=d[1],y=d[2],z=d[3],A=d[4],B=d[5],C=d[6],D=d[7],d!==c&&(c[8]=d[8],c[9]=d[9],c[10]=d[10],c[11]=d[11],c[12]=d[12],c[13]=d[13],c[14]=d[14],c[15]=d[15]),c[0]=w*i+A*h,c[1]=x*i+B*h,c[2]=y*i+C*h,c[3]=z*i+D*h,c[4]=A*i-w*h,c[5]=B*i-x*h,c[6]=C*i-y*h,c[7]=D*i-z*h,aI(e,e,[l/=F,l,l]),E&&aH(e,e,(j=[],k=E,j[0]=-k[0],j[1]=-k[1],j[2]=-k[2],j)),e}({height:c,scale:r,center:d,pitch:n,bearing:q,altitude:a}),this.width=f,this.height=c,this.scale=r,this.latitude=l,this.longitude=m,this.zoom=p,this.pitch=n,this.bearing=q,this.altitude=a,this.fovy=b,this.center=d,this.meterOffset=o||[0,0,0],this.distanceScales=s,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 b,c,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,a;const{width:I,height:J,projectionMatrix:K,viewMatrix:L}=this,G=aB();aG(G,G,K),aG(G,G,L),this.viewProjectionMatrix=G;const d=aB();aI(d,d,[I/2,-J/2,1]),aH(d,d,[1,-1,0]),aG(d,d,G);const H=(b=aB(),e=(c=d)[0],f=c[1],g=c[2],h=c[3],i=c[4],j=c[5],k=c[6],l=c[7],m=c[8],n=c[9],o=c[10],p=c[11],q=c[12],r=c[13],s=c[14],t=c[15],u=e*j-f*i,v=e*k-g*i,w=e*l-h*i,x=f*k-g*j,y=f*l-h*j,z=g*l-h*k,A=m*r-n*q,B=m*s-o*q,C=m*t-p*q,D=n*s-o*r,E=n*t-p*r,F=o*t-p*s,a=u*F-v*E+w*D+x*C-y*B+z*A,a?(a=1/a,b[0]=(j*F-k*E+l*D)*a,b[1]=(g*E-f*F-h*D)*a,b[2]=(r*z-s*y+t*x)*a,b[3]=(o*y-n*z-p*x)*a,b[4]=(k*C-i*F-l*B)*a,b[5]=(e*F-g*C+h*B)*a,b[6]=(s*w-q*z-t*v)*a,b[7]=(m*z-o*w+p*v)*a,b[8]=(i*E-j*C+l*A)*a,b[9]=(f*C-e*E-h*A)*a,b[10]=(q*y-r*w+t*u)*a,b[11]=(n*w-m*y-p*u)*a,b[12]=(j*B-i*D-k*A)*a,b[13]=(e*D-f*B+g*A)*a,b[14]=(r*v-q*x-s*u)*a,b[15]=(m*x-n*v+o*u)*a,b):null);if(!H)throw new Error("Pixel project matrix not invertible");this.pixelProjectionMatrix=d,this.pixelUnprojectionMatrix=H}equals(a){return a instanceof aY&&a.width===this.width&&a.height===this.height&&aJ(a.projectionMatrix,this.projectionMatrix)&&aJ(a.viewMatrix,this.viewMatrix)}project(a,{topLeft:f=!0}={}){const g=this.projectPosition(a),b=function(d,e){const[a,b,c=0]=d;return aM(Number.isFinite(a)&&Number.isFinite(b)&&Number.isFinite(c)),aC(e,[a,b,c,1])}(g,this.pixelProjectionMatrix),[c,d]=b,e=f?d:this.height-d;return 2===a.length?[c,e]:[c,e,b[2]]}unproject(f,{topLeft:g=!0,targetZ:a}={}){const[h,d,e]=f,i=g?d:this.height-d,j=a&&a*this.distanceScales.unitsPerMeter[2],k=aV([h,i,e],this.pixelUnprojectionMatrix,j),[b,c,l]=this.unprojectPosition(k);return Number.isFinite(e)?[b,c,l]:Number.isFinite(a)?[b,c,a]:[b,c]}projectPosition(a){const[b,c]=aR(a),d=(a[2]||0)*this.distanceScales.unitsPerMeter[2];return[b,c,d]}unprojectPosition(a){const[b,c]=aS(a),d=(a[2]||0)*this.distanceScales.metersPerUnit[2];return[b,c,d]}projectFlat(a){return aR(a)}unprojectFlat(a){return aS(a)}getMapCenterByLngLatPosition({lngLat:c,pos:d}){var a,b;const e=aV(d,this.pixelUnprojectionMatrix),f=aR(c),g=aK([],f,(a=[],b=e,a[0]=-b[0],a[1]=-b[1],a)),h=aK([],this.center,g);return aS(h)}getLocationAtPoint({lngLat:a,pos:b}){return this.getMapCenterByLngLatPosition({lngLat:a,pos:b})}fitBounds(c,d={}){const{width:a,height:b}=this,{longitude:e,latitude:f,zoom:g}=function({width:m,height:n,bounds:o,minExtent:f=0,maxZoom:p=24,padding:a=0,offset:g=[0,0]}){const[[q,r],[s,t]]=o;if(Number.isFinite(a)){const b=a;a={top:b,bottom:b,left:b,right:b}}else aM(Number.isFinite(a.top)&&Number.isFinite(a.bottom)&&Number.isFinite(a.left)&&Number.isFinite(a.right));const c=aR([q,aE(t,-85.051129,85.051129)]),d=aR([s,aE(r,-85.051129,85.051129)]),h=[Math.max(Math.abs(d[0]-c[0]),f),Math.max(Math.abs(d[1]-c[1]),f)],e=[m-a.left-a.right-2*Math.abs(g[0]),n-a.top-a.bottom-2*Math.abs(g[1])];aM(e[0]>0&&e[1]>0);const i=e[0]/h[0],j=e[1]/h[1],u=(a.right-a.left)/2/i,v=(a.bottom-a.top)/2/j,w=[(d[0]+c[0])/2+u,(d[1]+c[1])/2+v],k=aS(w),l=Math.min(p,aF(Math.abs(Math.min(i,j))));return aM(Number.isFinite(l)),{longitude:k[0],latitude:k[1],zoom:l}}(Object.assign({width:a,height:b,bounds:c},d));return new aY({width:a,height:b,longitude:e,latitude:f,zoom:g})}getBounds(b){const a=this.getBoundingRegion(b),c=Math.min(...a.map(a=>a[0])),d=Math.max(...a.map(a=>a[0])),e=Math.min(...a.map(a=>a[1])),f=Math.max(...a.map(a=>a[1]));return[[c,e],[d,f]]}getBoundingRegion(a={}){return function(a,d=0){const{width:e,height:h,unproject:b}=a,c={targetZ:d},i=b([0,h],c),j=b([e,h],c);let f,g;const k=a.fovy?.5*a.fovy*aW:Math.atan(.5/a.altitude),l=(90-a.pitch)*aW;return k>l-.01?(f=aX(a,0,d),g=aX(a,e,d)):(f=b([0,0],c),g=b([e,0],c)),[i,j,g,f]}(this,a.z||0)}}const aZ=["longitude","latitude","zoom"],a$={curve:1.414,speed:1.2};function a_(d,h,i){var f,j,k,o,p,q;i=Object.assign({},a$,i);const g=i.curve,l=d.zoom,w=[d.longitude,d.latitude],x=aQ(l),y=h.zoom,z=[h.longitude,h.latitude],A=aQ(y-l),r=aR(w),B=aR(z),s=(f=[],j=B,k=r,f[0]=j[0]-k[0],f[1]=j[1]-k[1],f),a=Math.max(d.width,d.height),e=a/A,t=(p=(o=s)[0],q=o[1],Math.hypot(p,q)*x),c=Math.max(t,.01),b=g*g,m=(e*e-a*a+b*b*c*c)/(2*a*b*c),n=(e*e-a*a-b*b*c*c)/(2*e*b*c),u=Math.log(Math.sqrt(m*m+1)-m),v=Math.log(Math.sqrt(n*n+1)-n);return{startZoom:l,startCenterXY:r,uDelta:s,w0:a,u1:t,S:(v-u)/g,rho:g,rho2:b,r0:u,r1:v}}var N=function(){if("undefined"!=typeof Map)return Map;function a(a,c){var b=-1;return a.some(function(a,d){return a[0]===c&&(b=d,!0)}),b}return function(){function b(){this.__entries__=[]}return Object.defineProperty(b.prototype,"size",{get:function(){return this.__entries__.length},enumerable:!0,configurable:!0}),b.prototype.get=function(c){var d=a(this.__entries__,c),b=this.__entries__[d];return b&&b[1]},b.prototype.set=function(b,c){var d=a(this.__entries__,b);~d?this.__entries__[d][1]=c:this.__entries__.push([b,c])},b.prototype.delete=function(d){var b=this.__entries__,c=a(b,d);~c&&b.splice(c,1)},b.prototype.has=function(b){return!!~a(this.__entries__,b)},b.prototype.clear=function(){this.__entries__.splice(0)},b.prototype.forEach=function(e,a){void 0===a&&(a=null);for(var b=0,c=this.__entries__;b0},a.prototype.connect_=function(){a0&&!this.connected_&&(document.addEventListener("transitionend",this.onTransitionEnd_),window.addEventListener("resize",this.refresh),a3?(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)},a.prototype.disconnect_=function(){a0&&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)},a.prototype.onTransitionEnd_=function(b){var a=b.propertyName,c=void 0===a?"":a;a2.some(function(a){return!!~c.indexOf(a)})&&this.refresh()},a.getInstance=function(){return this.instance_||(this.instance_=new a),this.instance_},a.instance_=null,a}(),a5=function(b,c){for(var a=0,d=Object.keys(c);a0},a}(),bi="undefined"!=typeof WeakMap?new WeakMap:new N,O=function(){function a(b){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function.");if(!arguments.length)throw new TypeError("1 argument required, but only 0 present.");var c=a4.getInstance(),d=new bh(b,c,this);bi.set(this,d)}return a}();["observe","unobserve","disconnect"].forEach(function(a){O.prototype[a]=function(){var b;return(b=bi.get(this))[a].apply(b,arguments)}});var bj=void 0!==o.ResizeObserver?o.ResizeObserver:O;function bk(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}function bl(d,c){for(var b=0;b=a.length?{done:!0}:{done:!1,value:a[d++]}},e:function(a){throw a},f:b}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var e,f,g=!0,h=!1;return{s:function(){e=a[Symbol.iterator]()},n:function(){var a=e.next();return g=a.done,a},e:function(a){h=!0,f=a},f:function(){try{g||null==e.return||e.return()}finally{if(h)throw f}}}}function bq(a,c){if(a){if("string"==typeof a)return br(a,c);var b=Object.prototype.toString.call(a).slice(8,-1);if("Object"===b&&a.constructor&&(b=a.constructor.name),"Map"===b||"Set"===b)return Array.from(a);if("Arguments"===b||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(b))return br(a,c)}}function br(c,a){(null==a||a>c.length)&&(a=c.length);for(var b=0,d=new Array(a);b1&& void 0!==arguments[1]?arguments[1]:"component";b.debug&&a.checkPropTypes(Q,b,"prop",c)}var i=function(){function a(b){var c=this;if(bk(this,a),g(this,"props",R),g(this,"width",0),g(this,"height",0),g(this,"_fireLoadEvent",function(){c.props.onLoad({type:"load",target:c._map})}),g(this,"_handleError",function(a){c.props.onError(a)}),!b.mapboxgl)throw new Error("Mapbox not available");this.mapboxgl=b.mapboxgl,a.initialized||(a.initialized=!0,this._checkStyleSheet(this.mapboxgl.version)),this._initialize(b)}return bm(a,[{key:"finalize",value:function(){return this._destroy(),this}},{key:"setProps",value:function(a){return this._update(this.props,a),this}},{key:"redraw",value:function(){var a=this._map;a.style&&(a._frame&&(a._frame.cancel(),a._frame=null),a._render())}},{key:"getMap",value:function(){return this._map}},{key:"_reuse",value:function(b){this._map=a.savedMap;var d=this._map.getContainer(),c=b.container;for(c.classList.add("mapboxgl-map");d.childNodes.length>0;)c.appendChild(d.childNodes[0]);this._map._container=c,a.savedMap=null,b.mapStyle&&this._map.setStyle(bt(b.mapStyle),{diff:!1}),this._map.isStyleLoaded()?this._fireLoadEvent():this._map.once("styledata",this._fireLoadEvent)}},{key:"_create",value:function(b){if(b.reuseMaps&&a.savedMap)this._reuse(b);else{if(b.gl){var d=HTMLCanvasElement.prototype.getContext;HTMLCanvasElement.prototype.getContext=function(){return HTMLCanvasElement.prototype.getContext=d,b.gl}}var c={container:b.container,center:[0,0],zoom:8,pitch:0,bearing:0,maxZoom:24,style:bt(b.mapStyle),interactive:!1,trackResize:!1,attributionControl:b.attributionControl,preserveDrawingBuffer:b.preserveDrawingBuffer};b.transformRequest&&(c.transformRequest=b.transformRequest),this._map=new this.mapboxgl.Map(Object.assign({},c,b.mapOptions)),this._map.once("load",this._fireLoadEvent),this._map.on("error",this._handleError)}return this}},{key:"_destroy",value:function(){this._map&&(this.props.reuseMaps&&!a.savedMap?(a.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(a){var d=this;bv(a=Object.assign({},R,a),"Mapbox"),this.mapboxgl.accessToken=a.mapboxApiAccessToken||R.mapboxApiAccessToken,this.mapboxgl.baseApiUrl=a.mapboxApiUrl,this._create(a);var b=a.container;Object.defineProperty(b,"offsetWidth",{configurable:!0,get:function(){return d.width}}),Object.defineProperty(b,"clientWidth",{configurable:!0,get:function(){return d.width}}),Object.defineProperty(b,"offsetHeight",{configurable:!0,get:function(){return d.height}}),Object.defineProperty(b,"clientHeight",{configurable:!0,get:function(){return d.height}});var c=this._map.getCanvas();c&&(c.style.outline="none"),this._updateMapViewport({},a),this._updateMapSize({},a),this.props=a}},{key:"_update",value:function(b,a){if(this._map){bv(a=Object.assign({},this.props,a),"Mapbox");var c=this._updateMapViewport(b,a),d=this._updateMapSize(b,a);this._updateMapStyle(b,a),!a.asyncRender&&(c||d)&&this.redraw(),this.props=a}}},{key:"_updateMapStyle",value:function(b,a){b.mapStyle!==a.mapStyle&&this._map.setStyle(bt(a.mapStyle),{diff:!a.preventStyleDiffing})}},{key:"_updateMapSize",value:function(b,a){var c=b.width!==a.width||b.height!==a.height;return c&&(this.width=a.width,this.height=a.height,this._map.resize()),c}},{key:"_updateMapViewport",value:function(d,e){var b=this._getViewState(d),a=this._getViewState(e),c=a.latitude!==b.latitude||a.longitude!==b.longitude||a.zoom!==b.zoom||a.pitch!==b.pitch||a.bearing!==b.bearing||a.altitude!==b.altitude;return c&&(this._map.jumpTo(this._viewStateToMapboxProps(a)),a.altitude!==b.altitude&&(this._map.transform.altitude=a.altitude)),c}},{key:"_getViewState",value:function(b){var a=b.viewState||b,f=a.longitude,g=a.latitude,h=a.zoom,c=a.pitch,d=a.bearing,e=a.altitude;return{longitude:f,latitude:g,zoom:h,pitch:void 0===c?0:c,bearing:void 0===d?0:d,altitude:void 0===e?1.5:e}}},{key:"_checkStyleSheet",value:function(){var c=arguments.length>0&& void 0!==arguments[0]?arguments[0]:"0.47.0";if(void 0!==P)try{var a=P.createElement("div");if(a.className="mapboxgl-map",a.style.display="none",P.body.appendChild(a),!("static"!==window.getComputedStyle(a).position)){var b=P.createElement("link");b.setAttribute("rel","stylesheet"),b.setAttribute("type","text/css"),b.setAttribute("href","https://api.tiles.mapbox.com/mapbox-gl-js/v".concat(c,"/mapbox-gl.css")),P.head.appendChild(b)}}catch(d){}}},{key:"_viewStateToMapboxProps",value:function(a){return{center:[a.longitude,a.latitude],zoom:a.zoom,bearing:a.bearing,pitch:a.pitch}}}]),a}();g(i,"initialized",!1),g(i,"propTypes",Q),g(i,"defaultProps",R),g(i,"savedMap",null);var S=b(6158),A=b.n(S);function bw(a){return Array.isArray(a)||ArrayBuffer.isView(a)}function bx(a,b){if(a===b)return!0;if(bw(a)&&bw(b)){if(a.length!==b.length)return!1;for(var c=0;c=Math.abs(a-b)}function by(a,b,c){return Math.max(b,Math.min(c,a))}function bz(a,c,b){return bw(a)?a.map(function(a,d){return bz(a,c[d],b)}):b*c+(1-b)*a}function bA(a,b){if(!a)throw new Error(b||"react-map-gl: assertion failed.")}function bB(c,d){var a=Object.keys(c);if(Object.getOwnPropertySymbols){var b=Object.getOwnPropertySymbols(c);d&&(b=b.filter(function(a){return Object.getOwnPropertyDescriptor(c,a).enumerable})),a.push.apply(a,b)}return a}function bC(c){for(var a=1;a0,"`scale` must be a positive number");var f=this._state,b=f.startZoom,c=f.startZoomLngLat;Number.isFinite(b)||(b=this._viewportProps.zoom,c=this._unproject(i)||this._unproject(d)),bA(c,"`startZoomLngLat` prop is required for zoom behavior to calculate where to position the map.");var g=this._calculateNewZoom({scale:e,startZoom:b||0}),j=new aY(Object.assign({},this._viewportProps,{zoom:g})),k=j.getMapCenterByLngLatPosition({lngLat:c,pos:d}),h=aA(k,2),l=h[0],m=h[1];return this._getUpdatedMapState({zoom:g,longitude:l,latitude:m})}},{key:"zoomEnd",value:function(){return this._getUpdatedMapState({startZoomLngLat:null,startZoom:null})}},{key:"_getUpdatedMapState",value:function(b){return new a(Object.assign({},this._viewportProps,this._state,b))}},{key:"_applyConstraints",value:function(a){var b=a.maxZoom,c=a.minZoom,d=a.zoom;a.zoom=by(d,c,b);var e=a.maxPitch,f=a.minPitch,g=a.pitch;return a.pitch=by(g,f,e),Object.assign(a,function({width:j,height:e,longitude:b,latitude:a,zoom:d,pitch:k=0,bearing:c=0}){(b< -180||b>180)&&(b=aD(b+180,360)-180),(c< -180||c>180)&&(c=aD(c+180,360)-180);const f=aF(e/512);if(d<=f)d=f,a=0;else{const g=e/2/Math.pow(2,d),h=aS([0,g])[1];if(ai&&(a=i)}}return{width:j,height:e,longitude:b,latitude:a,zoom:d,pitch:k,bearing:c}}(a)),a}},{key:"_unproject",value:function(a){var b=new aY(this._viewportProps);return a&&b.unproject(a)}},{key:"_calculateNewLngLat",value:function(a){var b=a.startPanLngLat,c=a.pos,d=new aY(this._viewportProps);return d.getMapCenterByLngLatPosition({lngLat:b,pos:c})}},{key:"_calculateNewZoom",value:function(a){var c=a.scale,d=a.startZoom,b=this._viewportProps,e=b.maxZoom,f=b.minZoom;return by(d+Math.log2(c),f,e)}},{key:"_calculateNewPitchAndBearing",value:function(c){var f=c.deltaScaleX,a=c.deltaScaleY,g=c.startBearing,b=c.startPitch;a=by(a,-1,1);var e=this._viewportProps,h=e.minPitch,i=e.maxPitch,d=b;return a>0?d=b+a*(i-b):a<0&&(d=b-a*(h-b)),{pitch:d,bearing:g+180*f}}},{key:"_getRotationParams",value:function(c,d){var h=c[0]-d[0],e=c[1]-d[1],i=c[1],a=d[1],f=this._viewportProps,j=f.width,g=f.height,b=0;return e>0?Math.abs(g-a)>5&&(b=e/(a-g)*1.2):e<0&&a>5&&(b=1-i/a),{deltaScaleX:h/j,deltaScaleY:b=Math.min(1,Math.max(-1,b))}}}]),a}();function bF(a){return a[0].toLowerCase()+a.slice(1)}function bG(c,d){var a=Object.keys(c);if(Object.getOwnPropertySymbols){var b=Object.getOwnPropertySymbols(c);d&&(b=b.filter(function(a){return Object.getOwnPropertyDescriptor(c,a).enumerable})),a.push.apply(a,b)}return a}function bH(c){for(var a=1;a1&& void 0!==arguments[1]?arguments[1]:{},b=a.current&&a.current.getMap();return b&&b.queryRenderedFeatures(c,d)}}},[]);var p=(0,c.useCallback)(function(b){var a=b.target;a===o.current&&a.scrollTo(0,0)},[]),q=d&&c.createElement(bI,{value:bN(bN({},b),{},{viewport:b.viewport||bP(bN({map:d,props:a},m)),map:d,container:b.container||h.current})},c.createElement("div",{key:"map-overlays",className:"overlays",ref:o,style:bQ,onScroll:p},a.children)),r=a.className,s=a.width,t=a.height,u=a.style,v=a.visibilityConstraints,w=Object.assign({position:"relative"},u,{width:s,height:t}),x=a.visible&&function(c){var b=arguments.length>1&& void 0!==arguments[1]?arguments[1]:B;for(var a in b){var d=a.slice(0,3),e=bF(a.slice(3));if("min"===d&&c[e]b[a])return!1}return!0}(a.viewState||a,v),y=Object.assign({},bQ,{visibility:x?"inherit":"hidden"});return c.createElement("div",{key:"map-container",ref:h,style:w},c.createElement("div",{key:"map-mapbox",ref:n,style:y,className:r}),q,!l&&!a.disableTokenWarning&&c.createElement(bR,null))});j.supported=function(){return A()&&A().supported()},j.propTypes=T,j.defaultProps=U;var q=j;function bS(c,a){(null==a||a>c.length)&&(a=c.length);for(var b=0,d=new Array(a);b=a.length?{done:!0}:{done:!1,value:a[d++]}},e:function(a){throw a},f:b}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var e,f,g=!0,h=!1;return{s:function(){e=a[Symbol.iterator]()},n:function(){var a=e.next();return g=a.done,a},e:function(a){h=!0,f=a},f:function(){try{g||null==e.return||e.return()}finally{if(h)throw f}}}}(this.propNames||[]);try{for(a.s();!(b=a.n()).done;){var c=b.value;if(!bx(d[c],e[c]))return!1}}catch(f){a.e(f)}finally{a.f()}return!0}},{key:"initializeProps",value:function(a,b){return{start:a,end:b}}},{key:"interpolateProps",value:function(a,b,c){bA(!1,"interpolateProps is not implemented")}},{key:"getDuration",value:function(b,a){return a.transitionDuration}}]),a}();function bT(a){if(void 0===a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return a}function bU(a,b){return(bU=Object.setPrototypeOf||function(a,b){return a.__proto__=b,a})(a,b)}function bV(b,a){if("function"!=typeof a&&null!==a)throw new TypeError("Super expression must either be null or a function");b.prototype=Object.create(a&&a.prototype,{constructor:{value:b,writable:!0,configurable:!0}}),Object.defineProperty(b,"prototype",{writable:!1}),a&&bU(b,a)}function bW(a){return(bW="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a})(a)}function bX(b,a){if(a&&("object"===bW(a)||"function"==typeof a))return a;if(void 0!==a)throw new TypeError("Derived constructors may only return object or undefined");return bT(b)}function bY(a){return(bY=Object.setPrototypeOf?Object.getPrototypeOf:function(a){return a.__proto__||Object.getPrototypeOf(a)})(a)}var bZ={longitude:1,bearing:1};function b$(a){return Number.isFinite(a)||Array.isArray(a)}function b_(b,c,a){return b in bZ&&Math.abs(a-c)>180&&(a=a<0?a+360:a-360),a}function b0(a,c){if("undefined"==typeof Symbol||null==a[Symbol.iterator]){if(Array.isArray(a)||(e=b1(a))||c&&a&&"number"==typeof a.length){e&&(a=e);var d=0,b=function(){};return{s:b,n:function(){return d>=a.length?{done:!0}:{done:!1,value:a[d++]}},e:function(a){throw a},f:b}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var e,f,g=!0,h=!1;return{s:function(){e=a[Symbol.iterator]()},n:function(){var a=e.next();return g=a.done,a},e:function(a){h=!0,f=a},f:function(){try{g||null==e.return||e.return()}finally{if(h)throw f}}}}function b1(a,c){if(a){if("string"==typeof a)return b2(a,c);var b=Object.prototype.toString.call(a).slice(8,-1);if("Object"===b&&a.constructor&&(b=a.constructor.name),"Map"===b||"Set"===b)return Array.from(a);if("Arguments"===b||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(b))return b2(a,c)}}function b2(c,a){(null==a||a>c.length)&&(a=c.length);for(var b=0,d=new Array(a);b=a.length?{done:!0}:{done:!1,value:a[d++]}},e:function(a){throw a},f:b}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var e,f,g=!0,h=!1;return{s:function(){e=a[Symbol.iterator]()},n:function(){var a=e.next();return g=a.done,a},e:function(a){h=!0,f=a},f:function(){try{g||null==e.return||e.return()}finally{if(h)throw f}}}}function b8(a,c){if(a){if("string"==typeof a)return b9(a,c);var b=Object.prototype.toString.call(a).slice(8,-1);if("Object"===b&&a.constructor&&(b=a.constructor.name),"Map"===b||"Set"===b)return Array.from(a);if("Arguments"===b||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(b))return b9(a,c)}}function b9(c,a){(null==a||a>c.length)&&(a=c.length);for(var b=0,d=new Array(a);b0&& void 0!==arguments[0]?arguments[0]:{};return bk(this,d),g(bT(a=e.call(this)),"propNames",b3),a.props=Object.assign({},b6,b),a}bm(d,[{key:"initializeProps",value:function(h,i){var j,e={},f={},c=b0(b4);try{for(c.s();!(j=c.n()).done;){var a=j.value,g=h[a],k=i[a];bA(b$(g)&&b$(k),"".concat(a," must be supplied for transition")),e[a]=g,f[a]=b_(a,g,k)}}catch(n){c.e(n)}finally{c.f()}var l,d=b0(b5);try{for(d.s();!(l=d.n()).done;){var b=l.value,m=h[b]||0,o=i[b]||0;e[b]=m,f[b]=b_(b,m,o)}}catch(p){d.e(p)}finally{d.f()}return{start:e,end:f}}},{key:"interpolateProps",value:function(c,d,e){var f,g=function(h,i,j,r={}){var k,l,m,c,d,e;const a={},{startZoom:s,startCenterXY:t,uDelta:u,w0:v,u1:n,S:w,rho:o,rho2:x,r0:b}=a_(h,i,r);if(n<.01){for(const f of aZ){const y=h[f],z=i[f];a[f]=(k=y,l=z,(m=j)*l+(1-m)*k)}return a}const p=j*w,A=s+aF(1/(Math.cosh(b)/Math.cosh(b+o*p))),g=(c=[],d=u,e=v*((Math.cosh(b)*Math.tanh(b+o*p)-Math.sinh(b))/x)/n,c[0]=d[0]*e,c[1]=d[1]*e,c);aK(g,g,t);const q=aS(g);return a.longitude=q[0],a.latitude=q[1],a.zoom=A,a}(c,d,e,this.props),a=b0(b5);try{for(a.s();!(f=a.n()).done;){var b=f.value;g[b]=bz(c[b],d[b],e)}}catch(h){a.e(h)}finally{a.f()}return g}},{key:"getDuration",value:function(c,b){var a=b.transitionDuration;return"auto"===a&&(a=function(f,g,a={}){a=Object.assign({},a$,a);const{screenSpeed:c,speed:h,maxDuration:d}=a,{S:i,rho:j}=a_(f,g,a),e=1e3*i;let b;return b=Number.isFinite(c)?e/(c/j):e/h,Number.isFinite(d)&&b>d?0:b}(c,b,this.props)),a}}])}(C);var ca=["longitude","latitude","zoom","bearing","pitch"],D=function(b){bV(a,b);var c,d,e=(c=a,d=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(a){return!1}}(),function(){var a,b=bY(c);if(d){var e=bY(this).constructor;a=Reflect.construct(b,arguments,e)}else a=b.apply(this,arguments);return bX(this,a)});function a(){var c,b=arguments.length>0&& void 0!==arguments[0]?arguments[0]:{};return bk(this,a),c=e.call(this),Array.isArray(b)&&(b={transitionProps:b}),c.propNames=b.transitionProps||ca,b.around&&(c.around=b.around),c}return bm(a,[{key:"initializeProps",value:function(g,c){var d={},e={};if(this.around){d.around=this.around;var h=new aY(g).unproject(this.around);Object.assign(e,c,{around:new aY(c).project(h),aroundLngLat:h})}var i,b=b7(this.propNames);try{for(b.s();!(i=b.n()).done;){var a=i.value,f=g[a],j=c[a];bA(b$(f)&&b$(j),"".concat(a," must be supplied for transition")),d[a]=f,e[a]=b_(a,f,j)}}catch(k){b.e(k)}finally{b.f()}return{start:d,end:e}}},{key:"interpolateProps",value:function(e,a,f){var g,b={},c=b7(this.propNames);try{for(c.s();!(g=c.n()).done;){var d=g.value;b[d]=bz(e[d],a[d],f)}}catch(i){c.e(i)}finally{c.f()}if(a.around){var h=aA(new aY(Object.assign({},a,b)).getMapCenterByLngLatPosition({lngLat:a.aroundLngLat,pos:bz(e.around,a.around,f)}),2),j=h[0],k=h[1];b.longitude=j,b.latitude=k}return b}}]),a}(C),r=function(){},E={BREAK:1,SNAP_TO_END:2,IGNORE:3,UPDATE:4},V={transitionDuration:0,transitionEasing:function(a){return a},transitionInterpolator:new D,transitionInterruption:E.BREAK,onTransitionStart:r,onTransitionInterrupt:r,onTransitionEnd:r},F=function(){function a(){var c=this,b=arguments.length>0&& void 0!==arguments[0]?arguments[0]:{};bk(this,a),g(this,"_animationFrame",null),g(this,"_onTransitionFrame",function(){c._animationFrame=requestAnimationFrame(c._onTransitionFrame),c._updateViewport()}),this.props=null,this.onViewportChange=b.onViewportChange||r,this.onStateChange=b.onStateChange||r,this.time=b.getTime||Date.now}return bm(a,[{key:"getViewportInTransition",value:function(){return this._animationFrame?this.state.propsInTransition:null}},{key:"processViewportChange",value:function(c){var a=this.props;if(this.props=c,!a||this._shouldIgnoreViewportChange(a,c))return!1;if(this._isTransitionEnabled(c)){var d=Object.assign({},a),b=Object.assign({},c);if(this._isTransitionInProgress()&&(a.onTransitionInterrupt(),this.state.interruption===E.SNAP_TO_END?Object.assign(d,this.state.endProps):Object.assign(d,this.state.propsInTransition),this.state.interruption===E.UPDATE)){var f,g,h,e=this.time(),i=(e-this.state.startTime)/this.state.duration;b.transitionDuration=this.state.duration-(e-this.state.startTime),b.transitionEasing=(h=(f=this.state.easing)(g=i),function(a){return 1/(1-h)*(f(a*(1-g)+g)-h)}),b.transitionInterpolator=d.transitionInterpolator}return b.onTransitionStart(),this._triggerTransition(d,b),!0}return this._isTransitionInProgress()&&(a.onTransitionInterrupt(),this._endTransition()),!1}},{key:"_isTransitionInProgress",value:function(){return Boolean(this._animationFrame)}},{key:"_isTransitionEnabled",value:function(a){var b=a.transitionDuration,c=a.transitionInterpolator;return(b>0||"auto"===b)&&Boolean(c)}},{key:"_isUpdateDueToCurrentTransition",value:function(a){return!!this.state.propsInTransition&&this.state.interpolator.arePropsEqual(a,this.state.propsInTransition)}},{key:"_shouldIgnoreViewportChange",value:function(b,a){return!b||(this._isTransitionInProgress()?this.state.interruption===E.IGNORE||this._isUpdateDueToCurrentTransition(a):!this._isTransitionEnabled(a)||a.transitionInterpolator.arePropsEqual(b,a))}},{key:"_triggerTransition",value:function(b,a){bA(this._isTransitionEnabled(a)),this._animationFrame&&cancelAnimationFrame(this._animationFrame);var c=a.transitionInterpolator,d=c.getDuration?c.getDuration(b,a):a.transitionDuration;if(0!==d){var e=a.transitionInterpolator.initializeProps(b,a),f={inTransition:!0,isZooming:b.zoom!==a.zoom,isPanning:b.longitude!==a.longitude||b.latitude!==a.latitude,isRotating:b.bearing!==a.bearing||b.pitch!==a.pitch};this.state={duration:d,easing:a.transitionEasing,interpolator:a.transitionInterpolator,interruption:a.transitionInterruption,startTime:this.time(),startProps:e.start,endProps:e.end,animation:null,propsInTransition:{}},this._onTransitionFrame(),this.onStateChange(f)}}},{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 d=this.time(),a=this.state,e=a.startTime,f=a.duration,g=a.easing,h=a.interpolator,i=a.startProps,j=a.endProps,c=!1,b=(d-e)/f;b>=1&&(b=1,c=!0),b=g(b);var k=h.interpolateProps(i,j,b),l=new bE(Object.assign({},this.props,k));this.state.propsInTransition=l.getViewportProps(),this.onViewportChange(this.state.propsInTransition,this.props),c&&(this._endTransition(),this.props.onTransitionEnd())}}]),a}();g(F,"defaultProps",V);var W=b(840),k=b.n(W);const cb={mousedown:1,mousemove:2,mouseup:4};!function(a){const b=a.prototype.handler;a.prototype.handler=function(a){const c=this.store;a.button>0&&"pointerdown"===a.type&& !function(b,c){for(let a=0;ab.pointerId===a.pointerId)&&c.push(a),b.call(this,a)}}(k().PointerEventInput),k().MouseInput.prototype.handler=function(a){let b=cb[a.type];1&b&&a.button>=0&&(this.pressed=!0),2&b&&0===a.which&&(b=4),this.pressed&&(4&b&&(this.pressed=!1),this.callback(this.manager,b,{pointers:[a],changedPointers:[a],pointerType:"mouse",srcEvent:a}))};const cc=k().Manager;var e=k();const cd=e?[[e.Pan,{event:"tripan",pointers:3,threshold:0,enable:!1}],[e.Rotate,{enable:!1}],[e.Pinch,{enable:!1}],[e.Swipe,{enable:!1}],[e.Pan,{threshold:0,enable:!1}],[e.Press,{enable:!1}],[e.Tap,{event:"doubletap",taps:2,enable:!1}],[e.Tap,{event:"anytap",enable:!1}],[e.Tap,{enable:!1}]]:null,ce={tripan:["rotate","pinch","pan"],rotate:["pinch"],pinch:["pan"],pan:["press","doubletap","anytap","tap"],doubletap:["anytap"],anytap:["tap"]},cf={doubletap:["tap"]},cg={pointerdown:"pointerdown",pointermove:"pointermove",pointerup:"pointerup",touchstart:"pointerdown",touchmove:"pointermove",touchend:"pointerup",mousedown:"pointerdown",mousemove:"pointermove",mouseup:"pointerup"},s={KEY_EVENTS:["keydown","keyup"],MOUSE_EVENTS:["mousedown","mousemove","mouseup","mouseover","mouseout","mouseleave"],WHEEL_EVENTS:["wheel","mousewheel"]},ch={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"},ci={click:"tap",anyclick:"anytap",dblclick:"doubletap",mousedown:"pointerdown",mousemove:"pointermove",mouseup:"pointerup",mouseover:"pointerover",mouseout:"pointerout",mouseleave:"pointerleave"},X="undefined"!=typeof navigator&&navigator.userAgent?navigator.userAgent.toLowerCase():"",G="undefined"!=typeof window?window:b.g;void 0!==b.g&&b.g;let Y=!1;try{const l={get passive(){return Y=!0,!0}};G.addEventListener("test",l,l),G.removeEventListener("test",l,l)}catch(cj){}const ck=-1!==X.indexOf("firefox"),{WHEEL_EVENTS:cl}=s,cm="wheel";class cn{constructor(b,c,a={}){this.element=b,this.callback=c,this.options=Object.assign({enable:!0},a),this.events=cl.concat(a.events||[]),this.handleEvent=this.handleEvent.bind(this),this.events.forEach(a=>b.addEventListener(a,this.handleEvent,!!Y&&{passive:!1}))}destroy(){this.events.forEach(a=>this.element.removeEventListener(a,this.handleEvent))}enableEventType(a,b){a===cm&&(this.options.enable=b)}handleEvent(b){if(!this.options.enable)return;let a=b.deltaY;G.WheelEvent&&(ck&&b.deltaMode===G.WheelEvent.DOM_DELTA_PIXEL&&(a/=G.devicePixelRatio),b.deltaMode===G.WheelEvent.DOM_DELTA_LINE&&(a*=40));const c={x:b.clientX,y:b.clientY};0!==a&&a%4.000244140625==0&&(a=Math.floor(a/4.000244140625)),b.shiftKey&&a&&(a*=.25),this._onWheel(b,-a,c)}_onWheel(a,b,c){this.callback({type:cm,center:c,delta:b,srcEvent:a,pointerType:"mouse",target:a.target})}}const{MOUSE_EVENTS:co}=s,cp="pointermove",cq="pointerover",cr="pointerout",cs="pointerleave";class ct{constructor(b,c,a={}){this.element=b,this.callback=c,this.pressed=!1,this.options=Object.assign({enable:!0},a),this.enableMoveEvent=this.options.enable,this.enableLeaveEvent=this.options.enable,this.enableOutEvent=this.options.enable,this.enableOverEvent=this.options.enable,this.events=co.concat(a.events||[]),this.handleEvent=this.handleEvent.bind(this),this.events.forEach(a=>b.addEventListener(a,this.handleEvent))}destroy(){this.events.forEach(a=>this.element.removeEventListener(a,this.handleEvent))}enableEventType(a,b){a===cp&&(this.enableMoveEvent=b),a===cq&&(this.enableOverEvent=b),a===cr&&(this.enableOutEvent=b),a===cs&&(this.enableLeaveEvent=b)}handleEvent(a){this.handleOverEvent(a),this.handleOutEvent(a),this.handleLeaveEvent(a),this.handleMoveEvent(a)}handleOverEvent(a){this.enableOverEvent&&"mouseover"===a.type&&this.callback({type:cq,srcEvent:a,pointerType:"mouse",target:a.target})}handleOutEvent(a){this.enableOutEvent&&"mouseout"===a.type&&this.callback({type:cr,srcEvent:a,pointerType:"mouse",target:a.target})}handleLeaveEvent(a){this.enableLeaveEvent&&"mouseleave"===a.type&&this.callback({type:cs,srcEvent:a,pointerType:"mouse",target:a.target})}handleMoveEvent(a){if(this.enableMoveEvent)switch(a.type){case"mousedown":a.button>=0&&(this.pressed=!0);break;case"mousemove":0===a.which&&(this.pressed=!1),this.pressed||this.callback({type:cp,srcEvent:a,pointerType:"mouse",target:a.target});break;case"mouseup":this.pressed=!1;break;default:}}}const{KEY_EVENTS:cu}=s,cv="keydown",cw="keyup";class cx{constructor(a,c,b={}){this.element=a,this.callback=c,this.options=Object.assign({enable:!0},b),this.enableDownEvent=this.options.enable,this.enableUpEvent=this.options.enable,this.events=cu.concat(b.events||[]),this.handleEvent=this.handleEvent.bind(this),a.tabIndex=b.tabIndex||0,a.style.outline="none",this.events.forEach(b=>a.addEventListener(b,this.handleEvent))}destroy(){this.events.forEach(a=>this.element.removeEventListener(a,this.handleEvent))}enableEventType(a,b){a===cv&&(this.enableDownEvent=b),a===cw&&(this.enableUpEvent=b)}handleEvent(a){const b=a.target||a.srcElement;("INPUT"!==b.tagName||"text"!==b.type)&&"TEXTAREA"!==b.tagName&&(this.enableDownEvent&&"keydown"===a.type&&this.callback({type:cv,srcEvent:a,key:a.key,target:a.target}),this.enableUpEvent&&"keyup"===a.type&&this.callback({type:cw,srcEvent:a,key:a.key,target:a.target}))}}const cy="contextmenu";class cz{constructor(a,b,c={}){this.element=a,this.callback=b,this.options=Object.assign({enable:!0},c),this.handleEvent=this.handleEvent.bind(this),a.addEventListener("contextmenu",this.handleEvent)}destroy(){this.element.removeEventListener("contextmenu",this.handleEvent)}enableEventType(a,b){a===cy&&(this.options.enable=b)}handleEvent(a){this.options.enable&&this.callback({type:cy,center:{x:a.clientX,y:a.clientY},srcEvent:a,pointerType:"mouse",target:a.target})}}const cA={pointerdown:1,pointermove:2,pointerup:4,mousedown:1,mousemove:2,mouseup:4},cB={srcElement:"root",priority:0};class cC{constructor(a){this.eventManager=a,this.handlers=[],this.handlersByElement=new Map,this.handleEvent=this.handleEvent.bind(this),this._active=!1}isEmpty(){return!this._active}add(f,g,a,h=!1,i=!1){const{handlers:j,handlersByElement:e}=this;a&&("object"!=typeof a||a.addEventListener)&&(a={srcElement:a}),a=a?Object.assign({},cB,a):cB;let b=e.get(a.srcElement);b||(b=[],e.set(a.srcElement,b));const c={type:f,handler:g,srcElement:a.srcElement,priority:a.priority};h&&(c.once=!0),i&&(c.passive=!0),j.push(c),this._active=this._active||!c.passive;let d=b.length-1;for(;d>=0&&!(b[d].priority>=c.priority);)d--;b.splice(d+1,0,c)}remove(f,g){const{handlers:b,handlersByElement:e}=this;for(let c=b.length-1;c>=0;c--){const a=b[c];if(a.type===f&&a.handler===g){b.splice(c,1);const d=e.get(a.srcElement);d.splice(d.indexOf(a),1),0===d.length&&e.delete(a.srcElement)}}this._active=b.some(a=>!a.passive)}handleEvent(c){if(this.isEmpty())return;const b=this._normalizeEvent(c);let a=c.srcEvent.target;for(;a&&a!==b.rootElement;){if(this._emit(b,a),b.handled)return;a=a.parentNode}this._emit(b,"root")}_emit(e,f){const a=this.handlersByElement.get(f);if(a){let g=!1;const h=()=>{e.handled=!0},i=()=>{e.handled=!0,g=!0},c=[];for(let b=0;b{const b=this.manager.get(a);b&&ce[a].forEach(a=>{b.recognizeWith(a)})}),b.recognizerOptions){const e=this.manager.get(d);if(e){const f=b.recognizerOptions[d];delete f.enable,e.set(f)}}for(const[h,c]of(this.wheelInput=new cn(a,this._onOtherEvent,{enable:!1}),this.moveInput=new ct(a,this._onOtherEvent,{enable:!1}),this.keyInput=new cx(a,this._onOtherEvent,{enable:!1,tabIndex:b.tabIndex}),this.contextmenuInput=new cz(a,this._onOtherEvent,{enable:!1}),this.events))c.isEmpty()||(this._toggleRecognizer(c.recognizerName,!0),this.manager.on(h,c.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(a,b,c){this._addEventHandler(a,b,c,!1)}once(a,b,c){this._addEventHandler(a,b,c,!0)}watch(a,b,c){this._addEventHandler(a,b,c,!1,!0)}off(a,b){this._removeEventHandler(a,b)}_toggleRecognizer(a,b){const{manager:d}=this;if(!d)return;const c=d.get(a);if(c&&c.options.enable!==b){c.set({enable:b});const e=cf[a];e&&!this.options.recognizers&&e.forEach(e=>{const f=d.get(e);b?(f.requireFailure(a),c.dropRequireFailure(e)):f.dropRequireFailure(a)})}this.wheelInput.enableEventType(a,b),this.moveInput.enableEventType(a,b),this.keyInput.enableEventType(a,b),this.contextmenuInput.enableEventType(a,b)}_addEventHandler(b,e,d,f,g){if("string"!=typeof b){for(const h in d=e,b)this._addEventHandler(h,b[h],d,f,g);return}const{manager:i,events:j}=this,c=ci[b]||b;let a=j.get(c);!a&&(a=new cC(this),j.set(c,a),a.recognizerName=ch[c]||c,i&&i.on(c,a.handleEvent)),a.add(b,e,d,f,g),a.isEmpty()||this._toggleRecognizer(a.recognizerName,!0)}_removeEventHandler(a,h){if("string"!=typeof a){for(const c in a)this._removeEventHandler(c,a[c]);return}const{events:d}=this,i=ci[a]||a,b=d.get(i);if(b&&(b.remove(a,h),b.isEmpty())){const{recognizerName:e}=b;let f=!1;for(const g of d.values())if(g.recognizerName===e&&!g.isEmpty()){f=!0;break}f||this._toggleRecognizer(e,!1)}}_onBasicInput(a){const{srcEvent:c}=a,b=cg[c.type];b&&this.manager.emit(b,a)}_onOtherEvent(a){this.manager.emit(a.type,a)}}function cE(c,d){var a=Object.keys(c);if(Object.getOwnPropertySymbols){var b=Object.getOwnPropertySymbols(c);d&&(b=b.filter(function(a){return Object.getOwnPropertyDescriptor(c,a).enumerable})),a.push.apply(a,b)}return a}function cF(c){for(var a=1;a0),e=d&&!this.state.isHovering,h=!d&&this.state.isHovering;(c||e)&&(a.features=b,c&&c(a)),e&&cO.call(this,"onMouseEnter",a),h&&cO.call(this,"onMouseLeave",a),(e||h)&&this.setState({isHovering:d})}}function cS(b){var c=this.props,d=c.onClick,f=c.onNativeClick,g=c.onDblClick,h=c.doubleClickZoom,a=[],e=g||h;switch(b.type){case"anyclick":a.push(f),e||a.push(d);break;case"click":e&&a.push(d);break;default:}(a=a.filter(Boolean)).length&&((b=cM.call(this,b)).features=cN.call(this,b.point),a.forEach(function(a){return a(b)}))}var m=(0,c.forwardRef)(function(b,h){var i,t,f=(0,c.useContext)(bJ),u=(0,c.useMemo)(function(){return b.controller||new Z},[]),v=(0,c.useMemo)(function(){return new cD(null,{touchAction:b.touchAction,recognizerOptions:b.eventRecognizerOptions})},[]),g=(0,c.useRef)(null),e=(0,c.useRef)(null),a=(0,c.useRef)({width:0,height:0,state:{isHovering:!1,isDragging:!1}}).current;a.props=b,a.map=e.current&&e.current.getMap(),a.setState=function(c){a.state=cL(cL({},a.state),c),g.current.style.cursor=b.getCursor(a.state)};var j=!0,k=function(b,c,d){if(j){i=[b,c,d];return}var e=a.props,f=e.onViewStateChange,g=e.onViewportChange;Object.defineProperty(b,"position",{get:function(){return[0,0,bL(a.map,b)]}}),f&&f({viewState:b,interactionState:c,oldViewState:d}),g&&g(b,c,d)};(0,c.useImperativeHandle)(h,function(){var a;return{getMap:(a=e).current&&a.current.getMap,queryRenderedFeatures:a.current&&a.current.queryRenderedFeatures}},[]);var d=(0,c.useMemo)(function(){return cL(cL({},f),{},{eventManager:v,container:f.container||g.current})},[f,g.current]);d.onViewportChange=k,d.viewport=f.viewport||bP(a),a.viewport=d.viewport;var w=function(b){var c=b.isDragging,d=void 0!==c&&c;if(d!==a.state.isDragging&&a.setState({isDragging:d}),j){t=b;return}var e=a.props.onInteractionStateChange;e&&e(b)},l=function(){a.width&&a.height&&u.setOptions(cL(cL(cL({},a.props),a.props.viewState),{},{isInteractive:Boolean(a.props.onViewStateChange||a.props.onViewportChange),onViewportChange:k,onStateChange:w,eventManager:v,width:a.width,height:a.height}))},m=function(b){var c=b.width,d=b.height;a.width=c,a.height=d,l(),a.props.onResize({width:c,height:d})};(0,c.useEffect)(function(){return v.setElement(g.current),v.on({pointerdown:cP.bind(a),pointermove:cR.bind(a),pointerup:cQ.bind(a),pointerleave:cO.bind(a,"onMouseOut"),click:cS.bind(a),anyclick:cS.bind(a),dblclick:cO.bind(a,"onDblClick"),wheel:cO.bind(a,"onWheel"),contextmenu:cO.bind(a,"onContextMenu")}),function(){v.destroy()}},[]),bK(function(){if(i){var a;k.apply(void 0,function(a){if(Array.isArray(a))return ax(a)}(a=i)||function(a){if("undefined"!=typeof Symbol&&null!=a[Symbol.iterator]||null!=a["@@iterator"])return Array.from(a)}(a)||ay(a)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}())}t&&w(t)}),l();var n=b.width,o=b.height,p=b.style,r=b.getCursor,s=(0,c.useMemo)(function(){return cL(cL({position:"relative"},p),{},{width:n,height:o,cursor:r(a.state)})},[p,n,o,r,a.state]);return i&&a._child||(a._child=c.createElement(bI,{value:d},c.createElement("div",{key:"event-canvas",ref:g,style:s},c.createElement(q,aw({},b,{width:"100%",height:"100%",style:null,onResize:m,ref:e}))))),j=!1,a._child});m.supported=q.supported,m.propTypes=$,m.defaultProps=_;var cT=m;function cU(b,a){if(b===a)return!0;if(!b||!a)return!1;if(Array.isArray(b)){if(!Array.isArray(a)||b.length!==a.length)return!1;for(var c=0;c prop: ".concat(e))}}(d,a,f.current):d=function(a,c,d){if(a.style&&a.style._loaded){var b=function(c){for(var a=1;a=0||(d[a]=c[a]);return d}(a,d);if(Object.getOwnPropertySymbols){var f=Object.getOwnPropertySymbols(a);for(c=0;c=0)&&Object.prototype.propertyIsEnumerable.call(a,b)&&(e[b]=a[b])}return e}(d,["layout","paint","filter","minzoom","maxzoom","beforeId"]);if(p!==a.beforeId&&b.moveLayer(c,p),e!==a.layout){var q=a.layout||{};for(var g in e)cU(e[g],q[g])||b.setLayoutProperty(c,g,e[g]);for(var r in q)e.hasOwnProperty(r)||b.setLayoutProperty(c,r,void 0)}if(f!==a.paint){var s=a.paint||{};for(var h in f)cU(f[h],s[h])||b.setPaintProperty(c,h,f[h]);for(var t in s)f.hasOwnProperty(t)||b.setPaintProperty(c,t,void 0)}for(var i in cU(m,a.filter)||b.setFilter(c,m),(n!==a.minzoom||o!==a.maxzoom)&&b.setLayerZoomRange(c,n,o),j)cU(j[i],a[i])||b.setLayerProperty(c,i,j[i])}(c,d,a,b)}catch(e){console.warn(e)}}(a,d,b,e.current):function(a,d,b){if(a.style&&a.style._loaded){var c=cY(cY({},b),{},{id:d});delete c.beforeId,a.addLayer(c,b.beforeId)}}(a,d,b),e.current=b,null}).propTypes=ab;var f={captureScroll:!1,captureDrag:!0,captureClick:!0,captureDoubleClick:!0,capturePointerMove:!1},d={captureScroll:a.bool,captureDrag:a.bool,captureClick:a.bool,captureDoubleClick:a.bool,capturePointerMove:a.bool};function c$(){var d=arguments.length>0&& void 0!==arguments[0]?arguments[0]:{},a=(0,c.useContext)(bJ),e=(0,c.useRef)(null),f=(0,c.useRef)({props:d,state:{},context:a,containerRef:e}),b=f.current;return b.props=d,b.context=a,(0,c.useEffect)(function(){return function(a){var b=a.containerRef.current,c=a.context.eventManager;if(b&&c){var d={wheel:function(c){var b=a.props;b.captureScroll&&c.stopPropagation(),b.onScroll&&b.onScroll(c,a)},panstart:function(c){var b=a.props;b.captureDrag&&c.stopPropagation(),b.onDragStart&&b.onDragStart(c,a)},anyclick:function(c){var b=a.props;b.captureClick&&c.stopPropagation(),b.onNativeClick&&b.onNativeClick(c,a)},click:function(c){var b=a.props;b.captureClick&&c.stopPropagation(),b.onClick&&b.onClick(c,a)},dblclick:function(c){var b=a.props;b.captureDoubleClick&&c.stopPropagation(),b.onDoubleClick&&b.onDoubleClick(c,a)},pointermove:function(c){var b=a.props;b.capturePointerMove&&c.stopPropagation(),b.onPointerMove&&b.onPointerMove(c,a)}};return c.watch(d,b),function(){c.off(d)}}}(b)},[a.eventManager]),b}function c_(b){var a=b.instance,c=c$(b),d=c.context,e=c.containerRef;return a._context=d,a._containerRef=e,a._render()}var H=function(b){bV(a,b);var d,e,f=(d=a,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(a){return!1}}(),function(){var a,b=bY(d);if(e){var c=bY(this).constructor;a=Reflect.construct(b,arguments,c)}else a=b.apply(this,arguments);return bX(this,a)});function a(){var b;bk(this,a);for(var e=arguments.length,h=new Array(e),d=0;d2&& void 0!==arguments[2]?arguments[2]:"x";if(null===a)return b;var c="x"===d?a.offsetWidth:a.offsetHeight;return c6(b/100*c)/c*100};function c8(c,d){var a=Object.keys(c);if(Object.getOwnPropertySymbols){var b=Object.getOwnPropertySymbols(c);d&&(b=b.filter(function(a){return Object.getOwnPropertyDescriptor(c,a).enumerable})),a.push.apply(a,b)}return a}var ae=Object.assign({},ac,{className:a.string,longitude:a.number.isRequired,latitude:a.number.isRequired,style:a.object}),af=Object.assign({},ad,{className:""});function t(b){var d,j,e,k,f,l,m,a,h=(d=b,e=(j=aA((0,c.useState)(null),2))[0],k=j[1],f=aA((0,c.useState)(null),2),l=f[0],m=f[1],a=c$(c1(c1({},d),{},{onDragStart:c4})),a.callbacks=d,a.state.dragPos=e,a.state.setDragPos=k,a.state.dragOffset=l,a.state.setDragOffset=m,(0,c.useEffect)(function(){return function(a){var b=a.context.eventManager;if(b&&a.state.dragPos){var c={panmove:function(b){return function(b,a){var h=a.props,c=a.callbacks,d=a.state,i=a.context;b.stopPropagation();var e=c2(b);d.setDragPos(e);var f=d.dragOffset;if(c.onDrag&&f){var g=Object.assign({},b);g.lngLat=c3(e,f,h,i),c.onDrag(g)}}(b,a)},panend:function(b){return function(c,a){var h=a.props,d=a.callbacks,b=a.state,i=a.context;c.stopPropagation();var e=b.dragPos,f=b.dragOffset;if(b.setDragPos(null),b.setDragOffset(null),d.onDragEnd&&e&&f){var g=Object.assign({},c);g.lngLat=c3(e,f,h,i),d.onDragEnd(g)}}(b,a)},pancancel:function(d){var c,b;return c=d,b=a.state,void(c.stopPropagation(),b.setDragPos(null),b.setDragOffset(null))}};return b.watch(c),function(){b.off(c)}}}(a)},[a.context.eventManager,Boolean(e)]),a),o=h.state,p=h.containerRef,q=b.children,r=b.className,s=b.draggable,A=b.style,t=o.dragPos,u=function(b){var a=b.props,e=b.state,f=b.context,g=a.longitude,h=a.latitude,j=a.offsetLeft,k=a.offsetTop,c=e.dragPos,d=e.dragOffset,l=f.viewport,m=f.map;if(c&&d)return[c[0]+d[0],c[1]+d[1]];var n=bL(m,{longitude:g,latitude:h}),i=aA(l.project([g,h,n]),2),o=i[0],p=i[1];return[o+=j,p+=k]}(h),n=aA(u,2),v=n[0],w=n[1],x="translate(".concat(c6(v),"px, ").concat(c6(w),"px)"),y=s?t?"grabbing":"grab":"auto",z=(0,c.useMemo)(function(){var a=function(c){for(var a=1;a0){var t=b,u=e;for(b=0;b<=1;b+=.5)k=(i=n-b*h)+h,e=Math.max(0,d-i)+Math.max(0,k-p+d),e0){var w=a,x=f;for(a=0;a<=1;a+=v)l=(j=m-a*g)+g,f=Math.max(0,d-j)+Math.max(0,l-o+d),f1||h< -1||f<0||f>p.width||g<0||g>p.height?i.display="none":i.zIndex=Math.floor((1-h)/2*1e5)),i),S=(0,c.useCallback)(function(b){t.props.onClose();var a=t.context.eventManager;a&&a.once("click",function(a){return a.stopPropagation()},b.target)},[]);return c.createElement("div",{className:"mapboxgl-popup mapboxgl-popup-anchor-".concat(L," ").concat(N),style:R,ref:u},c.createElement("div",{key:"tip",className:"mapboxgl-popup-tip",style:{borderWidth:O}}),c.createElement("div",{key:"content",ref:j,className:"mapboxgl-popup-content"},P&&c.createElement("button",{key:"close-button",className:"mapboxgl-popup-close-button",type:"button",onClick:S},"\xd7"),Q))}function da(c,d){var a=Object.keys(c);if(Object.getOwnPropertySymbols){var b=Object.getOwnPropertySymbols(c);d&&(b=b.filter(function(a){return Object.getOwnPropertyDescriptor(c,a).enumerable})),a.push.apply(a,b)}return a}u.propTypes=ag,u.defaultProps=ah,c.memo(u);var ai=Object.assign({},d,{toggleLabel:a.string,className:a.string,style:a.object,compact:a.bool,customAttribution:a.oneOfType([a.string,a.arrayOf(a.string)])}),aj=Object.assign({},f,{className:"",toggleLabel:"Toggle Attribution"});function v(a){var b=c$(a),d=b.context,i=b.containerRef,j=(0,c.useRef)(null),e=aA((0,c.useState)(!1),2),f=e[0],m=e[1];(0,c.useEffect)(function(){var h,e,c,f,g,b;return d.map&&(h=(e={customAttribution:a.customAttribution},c=d.map,f=i.current,g=j.current,(b=new(A()).AttributionControl(e))._map=c,b._container=f,b._innerContainer=g,b._updateAttributions(),b._updateEditLink(),c.on("styledata",b._updateData),c.on("sourcedata",b._updateData),b)),function(){var a;return h&&void((a=h)._map.off("styledata",a._updateData),a._map.off("sourcedata",a._updateData))}},[d.map]);var h=void 0===a.compact?d.viewport.width<=640:a.compact;(0,c.useEffect)(function(){!h&&f&&m(!1)},[h]);var k=(0,c.useCallback)(function(){return m(function(a){return!a})},[]),l=(0,c.useMemo)(function(){return function(c){for(var a=1;ac)return 1}return 0}(b.map.version,"1.6.0")>=0?2:1:2},[b.map]),f=b.viewport.bearing,d={transform:"rotate(".concat(-f,"deg)")},2===e?c.createElement("span",{className:"mapboxgl-ctrl-icon","aria-hidden":"true",style:d}):c.createElement("span",{className:"mapboxgl-ctrl-compass-arrow",style:d})))))}function di(c,d){var a=Object.keys(c);if(Object.getOwnPropertySymbols){var b=Object.getOwnPropertySymbols(c);d&&(b=b.filter(function(a){return Object.getOwnPropertyDescriptor(c,a).enumerable})),a.push.apply(a,b)}return a}y.propTypes=ao,y.defaultProps=ap,c.memo(y);var aq=Object.assign({},d,{className:a.string,style:a.object,maxWidth:a.number,unit:a.oneOf(["imperial","metric","nautical"])}),ar=Object.assign({},f,{className:"",maxWidth:100,unit:"metric"});function z(a){var d=c$(a),f=d.context,h=d.containerRef,e=aA((0,c.useState)(null),2),b=e[0],j=e[1];(0,c.useEffect)(function(){if(f.map){var a=new(A()).ScaleControl;a._map=f.map,a._container=h.current,j(a)}},[f.map]),b&&(b.options=a,b._onMove());var i=(0,c.useMemo)(function(){return function(c){for(var a=1;a\s*\(/gm,"{anonymous}()@"):"Unknown Stack Trace",b=g.console&&(g.console.warn||g.console.log);return b&&b.call(g.console,d,e),c.apply(this,arguments)}}m="function"!=typeof Object.assign?function(b){if(b===l||null===b)throw new TypeError("Cannot convert undefined or null to object");for(var e=Object(b),c=1;c -1}function _(a){return a.trim().split(/\s+/g)}function aa(a,d,c){if(a.indexOf&&!c)return a.indexOf(d);for(var b=0;baa(e,f)&&b.push(c[a]),e[a]=f,a++}return g&&(b=d?b.sort(function(a,b){return a[d]>b[d]}):b.sort()),b}function n(e,a){for(var c,d,f=a[0].toUpperCase()+a.slice(1),b=0;b1&&!b.firstMultiple?b.firstMultiple=an(a):1===h&&(b.firstMultiple=!1);var i=b.firstInput,c=b.firstMultiple,j=c?c.center:i.center,k=a.center=ao(e);a.timeStamp=U(),a.deltaTime=a.timeStamp-i.timeStamp,a.angle=as(j,k),a.distance=ar(j,k),al(b,a),a.offsetDirection=aq(a.deltaX,a.deltaY);var d=ap(a.deltaTime,a.deltaX,a.deltaY);a.overallVelocityX=d.x,a.overallVelocityY=d.y,a.overallVelocity=T(d.x)>T(d.y)?d.x:d.y,a.scale=c?au(c.pointers,e):1,a.rotation=c?at(c.pointers,e):0,a.maxPointers=b.prevInput?a.pointers.length>b.prevInput.maxPointers?a.pointers.length:b.prevInput.maxPointers:a.pointers.length,am(b,a);var f=g.element;Z(a.srcEvent.target,f)&&(f=a.srcEvent.target),a.target=f}function al(a,b){var c=b.center,d=a.offsetDelta||{},e=a.prevDelta||{},f=a.prevInput||{};(1===b.eventType||4===f.eventType)&&(e=a.prevDelta={x:f.deltaX||0,y:f.deltaY||0},d=a.offsetDelta={x:c.x,y:c.y}),b.deltaX=e.x+(c.x-d.x),b.deltaY=e.y+(c.y-d.y)}function am(h,a){var d,e,f,g,b=h.lastInterval||a,i=a.timeStamp-b.timeStamp;if(8!=a.eventType&&(i>25||l===b.velocity)){var j=a.deltaX-b.deltaX,k=a.deltaY-b.deltaY,c=ap(i,j,k);e=c.x,f=c.y,d=T(c.x)>T(c.y)?c.x:c.y,g=aq(j,k),h.lastInterval=a}else d=b.velocity,e=b.velocityX,f=b.velocityY,g=b.direction;a.velocity=d,a.velocityX=e,a.velocityY=f,a.direction=g}function an(a){for(var c=[],b=0;b=T(b)?a<0?2:4:b<0?8:16}function ar(b,c,a){a||(a=ah);var d=c[a[0]]-b[a[0]],e=c[a[1]]-b[a[1]];return Math.sqrt(d*d+e*e)}function as(b,c,a){a||(a=ah);var d=c[a[0]]-b[a[0]],e=c[a[1]]-b[a[1]];return 180*Math.atan2(e,d)/Math.PI}function at(a,b){return as(b[1],b[0],ai)+as(a[1],a[0],ai)}function au(a,b){return ar(b[0],b[1],ai)/ar(a[0],a[1],ai)}f.prototype={handler:function(){},init:function(){this.evEl&&H(this.element,this.evEl,this.domHandler),this.evTarget&&H(this.target,this.evTarget,this.domHandler),this.evWin&&H(ae(this.element),this.evWin,this.domHandler)},destroy:function(){this.evEl&&I(this.element,this.evEl,this.domHandler),this.evTarget&&I(this.target,this.evTarget,this.domHandler),this.evWin&&I(ae(this.element),this.evWin,this.domHandler)}};var av={mousedown:1,mousemove:2,mouseup:4};function u(){this.evEl="mousedown",this.evWin="mousemove mouseup",this.pressed=!1,f.apply(this,arguments)}e(u,f,{handler:function(a){var b=av[a.type];1&b&&0===a.button&&(this.pressed=!0),2&b&&1!==a.which&&(b=4),this.pressed&&(4&b&&(this.pressed=!1),this.callback(this.manager,b,{pointers:[a],changedPointers:[a],pointerType:L,srcEvent:a}))}});var aw={pointerdown:1,pointermove:2,pointerup:4,pointercancel:8,pointerout:8},ax={2:K,3:"pen",4:L,5:"kinect"},M="pointerdown",N="pointermove pointerup pointercancel";function v(){this.evEl=M,this.evWin=N,f.apply(this,arguments),this.store=this.manager.session.pointerEvents=[]}g.MSPointerEvent&&!g.PointerEvent&&(M="MSPointerDown",N="MSPointerMove MSPointerUp MSPointerCancel"),e(v,f,{handler:function(a){var b=this.store,e=!1,d=aw[a.type.toLowerCase().replace("ms","")],f=ax[a.pointerType]||a.pointerType,c=aa(b,a.pointerId,"pointerId");1&d&&(0===a.button||f==K)?c<0&&(b.push(a),c=b.length-1):12&d&&(e=!0),!(c<0)&&(b[c]=a,this.callback(this.manager,d,{pointers:b,changedPointers:[a],pointerType:f,srcEvent:a}),e&&b.splice(c,1))}});var ay={touchstart:1,touchmove:2,touchend:4,touchcancel:8};function w(){this.evTarget="touchstart",this.evWin="touchstart touchmove touchend touchcancel",this.started=!1,f.apply(this,arguments)}function az(b,d){var a=ab(b.touches),c=ab(b.changedTouches);return 12&d&&(a=ac(a.concat(c),"identifier",!0)),[a,c]}e(w,f,{handler:function(c){var a=ay[c.type];if(1===a&&(this.started=!0),this.started){var b=az.call(this,c,a);12&a&&b[0].length-b[1].length==0&&(this.started=!1),this.callback(this.manager,a,{pointers:b[0],changedPointers:b[1],pointerType:K,srcEvent:c})}}});var aA={touchstart:1,touchmove:2,touchend:4,touchcancel:8};function x(){this.evTarget="touchstart touchmove touchend touchcancel",this.targetIds={},f.apply(this,arguments)}function aB(h,g){var b=ab(h.touches),c=this.targetIds;if(3&g&&1===b.length)return c[b[0].identifier]=!0,[b,b];var a,d,e=ab(h.changedTouches),f=[],i=this.target;if(d=b.filter(function(a){return Z(a.target,i)}),1===g)for(a=0;a -1&&d.splice(a,1)},2500)}}function aE(b){for(var d=b.srcEvent.clientX,e=b.srcEvent.clientY,a=0;a -1&&this.requireFail.splice(b,1),this},hasRequireFailures:function(){return this.requireFail.length>0},canRecognizeWith:function(a){return!!this.simultaneous[a.id]},emit:function(d){var c=this,a=this.state;function b(a){c.manager.emit(a,d)}a<8&&b(c.options.event+aM(a)),b(c.options.event),d.additionalEvent&&b(d.additionalEvent),a>=8&&b(c.options.event+aM(a))},tryEmit:function(a){if(this.canEmit())return this.emit(a);this.state=32},canEmit:function(){for(var a=0;ac.threshold&&b&c.direction},attrTest:function(a){return h.prototype.attrTest.call(this,a)&&(2&this.state|| !(2&this.state)&&this.directionTest(a))},emit:function(a){this.pX=a.deltaX,this.pY=a.deltaY;var b=aN(a.direction);b&&(a.additionalEvent=this.options.event+b),this._super.emit.call(this,a)}}),e(p,h,{defaults:{event:"pinch",threshold:0,pointers:2},getTouchAction:function(){return[aI]},attrTest:function(a){return this._super.attrTest.call(this,a)&&(Math.abs(a.scale-1)>this.options.threshold||2&this.state)},emit:function(a){if(1!==a.scale){var b=a.scale<1?"in":"out";a.additionalEvent=this.options.event+b}this._super.emit.call(this,a)}}),e(q,i,{defaults:{event:"press",pointers:1,time:251,threshold:9},getTouchAction:function(){return[aG]},process:function(a){var b=this.options,c=a.pointers.length===b.pointers,d=a.distanceb.time;if(this._input=a,d&&c&&(!(12&a.eventType)||e)){if(1&a.eventType)this.reset(),this._timer=V(function(){this.state=8,this.tryEmit()},b.time,this);else if(4&a.eventType)return 8}else this.reset();return 32},reset:function(){clearTimeout(this._timer)},emit:function(a){8===this.state&&(a&&4&a.eventType?this.manager.emit(this.options.event+"up",a):(this._input.timeStamp=U(),this.manager.emit(this.options.event,this._input)))}}),e(r,h,{defaults:{event:"rotate",threshold:0,pointers:2},getTouchAction:function(){return[aI]},attrTest:function(a){return this._super.attrTest.call(this,a)&&(Math.abs(a.rotation)>this.options.threshold||2&this.state)}}),e(s,h,{defaults:{event:"swipe",threshold:10,velocity:.3,direction:30,pointers:1},getTouchAction:function(){return o.prototype.getTouchAction.call(this)},attrTest:function(a){var b,c=this.options.direction;return 30&c?b=a.overallVelocity:6&c?b=a.overallVelocityX:24&c&&(b=a.overallVelocityY),this._super.attrTest.call(this,a)&&c&a.offsetDirection&&a.distance>this.options.threshold&&a.maxPointers==this.options.pointers&&T(b)>this.options.velocity&&4&a.eventType},emit:function(a){var b=aN(a.offsetDirection);b&&this.manager.emit(this.options.event+b,a),this.manager.emit(this.options.event,a)}}),e(j,i,{defaults:{event:"tap",pointers:1,taps:1,interval:300,time:250,threshold:9,posThreshold:10},getTouchAction:function(){return[aH]},process:function(a){var b=this.options,c=a.pointers.length===b.pointers,d=a.distance1)for(var a=1;ac.length)&&(a=c.length);for(var b=0,d=new Array(a);bc?c:a}Math.hypot||(Math.hypot=function(){for(var b=0,a=arguments.length;a--;)b+=arguments[a]*arguments[a];return Math.sqrt(b)}),bc=new h(4),h!=Float32Array&&(bc[0]=0,bc[1]=0,bc[2]=0,bc[3]=0);const aF=Math.log2||function(a){return Math.log(a)*Math.LOG2E};function aG(e,f,g){var h=f[0],i=f[1],j=f[2],k=f[3],l=f[4],m=f[5],n=f[6],o=f[7],p=f[8],q=f[9],r=f[10],s=f[11],t=f[12],u=f[13],v=f[14],w=f[15],a=g[0],b=g[1],c=g[2],d=g[3];return e[0]=a*h+b*l+c*p+d*t,e[1]=a*i+b*m+c*q+d*u,e[2]=a*j+b*n+c*r+d*v,e[3]=a*k+b*o+c*s+d*w,a=g[4],b=g[5],c=g[6],d=g[7],e[4]=a*h+b*l+c*p+d*t,e[5]=a*i+b*m+c*q+d*u,e[6]=a*j+b*n+c*r+d*v,e[7]=a*k+b*o+c*s+d*w,a=g[8],b=g[9],c=g[10],d=g[11],e[8]=a*h+b*l+c*p+d*t,e[9]=a*i+b*m+c*q+d*u,e[10]=a*j+b*n+c*r+d*v,e[11]=a*k+b*o+c*s+d*w,a=g[12],b=g[13],c=g[14],d=g[15],e[12]=a*h+b*l+c*p+d*t,e[13]=a*i+b*m+c*q+d*u,e[14]=a*j+b*n+c*r+d*v,e[15]=a*k+b*o+c*s+d*w,e}function aH(b,a,f){var g,h,i,j,k,l,m,n,o,p,q,r,c=f[0],d=f[1],e=f[2];return a===b?(b[12]=a[0]*c+a[4]*d+a[8]*e+a[12],b[13]=a[1]*c+a[5]*d+a[9]*e+a[13],b[14]=a[2]*c+a[6]*d+a[10]*e+a[14],b[15]=a[3]*c+a[7]*d+a[11]*e+a[15]):(g=a[0],h=a[1],i=a[2],j=a[3],k=a[4],l=a[5],m=a[6],n=a[7],o=a[8],p=a[9],q=a[10],r=a[11],b[0]=g,b[1]=h,b[2]=i,b[3]=j,b[4]=k,b[5]=l,b[6]=m,b[7]=n,b[8]=o,b[9]=p,b[10]=q,b[11]=r,b[12]=g*c+k*d+o*e+a[12],b[13]=h*c+l*d+p*e+a[13],b[14]=i*c+m*d+q*e+a[14],b[15]=j*c+n*d+r*e+a[15]),b}function aI(a,b,f){var c=f[0],d=f[1],e=f[2];return a[0]=b[0]*c,a[1]=b[1]*c,a[2]=b[2]*c,a[3]=b[3]*c,a[4]=b[4]*d,a[5]=b[5]*d,a[6]=b[6]*d,a[7]=b[7]*d,a[8]=b[8]*e,a[9]=b[9]*e,a[10]=b[10]*e,a[11]=b[11]*e,a[12]=b[12],a[13]=b[13],a[14]=b[14],a[15]=b[15],a}function aJ(a,b){var c=a[0],d=a[1],e=a[2],f=a[3],g=a[4],h=a[5],i=a[6],j=a[7],k=a[8],l=a[9],m=a[10],n=a[11],o=a[12],p=a[13],q=a[14],r=a[15],s=b[0],t=b[1],u=b[2],v=b[3],w=b[4],x=b[5],y=b[6],z=b[7],A=b[8],B=b[9],C=b[10],D=b[11],E=b[12],F=b[13],G=b[14],H=b[15];return Math.abs(c-s)<=1e-6*Math.max(1,Math.abs(c),Math.abs(s))&&Math.abs(d-t)<=1e-6*Math.max(1,Math.abs(d),Math.abs(t))&&Math.abs(e-u)<=1e-6*Math.max(1,Math.abs(e),Math.abs(u))&&Math.abs(f-v)<=1e-6*Math.max(1,Math.abs(f),Math.abs(v))&&Math.abs(g-w)<=1e-6*Math.max(1,Math.abs(g),Math.abs(w))&&Math.abs(h-x)<=1e-6*Math.max(1,Math.abs(h),Math.abs(x))&&Math.abs(i-y)<=1e-6*Math.max(1,Math.abs(i),Math.abs(y))&&Math.abs(j-z)<=1e-6*Math.max(1,Math.abs(j),Math.abs(z))&&Math.abs(k-A)<=1e-6*Math.max(1,Math.abs(k),Math.abs(A))&&Math.abs(l-B)<=1e-6*Math.max(1,Math.abs(l),Math.abs(B))&&Math.abs(m-C)<=1e-6*Math.max(1,Math.abs(m),Math.abs(C))&&Math.abs(n-D)<=1e-6*Math.max(1,Math.abs(n),Math.abs(D))&&Math.abs(o-E)<=1e-6*Math.max(1,Math.abs(o),Math.abs(E))&&Math.abs(p-F)<=1e-6*Math.max(1,Math.abs(p),Math.abs(F))&&Math.abs(q-G)<=1e-6*Math.max(1,Math.abs(q),Math.abs(G))&&Math.abs(r-H)<=1e-6*Math.max(1,Math.abs(r),Math.abs(H))}function aK(a,b,c){return a[0]=b[0]+c[0],a[1]=b[1]+c[1],a}function aL(a,b,c,d){var e=b[0],f=b[1];return a[0]=e+d*(c[0]-e),a[1]=f+d*(c[1]-f),a}function aM(a,b){if(!a)throw new Error(b||"@math.gl/web-mercator: assertion failed.")}bd=new h(2),h!=Float32Array&&(bd[0]=0,bd[1]=0),be=new h(3),h!=Float32Array&&(be[0]=0,be[1]=0,be[2]=0);const n=Math.PI,aN=n/4,aO=n/180,aP=180/n;function aQ(a){return Math.pow(2,a)}function aR([b,a]){return aM(Number.isFinite(b)),aM(Number.isFinite(a)&&a>= -90&&a<=90,"invalid latitude"),[512*(b*aO+n)/(2*n),512*(n+Math.log(Math.tan(aN+.5*(a*aO))))/(2*n)]}function aS([a,b]){return[(a/512*(2*n)-n)*aP,2*(Math.atan(Math.exp(b/512*(2*n)-n))-aN)*aP]}function aT(a){return 2*Math.atan(.5/a)*aP}function aU(a){return .5/Math.tan(.5*a*aO)}function aV(i,c,j=0){const[a,b,e]=i;if(aM(Number.isFinite(a)&&Number.isFinite(b),"invalid pixel coordinate"),Number.isFinite(e)){const k=aC(c,[a,b,e,1]);return k}const f=aC(c,[a,b,0,1]),g=aC(c,[a,b,1,1]),d=f[2],h=g[2];return aL([],f,g,d===h?0:((j||0)-d)/(h-d))}const aW=Math.PI/180;function aX(a,c,d){const{pixelUnprojectionMatrix:e}=a,b=aC(e,[c,0,1,1]),f=aC(e,[c,a.height,1,1]),h=d*a.distanceScales.unitsPerMeter[2],i=(h-b[2])/(f[2]-b[2]),j=aL([],b,f,i),g=aS(j);return g[2]=d,g}class aY{constructor({width:f,height:c,latitude:l=0,longitude:m=0,zoom:p=0,pitch:n=0,bearing:q=0,altitude:a=null,fovy:b=null,position:o=null,nearZMultiplier:t=.02,farZMultiplier:u=1.01}={width:1,height:1}){f=f||1,c=c||1,null===b&&null===a?b=aT(a=1.5):null===b?b=aT(a):null===a&&(a=aU(b));const r=aQ(p);a=Math.max(.75,a);const s=function({latitude:c,longitude:i,highPrecision:j=!1}){aM(Number.isFinite(c)&&Number.isFinite(i));const b={},d=Math.cos(c*aO),e=1.4222222222222223/d,a=12790407194604047e-21/d;if(b.unitsPerMeter=[a,a,a],b.metersPerUnit=[1/a,1/a,1/a],b.unitsPerDegree=[1.4222222222222223,e,a],b.degreesPerUnit=[.703125,1/e,1/a],j){const f=aO*Math.tan(c*aO)/d,k=1.4222222222222223*f/2,g=12790407194604047e-21*f,h=g/e*a;b.unitsPerDegree2=[0,k,g],b.unitsPerMeter2=[h,0,h]}return b}({longitude:m,latitude:l}),d=aR([m,l]);if(d[2]=0,o){var e,g,h,i,j,k;i=d,j=d,k=(e=[],g=o,h=s.unitsPerMeter,e[0]=g[0]*h[0],e[1]=g[1]*h[1],e[2]=g[2]*h[2],e),i[0]=j[0]+k[0],i[1]=j[1]+k[1],i[2]=j[2]+k[2]}this.projectionMatrix=function({width:h,height:i,pitch:j,altitude:k,fovy:l,nearZMultiplier:m,farZMultiplier:n}){var a,f,g,c,b,d,e;const{fov:o,aspect:p,near:q,far:r}=function({width:f,height:g,fovy:a=aT(1.5),altitude:d,pitch:h=0,nearZMultiplier:i=1,farZMultiplier:j=1}){void 0!==d&&(a=aT(d));const b=.5*a*aO,c=aU(a),e=h*aO;return{fov:2*b,aspect:f/g,focalDistance:c,near:i,far:(Math.sin(e)*(Math.sin(b)*c/Math.sin(Math.min(Math.max(Math.PI/2-e-b,.01),Math.PI-.01)))+c)*j}}({width:h,height:i,altitude:k,fovy:l,pitch:j,nearZMultiplier:m,farZMultiplier:n}),s=(a=[],f=o,g=p,c=q,b=r,e=1/Math.tan(f/2),a[0]=e/g,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=e,a[6]=0,a[7]=0,a[8]=0,a[9]=0,a[11]=-1,a[12]=0,a[13]=0,a[15]=0,null!=b&&b!==1/0?(d=1/(c-b),a[10]=(b+c)*d,a[14]=2*b*c*d):(a[10]=-1,a[14]=-2*c),a);return s}({width:f,height:c,pitch:n,fovy:b,nearZMultiplier:t,farZMultiplier:u}),this.viewMatrix=function({height:F,pitch:G,bearing:H,altitude:I,scale:l,center:E=null}){var a,b,m,f,g,n,o,p,q,r,s,t,u,c,d,v,h,i,w,x,y,z,A,B,C,D,j,k;const e=aB();return aH(e,e,[0,0,-I]),a=e,b=e,m=-G*aO,f=Math.sin(m),g=Math.cos(m),n=b[4],o=b[5],p=b[6],q=b[7],r=b[8],s=b[9],t=b[10],u=b[11],b!==a&&(a[0]=b[0],a[1]=b[1],a[2]=b[2],a[3]=b[3],a[12]=b[12],a[13]=b[13],a[14]=b[14],a[15]=b[15]),a[4]=n*g+r*f,a[5]=o*g+s*f,a[6]=p*g+t*f,a[7]=q*g+u*f,a[8]=r*g-n*f,a[9]=s*g-o*f,a[10]=t*g-p*f,a[11]=u*g-q*f,c=e,d=e,v=H*aO,h=Math.sin(v),i=Math.cos(v),w=d[0],x=d[1],y=d[2],z=d[3],A=d[4],B=d[5],C=d[6],D=d[7],d!==c&&(c[8]=d[8],c[9]=d[9],c[10]=d[10],c[11]=d[11],c[12]=d[12],c[13]=d[13],c[14]=d[14],c[15]=d[15]),c[0]=w*i+A*h,c[1]=x*i+B*h,c[2]=y*i+C*h,c[3]=z*i+D*h,c[4]=A*i-w*h,c[5]=B*i-x*h,c[6]=C*i-y*h,c[7]=D*i-z*h,aI(e,e,[l/=F,l,l]),E&&aH(e,e,(j=[],k=E,j[0]=-k[0],j[1]=-k[1],j[2]=-k[2],j)),e}({height:c,scale:r,center:d,pitch:n,bearing:q,altitude:a}),this.width=f,this.height=c,this.scale=r,this.latitude=l,this.longitude=m,this.zoom=p,this.pitch=n,this.bearing=q,this.altitude=a,this.fovy=b,this.center=d,this.meterOffset=o||[0,0,0],this.distanceScales=s,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 b,c,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,a;const{width:I,height:J,projectionMatrix:K,viewMatrix:L}=this,G=aB();aG(G,G,K),aG(G,G,L),this.viewProjectionMatrix=G;const d=aB();aI(d,d,[I/2,-J/2,1]),aH(d,d,[1,-1,0]),aG(d,d,G);const H=(b=aB(),e=(c=d)[0],f=c[1],g=c[2],h=c[3],i=c[4],j=c[5],k=c[6],l=c[7],m=c[8],n=c[9],o=c[10],p=c[11],q=c[12],r=c[13],s=c[14],t=c[15],u=e*j-f*i,v=e*k-g*i,w=e*l-h*i,x=f*k-g*j,y=f*l-h*j,z=g*l-h*k,A=m*r-n*q,B=m*s-o*q,C=m*t-p*q,D=n*s-o*r,E=n*t-p*r,F=o*t-p*s,a=u*F-v*E+w*D+x*C-y*B+z*A,a?(a=1/a,b[0]=(j*F-k*E+l*D)*a,b[1]=(g*E-f*F-h*D)*a,b[2]=(r*z-s*y+t*x)*a,b[3]=(o*y-n*z-p*x)*a,b[4]=(k*C-i*F-l*B)*a,b[5]=(e*F-g*C+h*B)*a,b[6]=(s*w-q*z-t*v)*a,b[7]=(m*z-o*w+p*v)*a,b[8]=(i*E-j*C+l*A)*a,b[9]=(f*C-e*E-h*A)*a,b[10]=(q*y-r*w+t*u)*a,b[11]=(n*w-m*y-p*u)*a,b[12]=(j*B-i*D-k*A)*a,b[13]=(e*D-f*B+g*A)*a,b[14]=(r*v-q*x-s*u)*a,b[15]=(m*x-n*v+o*u)*a,b):null);if(!H)throw new Error("Pixel project matrix not invertible");this.pixelProjectionMatrix=d,this.pixelUnprojectionMatrix=H}equals(a){return a instanceof aY&&a.width===this.width&&a.height===this.height&&aJ(a.projectionMatrix,this.projectionMatrix)&&aJ(a.viewMatrix,this.viewMatrix)}project(a,{topLeft:f=!0}={}){const g=this.projectPosition(a),b=function(d,e){const[a,b,c=0]=d;return aM(Number.isFinite(a)&&Number.isFinite(b)&&Number.isFinite(c)),aC(e,[a,b,c,1])}(g,this.pixelProjectionMatrix),[c,d]=b,e=f?d:this.height-d;return 2===a.length?[c,e]:[c,e,b[2]]}unproject(f,{topLeft:g=!0,targetZ:a}={}){const[h,d,e]=f,i=g?d:this.height-d,j=a&&a*this.distanceScales.unitsPerMeter[2],k=aV([h,i,e],this.pixelUnprojectionMatrix,j),[b,c,l]=this.unprojectPosition(k);return Number.isFinite(e)?[b,c,l]:Number.isFinite(a)?[b,c,a]:[b,c]}projectPosition(a){const[b,c]=aR(a),d=(a[2]||0)*this.distanceScales.unitsPerMeter[2];return[b,c,d]}unprojectPosition(a){const[b,c]=aS(a),d=(a[2]||0)*this.distanceScales.metersPerUnit[2];return[b,c,d]}projectFlat(a){return aR(a)}unprojectFlat(a){return aS(a)}getMapCenterByLngLatPosition({lngLat:c,pos:d}){var a,b;const e=aV(d,this.pixelUnprojectionMatrix),f=aR(c),g=aK([],f,(a=[],b=e,a[0]=-b[0],a[1]=-b[1],a)),h=aK([],this.center,g);return aS(h)}getLocationAtPoint({lngLat:a,pos:b}){return this.getMapCenterByLngLatPosition({lngLat:a,pos:b})}fitBounds(c,d={}){const{width:a,height:b}=this,{longitude:e,latitude:f,zoom:g}=function({width:m,height:n,bounds:o,minExtent:f=0,maxZoom:p=24,padding:a=0,offset:g=[0,0]}){const[[q,r],[s,t]]=o;if(Number.isFinite(a)){const b=a;a={top:b,bottom:b,left:b,right:b}}else aM(Number.isFinite(a.top)&&Number.isFinite(a.bottom)&&Number.isFinite(a.left)&&Number.isFinite(a.right));const c=aR([q,aE(t,-85.051129,85.051129)]),d=aR([s,aE(r,-85.051129,85.051129)]),h=[Math.max(Math.abs(d[0]-c[0]),f),Math.max(Math.abs(d[1]-c[1]),f)],e=[m-a.left-a.right-2*Math.abs(g[0]),n-a.top-a.bottom-2*Math.abs(g[1])];aM(e[0]>0&&e[1]>0);const i=e[0]/h[0],j=e[1]/h[1],u=(a.right-a.left)/2/i,v=(a.bottom-a.top)/2/j,w=[(d[0]+c[0])/2+u,(d[1]+c[1])/2+v],k=aS(w),l=Math.min(p,aF(Math.abs(Math.min(i,j))));return aM(Number.isFinite(l)),{longitude:k[0],latitude:k[1],zoom:l}}(Object.assign({width:a,height:b,bounds:c},d));return new aY({width:a,height:b,longitude:e,latitude:f,zoom:g})}getBounds(b){const a=this.getBoundingRegion(b),c=Math.min(...a.map(a=>a[0])),d=Math.max(...a.map(a=>a[0])),e=Math.min(...a.map(a=>a[1])),f=Math.max(...a.map(a=>a[1]));return[[c,e],[d,f]]}getBoundingRegion(a={}){return function(a,d=0){const{width:e,height:h,unproject:b}=a,c={targetZ:d},i=b([0,h],c),j=b([e,h],c);let f,g;const k=a.fovy?.5*a.fovy*aW:Math.atan(.5/a.altitude),l=(90-a.pitch)*aW;return k>l-.01?(f=aX(a,0,d),g=aX(a,e,d)):(f=b([0,0],c),g=b([e,0],c)),[i,j,g,f]}(this,a.z||0)}}const aZ=["longitude","latitude","zoom"],a$={curve:1.414,speed:1.2};function a_(d,h,i){var f,j,k,o,p,q;i=Object.assign({},a$,i);const g=i.curve,l=d.zoom,w=[d.longitude,d.latitude],x=aQ(l),y=h.zoom,z=[h.longitude,h.latitude],A=aQ(y-l),r=aR(w),B=aR(z),s=(f=[],j=B,k=r,f[0]=j[0]-k[0],f[1]=j[1]-k[1],f),a=Math.max(d.width,d.height),e=a/A,t=(p=(o=s)[0],q=o[1],Math.hypot(p,q)*x),c=Math.max(t,.01),b=g*g,m=(e*e-a*a+b*b*c*c)/(2*a*b*c),n=(e*e-a*a-b*b*c*c)/(2*e*b*c),u=Math.log(Math.sqrt(m*m+1)-m),v=Math.log(Math.sqrt(n*n+1)-n);return{startZoom:l,startCenterXY:r,uDelta:s,w0:a,u1:t,S:(v-u)/g,rho:g,rho2:b,r0:u,r1:v}}var N=function(){if("undefined"!=typeof Map)return Map;function a(a,c){var b=-1;return a.some(function(a,d){return a[0]===c&&(b=d,!0)}),b}return function(){function b(){this.__entries__=[]}return Object.defineProperty(b.prototype,"size",{get:function(){return this.__entries__.length},enumerable:!0,configurable:!0}),b.prototype.get=function(c){var d=a(this.__entries__,c),b=this.__entries__[d];return b&&b[1]},b.prototype.set=function(b,c){var d=a(this.__entries__,b);~d?this.__entries__[d][1]=c:this.__entries__.push([b,c])},b.prototype.delete=function(d){var b=this.__entries__,c=a(b,d);~c&&b.splice(c,1)},b.prototype.has=function(b){return!!~a(this.__entries__,b)},b.prototype.clear=function(){this.__entries__.splice(0)},b.prototype.forEach=function(e,a){void 0===a&&(a=null);for(var b=0,c=this.__entries__;b0},a.prototype.connect_=function(){a0&&!this.connected_&&(document.addEventListener("transitionend",this.onTransitionEnd_),window.addEventListener("resize",this.refresh),a3?(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)},a.prototype.disconnect_=function(){a0&&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)},a.prototype.onTransitionEnd_=function(b){var a=b.propertyName,c=void 0===a?"":a;a2.some(function(a){return!!~c.indexOf(a)})&&this.refresh()},a.getInstance=function(){return this.instance_||(this.instance_=new a),this.instance_},a.instance_=null,a}(),a5=function(b,c){for(var a=0,d=Object.keys(c);a0},a}(),bi="undefined"!=typeof WeakMap?new WeakMap:new N,O=function(){function a(b){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function.");if(!arguments.length)throw new TypeError("1 argument required, but only 0 present.");var c=a4.getInstance(),d=new bh(b,c,this);bi.set(this,d)}return a}();["observe","unobserve","disconnect"].forEach(function(a){O.prototype[a]=function(){var b;return(b=bi.get(this))[a].apply(b,arguments)}});var bj=void 0!==o.ResizeObserver?o.ResizeObserver:O;function bk(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}function bl(d,c){for(var b=0;b=a.length?{done:!0}:{done:!1,value:a[d++]}},e:function(a){throw a},f:b}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var e,f,g=!0,h=!1;return{s:function(){e=a[Symbol.iterator]()},n:function(){var a=e.next();return g=a.done,a},e:function(a){h=!0,f=a},f:function(){try{g||null==e.return||e.return()}finally{if(h)throw f}}}}function bq(a,c){if(a){if("string"==typeof a)return br(a,c);var b=Object.prototype.toString.call(a).slice(8,-1);if("Object"===b&&a.constructor&&(b=a.constructor.name),"Map"===b||"Set"===b)return Array.from(a);if("Arguments"===b||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(b))return br(a,c)}}function br(c,a){(null==a||a>c.length)&&(a=c.length);for(var b=0,d=new Array(a);b1&& void 0!==arguments[1]?arguments[1]:"component";b.debug&&a.checkPropTypes(Q,b,"prop",c)}var i=function(){function a(b){var c=this;if(bk(this,a),g(this,"props",R),g(this,"width",0),g(this,"height",0),g(this,"_fireLoadEvent",function(){c.props.onLoad({type:"load",target:c._map})}),g(this,"_handleError",function(a){c.props.onError(a)}),!b.mapboxgl)throw new Error("Mapbox not available");this.mapboxgl=b.mapboxgl,a.initialized||(a.initialized=!0,this._checkStyleSheet(this.mapboxgl.version)),this._initialize(b)}return bm(a,[{key:"finalize",value:function(){return this._destroy(),this}},{key:"setProps",value:function(a){return this._update(this.props,a),this}},{key:"redraw",value:function(){var a=this._map;a.style&&(a._frame&&(a._frame.cancel(),a._frame=null),a._render())}},{key:"getMap",value:function(){return this._map}},{key:"_reuse",value:function(b){this._map=a.savedMap;var d=this._map.getContainer(),c=b.container;for(c.classList.add("mapboxgl-map");d.childNodes.length>0;)c.appendChild(d.childNodes[0]);this._map._container=c,a.savedMap=null,b.mapStyle&&this._map.setStyle(bt(b.mapStyle),{diff:!1}),this._map.isStyleLoaded()?this._fireLoadEvent():this._map.once("styledata",this._fireLoadEvent)}},{key:"_create",value:function(b){if(b.reuseMaps&&a.savedMap)this._reuse(b);else{if(b.gl){var d=HTMLCanvasElement.prototype.getContext;HTMLCanvasElement.prototype.getContext=function(){return HTMLCanvasElement.prototype.getContext=d,b.gl}}var c={container:b.container,center:[0,0],zoom:8,pitch:0,bearing:0,maxZoom:24,style:bt(b.mapStyle),interactive:!1,trackResize:!1,attributionControl:b.attributionControl,preserveDrawingBuffer:b.preserveDrawingBuffer};b.transformRequest&&(c.transformRequest=b.transformRequest),this._map=new this.mapboxgl.Map(Object.assign({},c,b.mapOptions)),this._map.once("load",this._fireLoadEvent),this._map.on("error",this._handleError)}return this}},{key:"_destroy",value:function(){this._map&&(this.props.reuseMaps&&!a.savedMap?(a.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(a){var d=this;bv(a=Object.assign({},R,a),"Mapbox"),this.mapboxgl.accessToken=a.mapboxApiAccessToken||R.mapboxApiAccessToken,this.mapboxgl.baseApiUrl=a.mapboxApiUrl,this._create(a);var b=a.container;Object.defineProperty(b,"offsetWidth",{configurable:!0,get:function(){return d.width}}),Object.defineProperty(b,"clientWidth",{configurable:!0,get:function(){return d.width}}),Object.defineProperty(b,"offsetHeight",{configurable:!0,get:function(){return d.height}}),Object.defineProperty(b,"clientHeight",{configurable:!0,get:function(){return d.height}});var c=this._map.getCanvas();c&&(c.style.outline="none"),this._updateMapViewport({},a),this._updateMapSize({},a),this.props=a}},{key:"_update",value:function(b,a){if(this._map){bv(a=Object.assign({},this.props,a),"Mapbox");var c=this._updateMapViewport(b,a),d=this._updateMapSize(b,a);this._updateMapStyle(b,a),!a.asyncRender&&(c||d)&&this.redraw(),this.props=a}}},{key:"_updateMapStyle",value:function(b,a){b.mapStyle!==a.mapStyle&&this._map.setStyle(bt(a.mapStyle),{diff:!a.preventStyleDiffing})}},{key:"_updateMapSize",value:function(b,a){var c=b.width!==a.width||b.height!==a.height;return c&&(this.width=a.width,this.height=a.height,this._map.resize()),c}},{key:"_updateMapViewport",value:function(d,e){var b=this._getViewState(d),a=this._getViewState(e),c=a.latitude!==b.latitude||a.longitude!==b.longitude||a.zoom!==b.zoom||a.pitch!==b.pitch||a.bearing!==b.bearing||a.altitude!==b.altitude;return c&&(this._map.jumpTo(this._viewStateToMapboxProps(a)),a.altitude!==b.altitude&&(this._map.transform.altitude=a.altitude)),c}},{key:"_getViewState",value:function(b){var a=b.viewState||b,f=a.longitude,g=a.latitude,h=a.zoom,c=a.pitch,d=a.bearing,e=a.altitude;return{longitude:f,latitude:g,zoom:h,pitch:void 0===c?0:c,bearing:void 0===d?0:d,altitude:void 0===e?1.5:e}}},{key:"_checkStyleSheet",value:function(){var c=arguments.length>0&& void 0!==arguments[0]?arguments[0]:"0.47.0";if(void 0!==P)try{var a=P.createElement("div");if(a.className="mapboxgl-map",a.style.display="none",P.body.appendChild(a),!("static"!==window.getComputedStyle(a).position)){var b=P.createElement("link");b.setAttribute("rel","stylesheet"),b.setAttribute("type","text/css"),b.setAttribute("href","https://api.tiles.mapbox.com/mapbox-gl-js/v".concat(c,"/mapbox-gl.css")),P.head.appendChild(b)}}catch(d){}}},{key:"_viewStateToMapboxProps",value:function(a){return{center:[a.longitude,a.latitude],zoom:a.zoom,bearing:a.bearing,pitch:a.pitch}}}]),a}();g(i,"initialized",!1),g(i,"propTypes",Q),g(i,"defaultProps",R),g(i,"savedMap",null);var S=b(6158),A=b.n(S);function bw(a){return Array.isArray(a)||ArrayBuffer.isView(a)}function bx(a,b){if(a===b)return!0;if(bw(a)&&bw(b)){if(a.length!==b.length)return!1;for(var c=0;c=Math.abs(a-b)}function by(a,b,c){return Math.max(b,Math.min(c,a))}function bz(a,c,b){return bw(a)?a.map(function(a,d){return bz(a,c[d],b)}):b*c+(1-b)*a}function bA(a,b){if(!a)throw new Error(b||"react-map-gl: assertion failed.")}function bB(c,d){var a=Object.keys(c);if(Object.getOwnPropertySymbols){var b=Object.getOwnPropertySymbols(c);d&&(b=b.filter(function(a){return Object.getOwnPropertyDescriptor(c,a).enumerable})),a.push.apply(a,b)}return a}function bC(c){for(var a=1;a0,"`scale` must be a positive number");var f=this._state,b=f.startZoom,c=f.startZoomLngLat;Number.isFinite(b)||(b=this._viewportProps.zoom,c=this._unproject(i)||this._unproject(d)),bA(c,"`startZoomLngLat` prop is required for zoom behavior to calculate where to position the map.");var g=this._calculateNewZoom({scale:e,startZoom:b||0}),j=new aY(Object.assign({},this._viewportProps,{zoom:g})),k=j.getMapCenterByLngLatPosition({lngLat:c,pos:d}),h=aA(k,2),l=h[0],m=h[1];return this._getUpdatedMapState({zoom:g,longitude:l,latitude:m})}},{key:"zoomEnd",value:function(){return this._getUpdatedMapState({startZoomLngLat:null,startZoom:null})}},{key:"_getUpdatedMapState",value:function(b){return new a(Object.assign({},this._viewportProps,this._state,b))}},{key:"_applyConstraints",value:function(a){var b=a.maxZoom,c=a.minZoom,d=a.zoom;a.zoom=by(d,c,b);var e=a.maxPitch,f=a.minPitch,g=a.pitch;return a.pitch=by(g,f,e),Object.assign(a,function({width:j,height:e,longitude:b,latitude:a,zoom:d,pitch:k=0,bearing:c=0}){(b< -180||b>180)&&(b=aD(b+180,360)-180),(c< -180||c>180)&&(c=aD(c+180,360)-180);const f=aF(e/512);if(d<=f)d=f,a=0;else{const g=e/2/Math.pow(2,d),h=aS([0,g])[1];if(ai&&(a=i)}}return{width:j,height:e,longitude:b,latitude:a,zoom:d,pitch:k,bearing:c}}(a)),a}},{key:"_unproject",value:function(a){var b=new aY(this._viewportProps);return a&&b.unproject(a)}},{key:"_calculateNewLngLat",value:function(a){var b=a.startPanLngLat,c=a.pos,d=new aY(this._viewportProps);return d.getMapCenterByLngLatPosition({lngLat:b,pos:c})}},{key:"_calculateNewZoom",value:function(a){var c=a.scale,d=a.startZoom,b=this._viewportProps,e=b.maxZoom,f=b.minZoom;return by(d+Math.log2(c),f,e)}},{key:"_calculateNewPitchAndBearing",value:function(c){var f=c.deltaScaleX,a=c.deltaScaleY,g=c.startBearing,b=c.startPitch;a=by(a,-1,1);var e=this._viewportProps,h=e.minPitch,i=e.maxPitch,d=b;return a>0?d=b+a*(i-b):a<0&&(d=b-a*(h-b)),{pitch:d,bearing:g+180*f}}},{key:"_getRotationParams",value:function(c,d){var h=c[0]-d[0],e=c[1]-d[1],i=c[1],a=d[1],f=this._viewportProps,j=f.width,g=f.height,b=0;return e>0?Math.abs(g-a)>5&&(b=e/(a-g)*1.2):e<0&&a>5&&(b=1-i/a),{deltaScaleX:h/j,deltaScaleY:b=Math.min(1,Math.max(-1,b))}}}]),a}();function bF(a){return a[0].toLowerCase()+a.slice(1)}function bG(c,d){var a=Object.keys(c);if(Object.getOwnPropertySymbols){var b=Object.getOwnPropertySymbols(c);d&&(b=b.filter(function(a){return Object.getOwnPropertyDescriptor(c,a).enumerable})),a.push.apply(a,b)}return a}function bH(c){for(var a=1;a1&& void 0!==arguments[1]?arguments[1]:{},b=a.current&&a.current.getMap();return b&&b.queryRenderedFeatures(c,d)}}},[]);var p=(0,c.useCallback)(function(b){var a=b.target;a===o.current&&a.scrollTo(0,0)},[]),q=d&&c.createElement(bI,{value:bN(bN({},b),{},{viewport:b.viewport||bP(bN({map:d,props:a},m)),map:d,container:b.container||h.current})},c.createElement("div",{key:"map-overlays",className:"overlays",ref:o,style:bQ,onScroll:p},a.children)),r=a.className,s=a.width,t=a.height,u=a.style,v=a.visibilityConstraints,w=Object.assign({position:"relative"},u,{width:s,height:t}),x=a.visible&&function(c){var b=arguments.length>1&& void 0!==arguments[1]?arguments[1]:B;for(var a in b){var d=a.slice(0,3),e=bF(a.slice(3));if("min"===d&&c[e]b[a])return!1}return!0}(a.viewState||a,v),y=Object.assign({},bQ,{visibility:x?"inherit":"hidden"});return c.createElement("div",{key:"map-container",ref:h,style:w},c.createElement("div",{key:"map-mapbox",ref:n,style:y,className:r}),q,!l&&!a.disableTokenWarning&&c.createElement(bR,null))});j.supported=function(){return A()&&A().supported()},j.propTypes=T,j.defaultProps=U;var q=j;function bS(c,a){(null==a||a>c.length)&&(a=c.length);for(var b=0,d=new Array(a);b=a.length?{done:!0}:{done:!1,value:a[d++]}},e:function(a){throw a},f:b}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var e,f,g=!0,h=!1;return{s:function(){e=a[Symbol.iterator]()},n:function(){var a=e.next();return g=a.done,a},e:function(a){h=!0,f=a},f:function(){try{g||null==e.return||e.return()}finally{if(h)throw f}}}}(this.propNames||[]);try{for(a.s();!(b=a.n()).done;){var c=b.value;if(!bx(d[c],e[c]))return!1}}catch(f){a.e(f)}finally{a.f()}return!0}},{key:"initializeProps",value:function(a,b){return{start:a,end:b}}},{key:"interpolateProps",value:function(a,b,c){bA(!1,"interpolateProps is not implemented")}},{key:"getDuration",value:function(b,a){return a.transitionDuration}}]),a}();function bT(a){if(void 0===a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return a}function bU(a,b){return(bU=Object.setPrototypeOf||function(a,b){return a.__proto__=b,a})(a,b)}function bV(b,a){if("function"!=typeof a&&null!==a)throw new TypeError("Super expression must either be null or a function");b.prototype=Object.create(a&&a.prototype,{constructor:{value:b,writable:!0,configurable:!0}}),Object.defineProperty(b,"prototype",{writable:!1}),a&&bU(b,a)}function bW(a){return(bW="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a})(a)}function bX(b,a){if(a&&("object"===bW(a)||"function"==typeof a))return a;if(void 0!==a)throw new TypeError("Derived constructors may only return object or undefined");return bT(b)}function bY(a){return(bY=Object.setPrototypeOf?Object.getPrototypeOf:function(a){return a.__proto__||Object.getPrototypeOf(a)})(a)}var bZ={longitude:1,bearing:1};function b$(a){return Number.isFinite(a)||Array.isArray(a)}function b_(b,c,a){return b in bZ&&Math.abs(a-c)>180&&(a=a<0?a+360:a-360),a}function b0(a,c){if("undefined"==typeof Symbol||null==a[Symbol.iterator]){if(Array.isArray(a)||(e=b1(a))||c&&a&&"number"==typeof a.length){e&&(a=e);var d=0,b=function(){};return{s:b,n:function(){return d>=a.length?{done:!0}:{done:!1,value:a[d++]}},e:function(a){throw a},f:b}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var e,f,g=!0,h=!1;return{s:function(){e=a[Symbol.iterator]()},n:function(){var a=e.next();return g=a.done,a},e:function(a){h=!0,f=a},f:function(){try{g||null==e.return||e.return()}finally{if(h)throw f}}}}function b1(a,c){if(a){if("string"==typeof a)return b2(a,c);var b=Object.prototype.toString.call(a).slice(8,-1);if("Object"===b&&a.constructor&&(b=a.constructor.name),"Map"===b||"Set"===b)return Array.from(a);if("Arguments"===b||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(b))return b2(a,c)}}function b2(c,a){(null==a||a>c.length)&&(a=c.length);for(var b=0,d=new Array(a);b=a.length?{done:!0}:{done:!1,value:a[d++]}},e:function(a){throw a},f:b}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var e,f,g=!0,h=!1;return{s:function(){e=a[Symbol.iterator]()},n:function(){var a=e.next();return g=a.done,a},e:function(a){h=!0,f=a},f:function(){try{g||null==e.return||e.return()}finally{if(h)throw f}}}}function b8(a,c){if(a){if("string"==typeof a)return b9(a,c);var b=Object.prototype.toString.call(a).slice(8,-1);if("Object"===b&&a.constructor&&(b=a.constructor.name),"Map"===b||"Set"===b)return Array.from(a);if("Arguments"===b||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(b))return b9(a,c)}}function b9(c,a){(null==a||a>c.length)&&(a=c.length);for(var b=0,d=new Array(a);b0&& void 0!==arguments[0]?arguments[0]:{};return bk(this,d),g(bT(a=e.call(this)),"propNames",b3),a.props=Object.assign({},b6,b),a}bm(d,[{key:"initializeProps",value:function(h,i){var j,e={},f={},c=b0(b4);try{for(c.s();!(j=c.n()).done;){var a=j.value,g=h[a],k=i[a];bA(b$(g)&&b$(k),"".concat(a," must be supplied for transition")),e[a]=g,f[a]=b_(a,g,k)}}catch(n){c.e(n)}finally{c.f()}var l,d=b0(b5);try{for(d.s();!(l=d.n()).done;){var b=l.value,m=h[b]||0,o=i[b]||0;e[b]=m,f[b]=b_(b,m,o)}}catch(p){d.e(p)}finally{d.f()}return{start:e,end:f}}},{key:"interpolateProps",value:function(c,d,e){var f,g=function(h,i,j,r={}){var k,l,m,c,d,e;const a={},{startZoom:s,startCenterXY:t,uDelta:u,w0:v,u1:n,S:w,rho:o,rho2:x,r0:b}=a_(h,i,r);if(n<.01){for(const f of aZ){const y=h[f],z=i[f];a[f]=(k=y,l=z,(m=j)*l+(1-m)*k)}return a}const p=j*w,A=s+aF(1/(Math.cosh(b)/Math.cosh(b+o*p))),g=(c=[],d=u,e=v*((Math.cosh(b)*Math.tanh(b+o*p)-Math.sinh(b))/x)/n,c[0]=d[0]*e,c[1]=d[1]*e,c);aK(g,g,t);const q=aS(g);return a.longitude=q[0],a.latitude=q[1],a.zoom=A,a}(c,d,e,this.props),a=b0(b5);try{for(a.s();!(f=a.n()).done;){var b=f.value;g[b]=bz(c[b],d[b],e)}}catch(h){a.e(h)}finally{a.f()}return g}},{key:"getDuration",value:function(c,b){var a=b.transitionDuration;return"auto"===a&&(a=function(f,g,a={}){a=Object.assign({},a$,a);const{screenSpeed:c,speed:h,maxDuration:d}=a,{S:i,rho:j}=a_(f,g,a),e=1e3*i;let b;return b=Number.isFinite(c)?e/(c/j):e/h,Number.isFinite(d)&&b>d?0:b}(c,b,this.props)),a}}])}(C);var ca=["longitude","latitude","zoom","bearing","pitch"],D=function(b){bV(a,b);var c,d,e=(c=a,d=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(a){return!1}}(),function(){var a,b=bY(c);if(d){var e=bY(this).constructor;a=Reflect.construct(b,arguments,e)}else a=b.apply(this,arguments);return bX(this,a)});function a(){var c,b=arguments.length>0&& void 0!==arguments[0]?arguments[0]:{};return bk(this,a),c=e.call(this),Array.isArray(b)&&(b={transitionProps:b}),c.propNames=b.transitionProps||ca,b.around&&(c.around=b.around),c}return bm(a,[{key:"initializeProps",value:function(g,c){var d={},e={};if(this.around){d.around=this.around;var h=new aY(g).unproject(this.around);Object.assign(e,c,{around:new aY(c).project(h),aroundLngLat:h})}var i,b=b7(this.propNames);try{for(b.s();!(i=b.n()).done;){var a=i.value,f=g[a],j=c[a];bA(b$(f)&&b$(j),"".concat(a," must be supplied for transition")),d[a]=f,e[a]=b_(a,f,j)}}catch(k){b.e(k)}finally{b.f()}return{start:d,end:e}}},{key:"interpolateProps",value:function(e,a,f){var g,b={},c=b7(this.propNames);try{for(c.s();!(g=c.n()).done;){var d=g.value;b[d]=bz(e[d],a[d],f)}}catch(i){c.e(i)}finally{c.f()}if(a.around){var h=aA(new aY(Object.assign({},a,b)).getMapCenterByLngLatPosition({lngLat:a.aroundLngLat,pos:bz(e.around,a.around,f)}),2),j=h[0],k=h[1];b.longitude=j,b.latitude=k}return b}}]),a}(C),r=function(){},E={BREAK:1,SNAP_TO_END:2,IGNORE:3,UPDATE:4},V={transitionDuration:0,transitionEasing:function(a){return a},transitionInterpolator:new D,transitionInterruption:E.BREAK,onTransitionStart:r,onTransitionInterrupt:r,onTransitionEnd:r},F=function(){function a(){var c=this,b=arguments.length>0&& void 0!==arguments[0]?arguments[0]:{};bk(this,a),g(this,"_animationFrame",null),g(this,"_onTransitionFrame",function(){c._animationFrame=requestAnimationFrame(c._onTransitionFrame),c._updateViewport()}),this.props=null,this.onViewportChange=b.onViewportChange||r,this.onStateChange=b.onStateChange||r,this.time=b.getTime||Date.now}return bm(a,[{key:"getViewportInTransition",value:function(){return this._animationFrame?this.state.propsInTransition:null}},{key:"processViewportChange",value:function(c){var a=this.props;if(this.props=c,!a||this._shouldIgnoreViewportChange(a,c))return!1;if(this._isTransitionEnabled(c)){var d=Object.assign({},a),b=Object.assign({},c);if(this._isTransitionInProgress()&&(a.onTransitionInterrupt(),this.state.interruption===E.SNAP_TO_END?Object.assign(d,this.state.endProps):Object.assign(d,this.state.propsInTransition),this.state.interruption===E.UPDATE)){var f,g,h,e=this.time(),i=(e-this.state.startTime)/this.state.duration;b.transitionDuration=this.state.duration-(e-this.state.startTime),b.transitionEasing=(h=(f=this.state.easing)(g=i),function(a){return 1/(1-h)*(f(a*(1-g)+g)-h)}),b.transitionInterpolator=d.transitionInterpolator}return b.onTransitionStart(),this._triggerTransition(d,b),!0}return this._isTransitionInProgress()&&(a.onTransitionInterrupt(),this._endTransition()),!1}},{key:"_isTransitionInProgress",value:function(){return Boolean(this._animationFrame)}},{key:"_isTransitionEnabled",value:function(a){var b=a.transitionDuration,c=a.transitionInterpolator;return(b>0||"auto"===b)&&Boolean(c)}},{key:"_isUpdateDueToCurrentTransition",value:function(a){return!!this.state.propsInTransition&&this.state.interpolator.arePropsEqual(a,this.state.propsInTransition)}},{key:"_shouldIgnoreViewportChange",value:function(b,a){return!b||(this._isTransitionInProgress()?this.state.interruption===E.IGNORE||this._isUpdateDueToCurrentTransition(a):!this._isTransitionEnabled(a)||a.transitionInterpolator.arePropsEqual(b,a))}},{key:"_triggerTransition",value:function(b,a){bA(this._isTransitionEnabled(a)),this._animationFrame&&cancelAnimationFrame(this._animationFrame);var c=a.transitionInterpolator,d=c.getDuration?c.getDuration(b,a):a.transitionDuration;if(0!==d){var e=a.transitionInterpolator.initializeProps(b,a),f={inTransition:!0,isZooming:b.zoom!==a.zoom,isPanning:b.longitude!==a.longitude||b.latitude!==a.latitude,isRotating:b.bearing!==a.bearing||b.pitch!==a.pitch};this.state={duration:d,easing:a.transitionEasing,interpolator:a.transitionInterpolator,interruption:a.transitionInterruption,startTime:this.time(),startProps:e.start,endProps:e.end,animation:null,propsInTransition:{}},this._onTransitionFrame(),this.onStateChange(f)}}},{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 d=this.time(),a=this.state,e=a.startTime,f=a.duration,g=a.easing,h=a.interpolator,i=a.startProps,j=a.endProps,c=!1,b=(d-e)/f;b>=1&&(b=1,c=!0),b=g(b);var k=h.interpolateProps(i,j,b),l=new bE(Object.assign({},this.props,k));this.state.propsInTransition=l.getViewportProps(),this.onViewportChange(this.state.propsInTransition,this.props),c&&(this._endTransition(),this.props.onTransitionEnd())}}]),a}();g(F,"defaultProps",V);var W=b(840),k=b.n(W);const cb={mousedown:1,mousemove:2,mouseup:4};!function(a){const b=a.prototype.handler;a.prototype.handler=function(a){const c=this.store;a.button>0&&"pointerdown"===a.type&& !function(b,c){for(let a=0;ab.pointerId===a.pointerId)&&c.push(a),b.call(this,a)}}(k().PointerEventInput),k().MouseInput.prototype.handler=function(a){let b=cb[a.type];1&b&&a.button>=0&&(this.pressed=!0),2&b&&0===a.which&&(b=4),this.pressed&&(4&b&&(this.pressed=!1),this.callback(this.manager,b,{pointers:[a],changedPointers:[a],pointerType:"mouse",srcEvent:a}))};const cc=k().Manager;var e=k();const cd=e?[[e.Pan,{event:"tripan",pointers:3,threshold:0,enable:!1}],[e.Rotate,{enable:!1}],[e.Pinch,{enable:!1}],[e.Swipe,{enable:!1}],[e.Pan,{threshold:0,enable:!1}],[e.Press,{enable:!1}],[e.Tap,{event:"doubletap",taps:2,enable:!1}],[e.Tap,{event:"anytap",enable:!1}],[e.Tap,{enable:!1}]]:null,ce={tripan:["rotate","pinch","pan"],rotate:["pinch"],pinch:["pan"],pan:["press","doubletap","anytap","tap"],doubletap:["anytap"],anytap:["tap"]},cf={doubletap:["tap"]},cg={pointerdown:"pointerdown",pointermove:"pointermove",pointerup:"pointerup",touchstart:"pointerdown",touchmove:"pointermove",touchend:"pointerup",mousedown:"pointerdown",mousemove:"pointermove",mouseup:"pointerup"},s={KEY_EVENTS:["keydown","keyup"],MOUSE_EVENTS:["mousedown","mousemove","mouseup","mouseover","mouseout","mouseleave"],WHEEL_EVENTS:["wheel","mousewheel"]},ch={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"},ci={click:"tap",anyclick:"anytap",dblclick:"doubletap",mousedown:"pointerdown",mousemove:"pointermove",mouseup:"pointerup",mouseover:"pointerover",mouseout:"pointerout",mouseleave:"pointerleave"},X="undefined"!=typeof navigator&&navigator.userAgent?navigator.userAgent.toLowerCase():"",G="undefined"!=typeof window?window:b.g;void 0!==b.g&&b.g;let Y=!1;try{const l={get passive(){return Y=!0,!0}};G.addEventListener("test",l,l),G.removeEventListener("test",l,l)}catch(cj){}const ck=-1!==X.indexOf("firefox"),{WHEEL_EVENTS:cl}=s,cm="wheel";class cn{constructor(b,c,a={}){this.element=b,this.callback=c,this.options=Object.assign({enable:!0},a),this.events=cl.concat(a.events||[]),this.handleEvent=this.handleEvent.bind(this),this.events.forEach(a=>b.addEventListener(a,this.handleEvent,!!Y&&{passive:!1}))}destroy(){this.events.forEach(a=>this.element.removeEventListener(a,this.handleEvent))}enableEventType(a,b){a===cm&&(this.options.enable=b)}handleEvent(b){if(!this.options.enable)return;let a=b.deltaY;G.WheelEvent&&(ck&&b.deltaMode===G.WheelEvent.DOM_DELTA_PIXEL&&(a/=G.devicePixelRatio),b.deltaMode===G.WheelEvent.DOM_DELTA_LINE&&(a*=40));const c={x:b.clientX,y:b.clientY};0!==a&&a%4.000244140625==0&&(a=Math.floor(a/4.000244140625)),b.shiftKey&&a&&(a*=.25),this._onWheel(b,-a,c)}_onWheel(a,b,c){this.callback({type:cm,center:c,delta:b,srcEvent:a,pointerType:"mouse",target:a.target})}}const{MOUSE_EVENTS:co}=s,cp="pointermove",cq="pointerover",cr="pointerout",cs="pointerleave";class ct{constructor(b,c,a={}){this.element=b,this.callback=c,this.pressed=!1,this.options=Object.assign({enable:!0},a),this.enableMoveEvent=this.options.enable,this.enableLeaveEvent=this.options.enable,this.enableOutEvent=this.options.enable,this.enableOverEvent=this.options.enable,this.events=co.concat(a.events||[]),this.handleEvent=this.handleEvent.bind(this),this.events.forEach(a=>b.addEventListener(a,this.handleEvent))}destroy(){this.events.forEach(a=>this.element.removeEventListener(a,this.handleEvent))}enableEventType(a,b){a===cp&&(this.enableMoveEvent=b),a===cq&&(this.enableOverEvent=b),a===cr&&(this.enableOutEvent=b),a===cs&&(this.enableLeaveEvent=b)}handleEvent(a){this.handleOverEvent(a),this.handleOutEvent(a),this.handleLeaveEvent(a),this.handleMoveEvent(a)}handleOverEvent(a){this.enableOverEvent&&"mouseover"===a.type&&this.callback({type:cq,srcEvent:a,pointerType:"mouse",target:a.target})}handleOutEvent(a){this.enableOutEvent&&"mouseout"===a.type&&this.callback({type:cr,srcEvent:a,pointerType:"mouse",target:a.target})}handleLeaveEvent(a){this.enableLeaveEvent&&"mouseleave"===a.type&&this.callback({type:cs,srcEvent:a,pointerType:"mouse",target:a.target})}handleMoveEvent(a){if(this.enableMoveEvent)switch(a.type){case"mousedown":a.button>=0&&(this.pressed=!0);break;case"mousemove":0===a.which&&(this.pressed=!1),this.pressed||this.callback({type:cp,srcEvent:a,pointerType:"mouse",target:a.target});break;case"mouseup":this.pressed=!1}}}const{KEY_EVENTS:cu}=s,cv="keydown",cw="keyup";class cx{constructor(a,c,b={}){this.element=a,this.callback=c,this.options=Object.assign({enable:!0},b),this.enableDownEvent=this.options.enable,this.enableUpEvent=this.options.enable,this.events=cu.concat(b.events||[]),this.handleEvent=this.handleEvent.bind(this),a.tabIndex=b.tabIndex||0,a.style.outline="none",this.events.forEach(b=>a.addEventListener(b,this.handleEvent))}destroy(){this.events.forEach(a=>this.element.removeEventListener(a,this.handleEvent))}enableEventType(a,b){a===cv&&(this.enableDownEvent=b),a===cw&&(this.enableUpEvent=b)}handleEvent(a){const b=a.target||a.srcElement;("INPUT"!==b.tagName||"text"!==b.type)&&"TEXTAREA"!==b.tagName&&(this.enableDownEvent&&"keydown"===a.type&&this.callback({type:cv,srcEvent:a,key:a.key,target:a.target}),this.enableUpEvent&&"keyup"===a.type&&this.callback({type:cw,srcEvent:a,key:a.key,target:a.target}))}}const cy="contextmenu";class cz{constructor(a,b,c={}){this.element=a,this.callback=b,this.options=Object.assign({enable:!0},c),this.handleEvent=this.handleEvent.bind(this),a.addEventListener("contextmenu",this.handleEvent)}destroy(){this.element.removeEventListener("contextmenu",this.handleEvent)}enableEventType(a,b){a===cy&&(this.options.enable=b)}handleEvent(a){this.options.enable&&this.callback({type:cy,center:{x:a.clientX,y:a.clientY},srcEvent:a,pointerType:"mouse",target:a.target})}}const cA={pointerdown:1,pointermove:2,pointerup:4,mousedown:1,mousemove:2,mouseup:4},cB={srcElement:"root",priority:0};class cC{constructor(a){this.eventManager=a,this.handlers=[],this.handlersByElement=new Map,this.handleEvent=this.handleEvent.bind(this),this._active=!1}isEmpty(){return!this._active}add(f,g,a,h=!1,i=!1){const{handlers:j,handlersByElement:e}=this;a&&("object"!=typeof a||a.addEventListener)&&(a={srcElement:a}),a=a?Object.assign({},cB,a):cB;let b=e.get(a.srcElement);b||(b=[],e.set(a.srcElement,b));const c={type:f,handler:g,srcElement:a.srcElement,priority:a.priority};h&&(c.once=!0),i&&(c.passive=!0),j.push(c),this._active=this._active||!c.passive;let d=b.length-1;for(;d>=0&&!(b[d].priority>=c.priority);)d--;b.splice(d+1,0,c)}remove(f,g){const{handlers:b,handlersByElement:e}=this;for(let c=b.length-1;c>=0;c--){const a=b[c];if(a.type===f&&a.handler===g){b.splice(c,1);const d=e.get(a.srcElement);d.splice(d.indexOf(a),1),0===d.length&&e.delete(a.srcElement)}}this._active=b.some(a=>!a.passive)}handleEvent(c){if(this.isEmpty())return;const b=this._normalizeEvent(c);let a=c.srcEvent.target;for(;a&&a!==b.rootElement;){if(this._emit(b,a),b.handled)return;a=a.parentNode}this._emit(b,"root")}_emit(e,f){const a=this.handlersByElement.get(f);if(a){let g=!1;const h=()=>{e.handled=!0},i=()=>{e.handled=!0,g=!0},c=[];for(let b=0;b{const b=this.manager.get(a);b&&ce[a].forEach(a=>{b.recognizeWith(a)})}),b.recognizerOptions){const e=this.manager.get(d);if(e){const f=b.recognizerOptions[d];delete f.enable,e.set(f)}}for(const[h,c]of(this.wheelInput=new cn(a,this._onOtherEvent,{enable:!1}),this.moveInput=new ct(a,this._onOtherEvent,{enable:!1}),this.keyInput=new cx(a,this._onOtherEvent,{enable:!1,tabIndex:b.tabIndex}),this.contextmenuInput=new cz(a,this._onOtherEvent,{enable:!1}),this.events))c.isEmpty()||(this._toggleRecognizer(c.recognizerName,!0),this.manager.on(h,c.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(a,b,c){this._addEventHandler(a,b,c,!1)}once(a,b,c){this._addEventHandler(a,b,c,!0)}watch(a,b,c){this._addEventHandler(a,b,c,!1,!0)}off(a,b){this._removeEventHandler(a,b)}_toggleRecognizer(a,b){const{manager:d}=this;if(!d)return;const c=d.get(a);if(c&&c.options.enable!==b){c.set({enable:b});const e=cf[a];e&&!this.options.recognizers&&e.forEach(e=>{const f=d.get(e);b?(f.requireFailure(a),c.dropRequireFailure(e)):f.dropRequireFailure(a)})}this.wheelInput.enableEventType(a,b),this.moveInput.enableEventType(a,b),this.keyInput.enableEventType(a,b),this.contextmenuInput.enableEventType(a,b)}_addEventHandler(b,e,d,f,g){if("string"!=typeof b){for(const h in d=e,b)this._addEventHandler(h,b[h],d,f,g);return}const{manager:i,events:j}=this,c=ci[b]||b;let a=j.get(c);!a&&(a=new cC(this),j.set(c,a),a.recognizerName=ch[c]||c,i&&i.on(c,a.handleEvent)),a.add(b,e,d,f,g),a.isEmpty()||this._toggleRecognizer(a.recognizerName,!0)}_removeEventHandler(a,h){if("string"!=typeof a){for(const c in a)this._removeEventHandler(c,a[c]);return}const{events:d}=this,i=ci[a]||a,b=d.get(i);if(b&&(b.remove(a,h),b.isEmpty())){const{recognizerName:e}=b;let f=!1;for(const g of d.values())if(g.recognizerName===e&&!g.isEmpty()){f=!0;break}f||this._toggleRecognizer(e,!1)}}_onBasicInput(a){const{srcEvent:c}=a,b=cg[c.type];b&&this.manager.emit(b,a)}_onOtherEvent(a){this.manager.emit(a.type,a)}}function cE(c,d){var a=Object.keys(c);if(Object.getOwnPropertySymbols){var b=Object.getOwnPropertySymbols(c);d&&(b=b.filter(function(a){return Object.getOwnPropertyDescriptor(c,a).enumerable})),a.push.apply(a,b)}return a}function cF(c){for(var a=1;a0),e=d&&!this.state.isHovering,h=!d&&this.state.isHovering;(c||e)&&(a.features=b,c&&c(a)),e&&cO.call(this,"onMouseEnter",a),h&&cO.call(this,"onMouseLeave",a),(e||h)&&this.setState({isHovering:d})}}function cS(b){var c=this.props,d=c.onClick,f=c.onNativeClick,g=c.onDblClick,h=c.doubleClickZoom,a=[],e=g||h;switch(b.type){case"anyclick":a.push(f),e||a.push(d);break;case"click":e&&a.push(d)}(a=a.filter(Boolean)).length&&((b=cM.call(this,b)).features=cN.call(this,b.point),a.forEach(function(a){return a(b)}))}var m=(0,c.forwardRef)(function(b,h){var i,t,f=(0,c.useContext)(bJ),u=(0,c.useMemo)(function(){return b.controller||new Z},[]),v=(0,c.useMemo)(function(){return new cD(null,{touchAction:b.touchAction,recognizerOptions:b.eventRecognizerOptions})},[]),g=(0,c.useRef)(null),e=(0,c.useRef)(null),a=(0,c.useRef)({width:0,height:0,state:{isHovering:!1,isDragging:!1}}).current;a.props=b,a.map=e.current&&e.current.getMap(),a.setState=function(c){a.state=cL(cL({},a.state),c),g.current.style.cursor=b.getCursor(a.state)};var j=!0,k=function(b,c,d){if(j){i=[b,c,d];return}var e=a.props,f=e.onViewStateChange,g=e.onViewportChange;Object.defineProperty(b,"position",{get:function(){return[0,0,bL(a.map,b)]}}),f&&f({viewState:b,interactionState:c,oldViewState:d}),g&&g(b,c,d)};(0,c.useImperativeHandle)(h,function(){var a;return{getMap:(a=e).current&&a.current.getMap,queryRenderedFeatures:a.current&&a.current.queryRenderedFeatures}},[]);var d=(0,c.useMemo)(function(){return cL(cL({},f),{},{eventManager:v,container:f.container||g.current})},[f,g.current]);d.onViewportChange=k,d.viewport=f.viewport||bP(a),a.viewport=d.viewport;var w=function(b){var c=b.isDragging,d=void 0!==c&&c;if(d!==a.state.isDragging&&a.setState({isDragging:d}),j){t=b;return}var e=a.props.onInteractionStateChange;e&&e(b)},l=function(){a.width&&a.height&&u.setOptions(cL(cL(cL({},a.props),a.props.viewState),{},{isInteractive:Boolean(a.props.onViewStateChange||a.props.onViewportChange),onViewportChange:k,onStateChange:w,eventManager:v,width:a.width,height:a.height}))},m=function(b){var c=b.width,d=b.height;a.width=c,a.height=d,l(),a.props.onResize({width:c,height:d})};(0,c.useEffect)(function(){return v.setElement(g.current),v.on({pointerdown:cP.bind(a),pointermove:cR.bind(a),pointerup:cQ.bind(a),pointerleave:cO.bind(a,"onMouseOut"),click:cS.bind(a),anyclick:cS.bind(a),dblclick:cO.bind(a,"onDblClick"),wheel:cO.bind(a,"onWheel"),contextmenu:cO.bind(a,"onContextMenu")}),function(){v.destroy()}},[]),bK(function(){if(i){var a;k.apply(void 0,function(a){if(Array.isArray(a))return ax(a)}(a=i)||function(a){if("undefined"!=typeof Symbol&&null!=a[Symbol.iterator]||null!=a["@@iterator"])return Array.from(a)}(a)||ay(a)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}())}t&&w(t)}),l();var n=b.width,o=b.height,p=b.style,r=b.getCursor,s=(0,c.useMemo)(function(){return cL(cL({position:"relative"},p),{},{width:n,height:o,cursor:r(a.state)})},[p,n,o,r,a.state]);return i&&a._child||(a._child=c.createElement(bI,{value:d},c.createElement("div",{key:"event-canvas",ref:g,style:s},c.createElement(q,aw({},b,{width:"100%",height:"100%",style:null,onResize:m,ref:e}))))),j=!1,a._child});m.supported=q.supported,m.propTypes=$,m.defaultProps=_;var cT=m;function cU(b,a){if(b===a)return!0;if(!b||!a)return!1;if(Array.isArray(b)){if(!Array.isArray(a)||b.length!==a.length)return!1;for(var c=0;c prop: ".concat(e))}}(d,a,f.current):d=function(a,c,d){if(a.style&&a.style._loaded){var b=function(c){for(var a=1;a=0||(d[a]=c[a]);return d}(a,d);if(Object.getOwnPropertySymbols){var f=Object.getOwnPropertySymbols(a);for(c=0;c=0)&&Object.prototype.propertyIsEnumerable.call(a,b)&&(e[b]=a[b])}return e}(d,["layout","paint","filter","minzoom","maxzoom","beforeId"]);if(p!==a.beforeId&&b.moveLayer(c,p),e!==a.layout){var q=a.layout||{};for(var g in e)cU(e[g],q[g])||b.setLayoutProperty(c,g,e[g]);for(var r in q)e.hasOwnProperty(r)||b.setLayoutProperty(c,r,void 0)}if(f!==a.paint){var s=a.paint||{};for(var h in f)cU(f[h],s[h])||b.setPaintProperty(c,h,f[h]);for(var t in s)f.hasOwnProperty(t)||b.setPaintProperty(c,t,void 0)}for(var i in cU(m,a.filter)||b.setFilter(c,m),(n!==a.minzoom||o!==a.maxzoom)&&b.setLayerZoomRange(c,n,o),j)cU(j[i],a[i])||b.setLayerProperty(c,i,j[i])}(c,d,a,b)}catch(e){console.warn(e)}}(a,d,b,e.current):function(a,d,b){if(a.style&&a.style._loaded){var c=cY(cY({},b),{},{id:d});delete c.beforeId,a.addLayer(c,b.beforeId)}}(a,d,b),e.current=b,null}).propTypes=ab;var f={captureScroll:!1,captureDrag:!0,captureClick:!0,captureDoubleClick:!0,capturePointerMove:!1},d={captureScroll:a.bool,captureDrag:a.bool,captureClick:a.bool,captureDoubleClick:a.bool,capturePointerMove:a.bool};function c$(){var d=arguments.length>0&& void 0!==arguments[0]?arguments[0]:{},a=(0,c.useContext)(bJ),e=(0,c.useRef)(null),f=(0,c.useRef)({props:d,state:{},context:a,containerRef:e}),b=f.current;return b.props=d,b.context=a,(0,c.useEffect)(function(){return function(a){var b=a.containerRef.current,c=a.context.eventManager;if(b&&c){var d={wheel:function(c){var b=a.props;b.captureScroll&&c.stopPropagation(),b.onScroll&&b.onScroll(c,a)},panstart:function(c){var b=a.props;b.captureDrag&&c.stopPropagation(),b.onDragStart&&b.onDragStart(c,a)},anyclick:function(c){var b=a.props;b.captureClick&&c.stopPropagation(),b.onNativeClick&&b.onNativeClick(c,a)},click:function(c){var b=a.props;b.captureClick&&c.stopPropagation(),b.onClick&&b.onClick(c,a)},dblclick:function(c){var b=a.props;b.captureDoubleClick&&c.stopPropagation(),b.onDoubleClick&&b.onDoubleClick(c,a)},pointermove:function(c){var b=a.props;b.capturePointerMove&&c.stopPropagation(),b.onPointerMove&&b.onPointerMove(c,a)}};return c.watch(d,b),function(){c.off(d)}}}(b)},[a.eventManager]),b}function c_(b){var a=b.instance,c=c$(b),d=c.context,e=c.containerRef;return a._context=d,a._containerRef=e,a._render()}var H=function(b){bV(a,b);var d,e,f=(d=a,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(a){return!1}}(),function(){var a,b=bY(d);if(e){var c=bY(this).constructor;a=Reflect.construct(b,arguments,c)}else a=b.apply(this,arguments);return bX(this,a)});function a(){var b;bk(this,a);for(var e=arguments.length,h=new Array(e),d=0;d2&& void 0!==arguments[2]?arguments[2]:"x";if(null===a)return b;var c="x"===d?a.offsetWidth:a.offsetHeight;return c6(b/100*c)/c*100};function c8(c,d){var a=Object.keys(c);if(Object.getOwnPropertySymbols){var b=Object.getOwnPropertySymbols(c);d&&(b=b.filter(function(a){return Object.getOwnPropertyDescriptor(c,a).enumerable})),a.push.apply(a,b)}return a}var ae=Object.assign({},ac,{className:a.string,longitude:a.number.isRequired,latitude:a.number.isRequired,style:a.object}),af=Object.assign({},ad,{className:""});function t(b){var d,j,e,k,f,l,m,a,h=(d=b,e=(j=aA((0,c.useState)(null),2))[0],k=j[1],f=aA((0,c.useState)(null),2),l=f[0],m=f[1],a=c$(c1(c1({},d),{},{onDragStart:c4})),a.callbacks=d,a.state.dragPos=e,a.state.setDragPos=k,a.state.dragOffset=l,a.state.setDragOffset=m,(0,c.useEffect)(function(){return function(a){var b=a.context.eventManager;if(b&&a.state.dragPos){var c={panmove:function(b){return function(b,a){var h=a.props,c=a.callbacks,d=a.state,i=a.context;b.stopPropagation();var e=c2(b);d.setDragPos(e);var f=d.dragOffset;if(c.onDrag&&f){var g=Object.assign({},b);g.lngLat=c3(e,f,h,i),c.onDrag(g)}}(b,a)},panend:function(b){return function(c,a){var h=a.props,d=a.callbacks,b=a.state,i=a.context;c.stopPropagation();var e=b.dragPos,f=b.dragOffset;if(b.setDragPos(null),b.setDragOffset(null),d.onDragEnd&&e&&f){var g=Object.assign({},c);g.lngLat=c3(e,f,h,i),d.onDragEnd(g)}}(b,a)},pancancel:function(d){var c,b;return c=d,b=a.state,void(c.stopPropagation(),b.setDragPos(null),b.setDragOffset(null))}};return b.watch(c),function(){b.off(c)}}}(a)},[a.context.eventManager,Boolean(e)]),a),o=h.state,p=h.containerRef,q=b.children,r=b.className,s=b.draggable,A=b.style,t=o.dragPos,u=function(b){var a=b.props,e=b.state,f=b.context,g=a.longitude,h=a.latitude,j=a.offsetLeft,k=a.offsetTop,c=e.dragPos,d=e.dragOffset,l=f.viewport,m=f.map;if(c&&d)return[c[0]+d[0],c[1]+d[1]];var n=bL(m,{longitude:g,latitude:h}),i=aA(l.project([g,h,n]),2),o=i[0],p=i[1];return[o+=j,p+=k]}(h),n=aA(u,2),v=n[0],w=n[1],x="translate(".concat(c6(v),"px, ").concat(c6(w),"px)"),y=s?t?"grabbing":"grab":"auto",z=(0,c.useMemo)(function(){var a=function(c){for(var a=1;a0){var t=b,u=e;for(b=0;b<=1;b+=.5)k=(i=n-b*h)+h,e=Math.max(0,d-i)+Math.max(0,k-p+d),e0){var w=a,x=f;for(a=0;a<=1;a+=v)l=(j=m-a*g)+g,f=Math.max(0,d-j)+Math.max(0,l-o+d),f1||h< -1||f<0||f>p.width||g<0||g>p.height?i.display="none":i.zIndex=Math.floor((1-h)/2*1e5)),i),S=(0,c.useCallback)(function(b){t.props.onClose();var a=t.context.eventManager;a&&a.once("click",function(a){return a.stopPropagation()},b.target)},[]);return c.createElement("div",{className:"mapboxgl-popup mapboxgl-popup-anchor-".concat(L," ").concat(N),style:R,ref:u},c.createElement("div",{key:"tip",className:"mapboxgl-popup-tip",style:{borderWidth:O}}),c.createElement("div",{key:"content",ref:j,className:"mapboxgl-popup-content"},P&&c.createElement("button",{key:"close-button",className:"mapboxgl-popup-close-button",type:"button",onClick:S},"\xd7"),Q))}function da(c,d){var a=Object.keys(c);if(Object.getOwnPropertySymbols){var b=Object.getOwnPropertySymbols(c);d&&(b=b.filter(function(a){return Object.getOwnPropertyDescriptor(c,a).enumerable})),a.push.apply(a,b)}return a}u.propTypes=ag,u.defaultProps=ah,c.memo(u);var ai=Object.assign({},d,{toggleLabel:a.string,className:a.string,style:a.object,compact:a.bool,customAttribution:a.oneOfType([a.string,a.arrayOf(a.string)])}),aj=Object.assign({},f,{className:"",toggleLabel:"Toggle Attribution"});function v(a){var b=c$(a),d=b.context,i=b.containerRef,j=(0,c.useRef)(null),e=aA((0,c.useState)(!1),2),f=e[0],m=e[1];(0,c.useEffect)(function(){var h,e,c,f,g,b;return d.map&&(h=(e={customAttribution:a.customAttribution},c=d.map,f=i.current,g=j.current,(b=new(A()).AttributionControl(e))._map=c,b._container=f,b._innerContainer=g,b._updateAttributions(),b._updateEditLink(),c.on("styledata",b._updateData),c.on("sourcedata",b._updateData),b)),function(){var a;return h&&void((a=h)._map.off("styledata",a._updateData),a._map.off("sourcedata",a._updateData))}},[d.map]);var h=void 0===a.compact?d.viewport.width<=640:a.compact;(0,c.useEffect)(function(){!h&&f&&m(!1)},[h]);var k=(0,c.useCallback)(function(){return m(function(a){return!a})},[]),l=(0,c.useMemo)(function(){return function(c){for(var a=1;ac)return 1}return 0}(b.map.version,"1.6.0")>=0?2:1:2},[b.map]),f=b.viewport.bearing,d={transform:"rotate(".concat(-f,"deg)")},2===e?c.createElement("span",{className:"mapboxgl-ctrl-icon","aria-hidden":"true",style:d}):c.createElement("span",{className:"mapboxgl-ctrl-compass-arrow",style:d})))))}function di(c,d){var a=Object.keys(c);if(Object.getOwnPropertySymbols){var b=Object.getOwnPropertySymbols(c);d&&(b=b.filter(function(a){return Object.getOwnPropertyDescriptor(c,a).enumerable})),a.push.apply(a,b)}return a}y.propTypes=ao,y.defaultProps=ap,c.memo(y);var aq=Object.assign({},d,{className:a.string,style:a.object,maxWidth:a.number,unit:a.oneOf(["imperial","metric","nautical"])}),ar=Object.assign({},f,{className:"",maxWidth:100,unit:"metric"});function z(a){var d=c$(a),f=d.context,h=d.containerRef,e=aA((0,c.useState)(null),2),b=e[0],j=e[1];(0,c.useEffect)(function(){if(f.map){var a=new(A()).ScaleControl;a._map=f.map,a._container=h.current,j(a)}},[f.map]),b&&(b.options=a,b._onMove());var i=(0,c.useMemo)(function(){return function(c){for(var a=1;a 0) { @@ -3513,6 +3508,7 @@ } switch(domEventName){ case 'paste': + default: return null; case 'keypress': if (!(nativeEvent9 = nativeEvent).ctrlKey && !nativeEvent9.altKey && !nativeEvent9.metaKey || nativeEvent9.ctrlKey && nativeEvent9.altKey) { @@ -3522,8 +3518,6 @@ return null; case 'compositionend': return useFallbackCompositionData && !isUsingKoreanIME(nativeEvent) ? null : nativeEvent.data; - default: - return null; } }(domEventName10, nativeEvent8))) return null; var chars1, listeners = accumulateTwoPhaseListeners(targetInst, 'onBeforeInput'); @@ -4893,7 +4887,6 @@ break; } error1("Encountered two children with the same key, `%s`. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted \u2014 the behavior is unsupported and could change in a future version.", key); - break; } return knownKeys; } @@ -4906,22 +4899,16 @@ return placeSingleChild(function(returnFiber, currentFirstChild, element, lanes) { for(var key = element.key, child = currentFirstChild; null !== child;){ if (child.key === key) { - switch(child.tag){ - case 7: - if (element.type === REACT_FRAGMENT_TYPE) { - deleteRemainingChildren(returnFiber, child.sibling); - var existing = useFiber(child, element.props.children); - return existing.return = returnFiber, existing._debugSource = element._source, existing._debugOwner = element._owner, existing; - } - break; - case 22: - default: - if (child.elementType === element.type || isCompatibleFamilyForHotReloading(child, element)) { - deleteRemainingChildren(returnFiber, child.sibling); - var _existing3 = useFiber(child, element.props); - return _existing3.ref = coerceRef(returnFiber, child, element), _existing3.return = returnFiber, _existing3._debugSource = element._source, _existing3._debugOwner = element._owner, _existing3; - } - break; + if (7 === child.tag) { + if (element.type === REACT_FRAGMENT_TYPE) { + deleteRemainingChildren(returnFiber, child.sibling); + var existing = useFiber(child, element.props.children); + return existing.return = returnFiber, existing._debugSource = element._source, existing._debugOwner = element._owner, existing; + } + } else if (child.elementType === element.type || isCompatibleFamilyForHotReloading(child, element)) { + deleteRemainingChildren(returnFiber, child.sibling); + var _existing3 = useFiber(child, element.props); + return _existing3.ref = coerceRef(returnFiber, child, element), _existing3.return = returnFiber, _existing3._debugSource = element._source, _existing3._debugOwner = element._owner, _existing3; } deleteRemainingChildren(returnFiber, child); break; @@ -5061,7 +5048,6 @@ default: var container = 8 === nodeType ? rootContainerInstance.parentNode : rootContainerInstance; namespace = getChildNamespace(container.namespaceURI || null, type = container.tagName); - break; } return { namespace: namespace, @@ -5131,7 +5117,6 @@ break; case 5: returnFiber.type, parentProps = returnFiber.memoizedProps, parentInstance = returnFiber.stateNode, instance4 = instance, !0 !== parentProps[SUPPRESS_HYDRATION_WARNING$1] && (1 === instance4.nodeType ? warnForDeletedHydratableElement(parentInstance, instance4) : 8 === instance4.nodeType || warnForDeletedHydratableText(parentInstance, instance4)); - break; } var parentContainer, instance3, parentProps, parentInstance, instance4, childToDelete = createFiberFromHostInstanceForDeletion(); childToDelete.stateNode = instance, childToDelete.return = returnFiber, childToDelete.flags = Deletion, null !== returnFiber.lastEffect ? (returnFiber.lastEffect.nextEffect = childToDelete, returnFiber.lastEffect = childToDelete) : returnFiber.firstEffect = returnFiber.lastEffect = childToDelete; @@ -5147,7 +5132,6 @@ break; case 6: warnForInsertedHydratedText(parentContainer, fiber.pendingProps); - break; } break; case 5: @@ -5164,7 +5148,6 @@ break; case 13: parentProps[SUPPRESS_HYDRATION_WARNING$1]; - break; } break; default: @@ -5183,8 +5166,6 @@ var instance6, text = fiber.pendingProps, textInstance = (instance6 = nextInstance, '' === text || 3 !== instance6.nodeType ? null : instance6); if (null !== textInstance) return fiber.stateNode = textInstance, !0; return !1; - case 13: - return !1; default: return !1; } @@ -6597,7 +6578,6 @@ break; default: error1('"%s" is not a supported revealOrder on . Did you mean "together", "forwards" or "backwards"?', revealOrder); - break; } else error1('%s is not a supported value for revealOrder on . Did you mean "together", "forwards" or "backwards"?', revealOrder); } @@ -6916,9 +6896,7 @@ case 19: return updateSuspenseListComponent(current13, workInProgress16, renderLanes12); case 20: - break; case 21: - break; case 22: break; case 23: @@ -6943,7 +6921,6 @@ case 'collapsed': for(var _tailNode = renderState.tail, _lastTailNode = null; null !== _tailNode;)null !== _tailNode.alternate && (_lastTailNode = _tailNode), _tailNode = _tailNode.sibling; null === _lastTailNode ? hasRenderedATailFallback || null === renderState.tail ? renderState.tail = null : renderState.tail.sibling = null : _lastTailNode.sibling = null; - break; } } function completeWork(current, workInProgress, renderLanes) { @@ -6961,6 +6938,7 @@ case 14: return null; case 1: + case 17: return isContextProvider(workInProgress.type) && popContext(workInProgress), null; case 3: popHostContainer(workInProgress), popTopLevelContextObject(workInProgress), resetWorkInProgressVersions(); @@ -7012,18 +6990,14 @@ break; case 'textarea': initWrapperState$2(domElement, rawProps), listenToNonDelegatedEvent('invalid', domElement); - break; } assertValidProps(tag, rawProps), extraAttributeNames = new Set(); for(var attributes = domElement.attributes, _i = 0; _i < attributes.length; _i++){ var name = attributes[_i].name.toLowerCase(); switch(name){ case 'data-reactroot': - break; case 'value': - break; case 'checked': - break; case 'selected': break; default: @@ -7085,7 +7059,6 @@ break; default: 'function' == typeof rawProps.onClick && trapClickOnNonInteractiveElement(domElement); - break; } return updatePayload; }(instance, type9, props7, hostContext2.namespace)), fiber.updateQueue = updatePayload1, null !== updatePayload1 && markUpdate(workInProgress); @@ -7174,7 +7147,6 @@ break; default: 'function' == typeof props13.onClick && trapClickOnNonInteractiveElement(domElement3); - break; } }(instance7, type10 = type11, props8 = newProps, rootContainerInstance), shouldAutoFocusHostComponent(type10, props8) && markUpdate(workInProgress); } @@ -7201,7 +7173,6 @@ returnFiber.type; var parentProps, textInstance2, text3, parentProps3 = returnFiber.memoizedProps; returnFiber.stateNode, parentProps = parentProps3, textInstance2 = textInstance1, text3 = textContent, !0 !== parentProps[SUPPRESS_HYDRATION_WARNING$1] && warnForUnmatchedText(textInstance2, text3); - break; } } return shouldUpdate; @@ -7218,8 +7189,6 @@ return popHostContainer(workInProgress), updateHostContainer(workInProgress), null === current && listenToAllSupportedEvents(workInProgress.stateNode.containerInfo), null; case 10: return popProvider(workInProgress), null; - case 17: - return isContextProvider(workInProgress.type) && popContext(workInProgress), null; case 19: popSuspenseContext(workInProgress); var renderState = workInProgress.memoizedState; @@ -7265,9 +7234,7 @@ } return null; case 20: - break; case 21: - break; case 22: break; case 23: @@ -7327,8 +7294,6 @@ popHostContainer(interruptedWork); break; case 13: - popSuspenseContext(interruptedWork); - break; case 19: popSuspenseContext(interruptedWork); break; @@ -7338,7 +7303,6 @@ case 23: case 24: popRenderLanes(interruptedWork); - break; } } function createCapturedValue(value, source) { @@ -7403,7 +7367,6 @@ break; default: lastProps = lastRawProps, nextProps = nextRawProps, 'function' != typeof lastProps.onClick && 'function' == typeof nextProps.onClick && trapClickOnNonInteractiveElement(domElement); - break; } assertValidProps(tag, nextProps); var styleUpdates1 = null; @@ -7541,7 +7504,6 @@ enqueueCapturedUpdate(workInProgress, _update2); return; } - break; } workInProgress = workInProgress.return; }while (null !== workInProgress) @@ -7564,6 +7526,10 @@ case 11: case 15: case 22: + case 5: + case 6: + case 4: + case 17: return; case 1: if (256 & finishedWork.flags && null !== current) { @@ -7576,11 +7542,6 @@ case 3: 256 & finishedWork.flags && clearContainer(finishedWork.stateNode.containerInfo); return; - case 5: - case 6: - case 4: - case 17: - return; } throw Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue."); } @@ -7633,11 +7594,8 @@ var _instance = null; if (null !== finishedWork1.child) switch(finishedWork1.child.tag){ case 5: - _instance = finishedWork1.child.stateNode; - break; case 1: _instance = finishedWork1.child.stateNode; - break; } commitUpdateQueue(finishedWork1, _updateQueue, _instance); } @@ -7650,8 +7608,13 @@ } return; case 6: - return; case 4: + case 19: + case 17: + case 20: + case 21: + case 23: + case 24: return; case 12: var _finishedWork$memoize2 = finishedWork1.memoizedProps, onRender = (_finishedWork$memoize2.onCommit, _finishedWork$memoize2.onRender); @@ -7662,13 +7625,6 @@ case 13: commitSuspenseHydrationCallbacks(finishedRoot, finishedWork1); return; - case 19: - case 17: - case 20: - case 21: - case 23: - case 24: - return; } throw Error("This unit of work tag should not have side-effects. This error is likely caused by a bug in React. Please file an issue."); } @@ -7697,14 +7653,7 @@ var ref = finishedWork.ref; if (null !== ref) { var instanceToUse, instance = finishedWork.stateNode; - switch(finishedWork.tag){ - case 5: - instanceToUse = instance; - break; - default: - instanceToUse = instance; - } - 'function' == typeof ref ? ref(instanceToUse) : (ref.hasOwnProperty('current') || error1("Unexpected ref object provided for %s. Use either a ref-setter function or React.createRef().", getComponentName(finishedWork.type)), ref.current = instanceToUse); + instanceToUse = (finishedWork.tag, instance), 'function' == typeof ref ? ref(instanceToUse) : (ref.hasOwnProperty('current') || error1("Unexpected ref object provided for %s. Use either a ref-setter function or React.createRef().", getComponentName(finishedWork.type)), ref.current = instanceToUse); } } function commitDetachRef(current) { @@ -7748,9 +7697,7 @@ unmountHostComponents(finishedRoot, current); return; case 20: - return; case 18: - return; case 21: return; } @@ -7788,12 +7735,9 @@ parent1 = parentStateNode, isContainer = !1; break; case 3: - parent1 = parentStateNode.containerInfo, isContainer = !0; - break; case 4: parent1 = parentStateNode.containerInfo, isContainer = !0; break; - case 20: default: throw Error("Invalid host parent fiber. This error is likely caused by a bug in React. Please file an issue."); } @@ -7855,8 +7799,6 @@ currentParent = parentStateNode, currentParentIsContainer = !1; break findParent; case 3: - currentParent = parentStateNode.containerInfo, currentParentIsContainer = !0; - break findParent; case 4: currentParent = parentStateNode.containerInfo, currentParentIsContainer = !0; break findParent; @@ -7910,6 +7852,8 @@ }(3, finishedWork2); return; case 1: + case 12: + case 17: return; case 5: var instance = finishedWork2.stateNode; @@ -7932,7 +7876,6 @@ break; case 'select': element = domElement8, props = nextRawProps, wasMultiple = (node = element)._wrapperState.wasMultiple, node._wrapperState.wasMultiple = !!props.multiple, value = props.value, null != value ? updateOptions(node, !!props.multiple, value, !1) : !!props.multiple !== wasMultiple && (null != props.defaultValue ? updateOptions(node, !!props.multiple, props.defaultValue, !0) : updateOptions(node, !!props.multiple, props.multiple ? [] : '', !1)); - break; } }(domElement6, updatePayload6, type, oldProps, newProps)); } @@ -7946,18 +7889,13 @@ var _root = finishedWork2.stateNode; _root.hydrate && (_root.hydrate = !1, retryIfBlockedOn(_root.containerInfo)); return; - case 12: - return; case 13: commitSuspenseComponent(finishedWork2), attachSuspenseRetryListeners(finishedWork2); return; case 19: attachSuspenseRetryListeners(finishedWork2); return; - case 17: - return; case 20: - break; case 21: break; case 23: @@ -8129,6 +8067,7 @@ case 1: throw Error("Root did not complete. This is a bug in React."); case 2: + case 5: commitRoot(root4); break; case 3: @@ -8164,9 +8103,6 @@ } commitRoot(root4); break; - case 5: - commitRoot(root4); - break; default: throw Error("Unknown root exit status."); } @@ -8526,7 +8462,6 @@ break; case Deletion: commitDeletion(root, nextEffect); - break; } resetCurrentFiber(), nextEffect = nextEffect.nextEffect; } @@ -8725,7 +8660,6 @@ break; case 1: didWarnAboutUpdateInRender || (error1("Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state."), didWarnAboutUpdateInRender = !0); - break; } } didWarnAboutUpdateInRenderForAnotherComponent = new Set(); @@ -8897,7 +8831,6 @@ break; case 11: candidateType = type.render; - break; } if (null === resolveFamily) throw new Error('Expected resolveFamily to be set during hot reload.'); var needsRender = !1, needsRemount = !1; @@ -8917,7 +8850,6 @@ break; case 11: candidateType = type.render; - break; } var didMatch = !1; null !== candidateType && types.has(candidateType) && (didMatch = !0), didMatch ? findHostInstancesForFiberShallowly(fiber, hostInstances) : null !== child && findHostInstancesForMatchingFibersRecursively(child, types, hostInstances), null !== sibling && findHostInstancesForMatchingFibersRecursively(sibling, types, hostInstances); @@ -8929,8 +8861,6 @@ hostInstances.add(node.stateNode); return; case 4: - hostInstances.add(node.stateNode.containerInfo); - return; case 3: hostInstances.add(node.stateNode.containerInfo); return; @@ -9010,7 +8940,6 @@ break; case 11: workInProgress.type = resolveForwardRefForHotReloading(current.type); - break; } return workInProgress; } @@ -9051,7 +8980,6 @@ return createFiberFromOffscreen(pendingProps, mode, lanes, key); case REACT_LEGACY_HIDDEN_TYPE: return createFiberFromLegacyHidden(pendingProps, mode, lanes, key); - case REACT_SCOPE_TYPE: default: if ('object' == typeof type && null !== type) switch(type.$$typeof){ case REACT_PROVIDER_TYPE: @@ -9144,7 +9072,6 @@ break; case 0: this._debugRootType = 'createLegacyRoot()'; - break; } } function registerMutableSourceForHydration(root, mutableSource) { @@ -9175,7 +9102,6 @@ return node.stateNode.context; case 1: if (isContextProvider(node.type)) return node.stateNode.__reactInternalMemoizedMergedChildContext; - break; } node = node.return; }while (null !== node) @@ -9195,13 +9121,7 @@ } function getPublicRootInstance(container) { var containerFiber = container.current; - if (!containerFiber.child) return null; - switch(containerFiber.child.tag){ - case 5: - return containerFiber.child.stateNode; - default: - return containerFiber.child.stateNode; - } + return containerFiber.child ? (containerFiber.child.tag, containerFiber.child.stateNode) : null; } function markRetryLaneImpl(fiber, retryLane) { var a, b, suspenseState = fiber.memoizedState; diff --git a/crates/swc_ecma_minifier/tests/single-pass/terser/1/output.js b/crates/swc_ecma_minifier/tests/single-pass/terser/1/output.js index ff131235759a..e779f276440f 100644 --- a/crates/swc_ecma_minifier/tests/single-pass/terser/1/output.js +++ b/crates/swc_ecma_minifier/tests/single-pass/terser/1/output.js @@ -7,47 +7,45 @@ def_optimize(AST_Call, function(self, compressor) { }).optimize(compressor); } if (is_undeclared_ref(exp)) exp.name; - else if (exp instanceof AST_Dot) switch(exp.property){ - case "join": - if (exp.expression instanceof AST_Array) { - EXIT: if (!(self.args.length > 0) || (separator = self.args[0].evaluate(compressor)) !== self.args[0]) { - for(var separator, first, elements = [], consts = [], i = 0, len = exp.expression.elements.length; i < len; i++){ - var el = exp.expression.elements[i]; - if (el instanceof AST_Expansion) break EXIT; - var value = el.evaluate(compressor); - value !== el ? consts.push(value) : (consts.length > 0 && (elements.push(make_node(AST_String, self, { - value: consts.join(separator) - })), consts.length = 0), elements.push(el)); - } - if (consts.length > 0 && elements.push(make_node(AST_String, self, { + else if (exp instanceof AST_Dot && "join" === exp.property) { + if (exp.expression instanceof AST_Array) { + EXIT: if (!(self.args.length > 0) || (separator = self.args[0].evaluate(compressor)) !== self.args[0]) { + for(var separator, first, elements = [], consts = [], i = 0, len = exp.expression.elements.length; i < len; i++){ + var el = exp.expression.elements[i]; + if (el instanceof AST_Expansion) break EXIT; + var value = el.evaluate(compressor); + value !== el ? consts.push(value) : (consts.length > 0 && (elements.push(make_node(AST_String, self, { value: consts.join(separator) - })), 0 == elements.length) return make_node(AST_String, self, { - value: "" + })), consts.length = 0), elements.push(el)); + } + if (consts.length > 0 && elements.push(make_node(AST_String, self, { + value: consts.join(separator) + })), 0 == elements.length) return make_node(AST_String, self, { + value: "" + }); + if (1 == elements.length) { + if (elements[0].is_string(compressor)) return elements[0]; + return make_node(AST_Binary, elements[0], { + operator: "+", + left: make_node(AST_String, self, { + value: "" + }), + right: elements[0] }); - if (1 == elements.length) { - if (elements[0].is_string(compressor)) return elements[0]; - return make_node(AST_Binary, elements[0], { - operator: "+", - left: make_node(AST_String, self, { - value: "" - }), - right: elements[0] - }); - } - if ("" == separator) return first = elements[0].is_string(compressor) || elements[1].is_string(compressor) ? elements.shift() : make_node(AST_String, self, { - value: "" - }), elements.reduce(function(prev, el) { - return make_node(AST_Binary, el, { - operator: "+", - left: prev, - right: el - }); - }, first).optimize(compressor); - var node = self.clone(); - return node.expression = node.expression.clone(), node.expression.expression = node.expression.expression.clone(), node.expression.expression.elements = elements, best_of(compressor, self, node); } + if ("" == separator) return first = elements[0].is_string(compressor) || elements[1].is_string(compressor) ? elements.shift() : make_node(AST_String, self, { + value: "" + }), elements.reduce(function(prev, el) { + return make_node(AST_Binary, el, { + operator: "+", + left: prev, + right: el + }); + }, first).optimize(compressor); + var node = self.clone(); + return node.expression = node.expression.clone(), node.expression.expression = node.expression.expression.clone(), node.expression.expression.elements = elements, best_of(compressor, self, node); } - break; + } } } }); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/reduce_vars/issue_1670_6/output.js b/crates/swc_ecma_minifier/tests/terser/compress/reduce_vars/issue_1670_6/output.js index 9df228ffa19a..9f4edfadb505 100644 --- a/crates/swc_ecma_minifier/tests/terser/compress/reduce_vars/issue_1670_6/output.js +++ b/crates/swc_ecma_minifier/tests/terser/compress/reduce_vars/issue_1670_6/output.js @@ -1,9 +1,4 @@ -(function (a) { - switch (1) { - case (a = 1): - console.log(a); - break; - default: - console.log(2); - } +(function(a) { + if (1 === (a = 1)) console.log(a); + else console.log(2); })(1); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_case/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_case/output.js index 27ad6466c347..a3a043e13da0 100644 --- a/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_case/output.js +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_case/output.js @@ -1,4 +1 @@ -switch (foo) { - case "bar": - baz(); -} +if ("bar" === foo) baz(); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_case_2/analysis-snapshot.rust-debug b/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_case_2/analysis-snapshot.rust-debug new file mode 100644 index 000000000000..a3f0d8906ff4 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_case_2/analysis-snapshot.rust-debug @@ -0,0 +1,118 @@ +TestSnapshot { + vars: [ + ( + ( + Atom('bar' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('foo' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('moo' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ], +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_case_2/config.json b/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_case_2/config.json new file mode 100644 index 000000000000..7c685532f125 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_case_2/config.json @@ -0,0 +1,4 @@ +{ + "dead_code": true, + "switches": true +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_case_2/input.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_case_2/input.js new file mode 100644 index 000000000000..d2dc51796c99 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_case_2/input.js @@ -0,0 +1,9 @@ +switch (foo) { + case "bar": + bar(); + break; + case "moo": + case moo: + case "baz": + break; +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_case_2/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_case_2/output.js new file mode 100644 index 000000000000..5b45fc5df4d5 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_case_2/output.js @@ -0,0 +1 @@ +if ("bar" === foo) bar(); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_case_2/output.terser.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_case_2/output.terser.js new file mode 100644 index 000000000000..67bc9b72b4a8 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_case_2/output.terser.js @@ -0,0 +1,6 @@ +switch (foo) { + case "bar": + bar(); + case "moo": + case moo: +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_default_1/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_default_1/output.js index 27ad6466c347..a3a043e13da0 100644 --- a/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_default_1/output.js +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_default_1/output.js @@ -1,4 +1 @@ -switch (foo) { - case "bar": - baz(); -} +if ("bar" === foo) baz(); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_default_2/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_default_2/output.js index 27ad6466c347..a3a043e13da0 100644 --- a/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_default_2/output.js +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/drop_default_2/output.js @@ -1,4 +1 @@ -switch (foo) { - case "bar": - baz(); -} +if ("bar" === foo) baz(); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch/analysis-snapshot.rust-debug b/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch/analysis-snapshot.rust-debug new file mode 100644 index 000000000000..e863fb5028a4 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch/analysis-snapshot.rust-debug @@ -0,0 +1,80 @@ +TestSnapshot { + vars: [ + ( + ( + Atom('console' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: true, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('id' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ], +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch/config.json b/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch/config.json new file mode 100644 index 000000000000..c39c8d07f6c9 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch/config.json @@ -0,0 +1,4 @@ +{ + "switches": true, + "dead_code": true +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch/input.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch/input.js new file mode 100644 index 000000000000..d3913948a5f2 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch/input.js @@ -0,0 +1,7 @@ +switch (id(123)) { + case 1: + case 2: + case 3: + default: + console.log("PASS"); +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch/output.js new file mode 100644 index 000000000000..5cf989a75381 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch/output.js @@ -0,0 +1,2 @@ +id(123); +console.log("PASS"); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch/output.terser.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch/output.terser.js new file mode 100644 index 000000000000..5cf989a75381 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch/output.terser.js @@ -0,0 +1,2 @@ +id(123); +console.log("PASS"); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch_2/analysis-snapshot.rust-debug b/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch_2/analysis-snapshot.rust-debug new file mode 100644 index 000000000000..e863fb5028a4 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch_2/analysis-snapshot.rust-debug @@ -0,0 +1,80 @@ +TestSnapshot { + vars: [ + ( + ( + Atom('console' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: true, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('id' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ], +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch_2/config.json b/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch_2/config.json new file mode 100644 index 000000000000..c39c8d07f6c9 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch_2/config.json @@ -0,0 +1,4 @@ +{ + "switches": true, + "dead_code": true +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch_2/input.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch_2/input.js new file mode 100644 index 000000000000..43893cee675c --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch_2/input.js @@ -0,0 +1,7 @@ +switch (id(123)) { + case 1: + "no side effect"; + case 1: + default: + console.log("PASS"); +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch_2/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch_2/output.js new file mode 100644 index 000000000000..7f8744952643 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch_2/output.js @@ -0,0 +1,2 @@ +if (1 === id(123)) "no side effect"; +console.log("PASS"); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch_2/output.terser.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch_2/output.terser.js new file mode 100644 index 000000000000..5cf989a75381 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/gut_entire_switch_2/output.terser.js @@ -0,0 +1,2 @@ +id(123); +console.log("PASS"); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else/analysis-snapshot.rust-debug b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else/analysis-snapshot.rust-debug new file mode 100644 index 000000000000..2c808e8807e9 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else/analysis-snapshot.rust-debug @@ -0,0 +1,118 @@ +TestSnapshot { + vars: [ + ( + ( + Atom('bar' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('foo' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('other' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ], +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else/config.json b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else/config.json new file mode 100644 index 000000000000..7c685532f125 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else/config.json @@ -0,0 +1,4 @@ +{ + "dead_code": true, + "switches": true +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else/input.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else/input.js new file mode 100644 index 000000000000..c727eb4e448f --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else/input.js @@ -0,0 +1,7 @@ +switch (foo) { + case "bar": + bar(); + break; + default: + other(); +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else/output.js new file mode 100644 index 000000000000..8e0bd39ab587 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else/output.js @@ -0,0 +1,2 @@ +if ("bar" === foo) bar(); +else other(); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else/output.terser.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else/output.terser.js new file mode 100644 index 000000000000..8e0bd39ab587 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else/output.terser.js @@ -0,0 +1,2 @@ +if ("bar" === foo) bar(); +else other(); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else2/analysis-snapshot.rust-debug b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else2/analysis-snapshot.rust-debug new file mode 100644 index 000000000000..2c808e8807e9 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else2/analysis-snapshot.rust-debug @@ -0,0 +1,118 @@ +TestSnapshot { + vars: [ + ( + ( + Atom('bar' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('foo' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('other' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ], +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else2/config.json b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else2/config.json new file mode 100644 index 000000000000..7c685532f125 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else2/config.json @@ -0,0 +1,4 @@ +{ + "dead_code": true, + "switches": true +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else2/input.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else2/input.js new file mode 100644 index 000000000000..c3f919d9a444 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else2/input.js @@ -0,0 +1,6 @@ +switch (foo) { + case "bar": + bar(); + default: + other(); +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else2/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else2/output.js new file mode 100644 index 000000000000..ca79f1ea6acc --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else2/output.js @@ -0,0 +1,2 @@ +if ("bar" === foo) bar(); +other(); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else2/output.terser.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else2/output.terser.js new file mode 100644 index 000000000000..ca79f1ea6acc --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else2/output.terser.js @@ -0,0 +1,2 @@ +if ("bar" === foo) bar(); +other(); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else3/analysis-snapshot.rust-debug b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else3/analysis-snapshot.rust-debug new file mode 100644 index 000000000000..2c808e8807e9 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else3/analysis-snapshot.rust-debug @@ -0,0 +1,118 @@ +TestSnapshot { + vars: [ + ( + ( + Atom('bar' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('foo' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('other' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ], +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else3/config.json b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else3/config.json new file mode 100644 index 000000000000..7c685532f125 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else3/config.json @@ -0,0 +1,4 @@ +{ + "dead_code": true, + "switches": true +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else3/input.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else3/input.js new file mode 100644 index 000000000000..51668684e757 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else3/input.js @@ -0,0 +1,7 @@ +switch (foo) { + default: + other(); + break; + case "bar": + bar(); +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else3/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else3/output.js new file mode 100644 index 000000000000..8e0bd39ab587 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else3/output.js @@ -0,0 +1,2 @@ +if ("bar" === foo) bar(); +else other(); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else3/output.terser.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else3/output.terser.js new file mode 100644 index 000000000000..8e0bd39ab587 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else3/output.terser.js @@ -0,0 +1,2 @@ +if ("bar" === foo) bar(); +else other(); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else4/analysis-snapshot.rust-debug b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else4/analysis-snapshot.rust-debug new file mode 100644 index 000000000000..2c808e8807e9 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else4/analysis-snapshot.rust-debug @@ -0,0 +1,118 @@ +TestSnapshot { + vars: [ + ( + ( + Atom('bar' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('foo' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('other' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ], +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else4/config.json b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else4/config.json new file mode 100644 index 000000000000..7c685532f125 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else4/config.json @@ -0,0 +1,4 @@ +{ + "dead_code": true, + "switches": true +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else4/input.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else4/input.js new file mode 100644 index 000000000000..21fb9b647d25 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else4/input.js @@ -0,0 +1,6 @@ +switch (foo) { + default: + other(); + case "bar": + bar(); +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else4/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else4/output.js new file mode 100644 index 000000000000..861c3ce19443 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else4/output.js @@ -0,0 +1,2 @@ +if ("bar" !== foo) other(); +bar(); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else4/output.terser.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else4/output.terser.js new file mode 100644 index 000000000000..861c3ce19443 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else4/output.terser.js @@ -0,0 +1,2 @@ +if ("bar" !== foo) other(); +bar(); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else5/analysis-snapshot.rust-debug b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else5/analysis-snapshot.rust-debug new file mode 100644 index 000000000000..31593d33f01b --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else5/analysis-snapshot.rust-debug @@ -0,0 +1,80 @@ +TestSnapshot { + vars: [ + ( + ( + Atom('bar' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 2, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 2, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('other' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ], +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else5/config.json b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else5/config.json new file mode 100644 index 000000000000..592bd78fdf8c --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else5/config.json @@ -0,0 +1,5 @@ +{ + "dead_code": true, + "switches": true, + "evaluate": true +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else5/input.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else5/input.js new file mode 100644 index 000000000000..f3c3654b1428 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else5/input.js @@ -0,0 +1,7 @@ +switch (1) { + case bar: + bar(); + break; + case 1: + other(); +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else5/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else5/output.js new file mode 100644 index 000000000000..3ff0c5a96448 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else5/output.js @@ -0,0 +1,2 @@ +if (1 === bar) bar(); +else other(); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else5/output.terser.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else5/output.terser.js new file mode 100644 index 000000000000..be0116bee079 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else5/output.terser.js @@ -0,0 +1,5 @@ +if (1 === bar) bar(); +else { + 1; + other(); +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else6/analysis-snapshot.rust-debug b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else6/analysis-snapshot.rust-debug new file mode 100644 index 000000000000..31593d33f01b --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else6/analysis-snapshot.rust-debug @@ -0,0 +1,80 @@ +TestSnapshot { + vars: [ + ( + ( + Atom('bar' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 2, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 2, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('other' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ], +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else6/config.json b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else6/config.json new file mode 100644 index 000000000000..592bd78fdf8c --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else6/config.json @@ -0,0 +1,5 @@ +{ + "dead_code": true, + "switches": true, + "evaluate": true +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else6/input.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else6/input.js new file mode 100644 index 000000000000..d3b63c5579b0 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else6/input.js @@ -0,0 +1,6 @@ +switch (1) { + case bar: + bar(); + case 1: + other(); +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else6/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else6/output.js new file mode 100644 index 000000000000..8b487596170d --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else6/output.js @@ -0,0 +1,2 @@ +if (1 === bar) bar(); +other(); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else6/output.terser.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else6/output.terser.js new file mode 100644 index 000000000000..1300d6adcc71 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else6/output.terser.js @@ -0,0 +1,3 @@ +if (1 === bar) bar(); +1; +other(); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else7/analysis-snapshot.rust-debug b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else7/analysis-snapshot.rust-debug new file mode 100644 index 000000000000..2c808e8807e9 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else7/analysis-snapshot.rust-debug @@ -0,0 +1,118 @@ +TestSnapshot { + vars: [ + ( + ( + Atom('bar' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('foo' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('other' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ], +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else7/config.json b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else7/config.json new file mode 100644 index 000000000000..7c685532f125 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else7/config.json @@ -0,0 +1,4 @@ +{ + "dead_code": true, + "switches": true +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else7/input.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else7/input.js new file mode 100644 index 000000000000..cea593247136 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else7/input.js @@ -0,0 +1,7 @@ +switch (foo) { + case "bar": + break; + bar(); + default: + other(); +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else7/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else7/output.js new file mode 100644 index 000000000000..8a32dc8d5ff9 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else7/output.js @@ -0,0 +1 @@ +"bar" === foo || other(); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else7/output.terser.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else7/output.terser.js new file mode 100644 index 000000000000..63849f978001 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else7/output.terser.js @@ -0,0 +1,2 @@ +if ("bar" === foo); +else other(); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else8/analysis-snapshot.rust-debug b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else8/analysis-snapshot.rust-debug new file mode 100644 index 000000000000..3f4771abbb33 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else8/analysis-snapshot.rust-debug @@ -0,0 +1,118 @@ +TestSnapshot { + vars: [ + ( + ( + Atom('console' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: true, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('foo' type=inline), + #2, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: true, + declared_count: 1, + declared_as_fn_param: true, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: false, + is_fn_local: true, + used_by_nested_fn: true, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('test' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: true, + declared_count: 1, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 1, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: true, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: false, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: true, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ], +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else8/config.json b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else8/config.json new file mode 100644 index 000000000000..ee65e9fdc67e --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else8/config.json @@ -0,0 +1,3 @@ +{ + "defaults": true +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else8/input.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else8/input.js new file mode 100644 index 000000000000..9c4ccd6f9a9d --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else8/input.js @@ -0,0 +1,9 @@ +function test(foo) { + switch (foo) { + case "bar": + return "PASS"; + default: + return "FAIL"; + } +} +console.log(test("bar")); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else8/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else8/output.js new file mode 100644 index 000000000000..4a0cfa4e3318 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else8/output.js @@ -0,0 +1,4 @@ +function test(foo) { + return "bar" === foo ? "PASS" : "FAIL"; +} +console.log(test("bar")); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else8/output.terser.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else8/output.terser.js new file mode 100644 index 000000000000..4a0cfa4e3318 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/if_else8/output.terser.js @@ -0,0 +1,4 @@ +function test(foo) { + return "bar" === foo ? "PASS" : "FAIL"; +} +console.log(test("bar")); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_1/analysis-snapshot.rust-debug b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_1/analysis-snapshot.rust-debug new file mode 100644 index 000000000000..e905e161aa1f --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_1/analysis-snapshot.rust-debug @@ -0,0 +1,156 @@ +TestSnapshot { + vars: [ + ( + ( + Atom('console' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 2, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 2, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: true, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: true, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('definitely_true' type=dynamic), + #2, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: true, + declared_count: 1, + declared_as_fn_param: true, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: false, + is_fn_local: true, + used_by_nested_fn: true, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('maybe_true' type=dynamic), + #2, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: true, + declared_count: 1, + declared_as_fn_param: true, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: false, + is_fn_local: true, + used_by_nested_fn: true, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('test' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 2, + cond_init: false, + declared: true, + declared_count: 1, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 2, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: false, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: true, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ], +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_1/config.json b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_1/config.json new file mode 100644 index 000000000000..c39c8d07f6c9 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_1/config.json @@ -0,0 +1,4 @@ +{ + "switches": true, + "dead_code": true +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_1/input.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_1/input.js new file mode 100644 index 000000000000..dc11bff83493 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_1/input.js @@ -0,0 +1,13 @@ +function test(definitely_true, maybe_true) { + switch (true) { + case definitely_true: + default: + console.log("PASS"); + break; + case maybe_true: + console.log("FAIL"); + break; + } +} +test(true, false); +test(true, true); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_1/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_1/output.js new file mode 100644 index 000000000000..5741ce780ad8 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_1/output.js @@ -0,0 +1,12 @@ +function test(definitely_true, maybe_true) { + switch (true) { + case definitely_true: + default: + console.log("PASS"); + break; + case maybe_true: + console.log("FAIL"); + } +} +test(true, false); +test(true, true); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_1/output.terser.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_1/output.terser.js new file mode 100644 index 000000000000..5741ce780ad8 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_1/output.terser.js @@ -0,0 +1,12 @@ +function test(definitely_true, maybe_true) { + switch (true) { + case definitely_true: + default: + console.log("PASS"); + break; + case maybe_true: + console.log("FAIL"); + } +} +test(true, false); +test(true, true); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_2/analysis-snapshot.rust-debug b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_2/analysis-snapshot.rust-debug new file mode 100644 index 000000000000..e905e161aa1f --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_2/analysis-snapshot.rust-debug @@ -0,0 +1,156 @@ +TestSnapshot { + vars: [ + ( + ( + Atom('console' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 2, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 2, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: true, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: true, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('definitely_true' type=dynamic), + #2, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: true, + declared_count: 1, + declared_as_fn_param: true, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: false, + is_fn_local: true, + used_by_nested_fn: true, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('maybe_true' type=dynamic), + #2, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: true, + declared_count: 1, + declared_as_fn_param: true, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: false, + is_fn_local: true, + used_by_nested_fn: true, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('test' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 2, + cond_init: false, + declared: true, + declared_count: 1, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 2, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: false, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: true, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ], +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_2/config.json b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_2/config.json new file mode 100644 index 000000000000..c39c8d07f6c9 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_2/config.json @@ -0,0 +1,4 @@ +{ + "switches": true, + "dead_code": true +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_2/input.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_2/input.js new file mode 100644 index 000000000000..dc11bff83493 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_2/input.js @@ -0,0 +1,13 @@ +function test(definitely_true, maybe_true) { + switch (true) { + case definitely_true: + default: + console.log("PASS"); + break; + case maybe_true: + console.log("FAIL"); + break; + } +} +test(true, false); +test(true, true); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_2/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_2/output.js new file mode 100644 index 000000000000..5741ce780ad8 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_2/output.js @@ -0,0 +1,12 @@ +function test(definitely_true, maybe_true) { + switch (true) { + case definitely_true: + default: + console.log("PASS"); + break; + case maybe_true: + console.log("FAIL"); + } +} +test(true, false); +test(true, true); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_2/output.terser.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_2/output.terser.js new file mode 100644 index 000000000000..5741ce780ad8 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_2/output.terser.js @@ -0,0 +1,12 @@ +function test(definitely_true, maybe_true) { + switch (true) { + case definitely_true: + default: + console.log("PASS"); + break; + case maybe_true: + console.log("FAIL"); + } +} +test(true, false); +test(true, true); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_3/analysis-snapshot.rust-debug b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_3/analysis-snapshot.rust-debug new file mode 100644 index 000000000000..e905e161aa1f --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_3/analysis-snapshot.rust-debug @@ -0,0 +1,156 @@ +TestSnapshot { + vars: [ + ( + ( + Atom('console' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 2, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 2, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: true, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: true, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('definitely_true' type=dynamic), + #2, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: true, + declared_count: 1, + declared_as_fn_param: true, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: false, + is_fn_local: true, + used_by_nested_fn: true, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('maybe_true' type=dynamic), + #2, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: true, + declared_count: 1, + declared_as_fn_param: true, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: false, + is_fn_local: true, + used_by_nested_fn: true, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('test' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 2, + cond_init: false, + declared: true, + declared_count: 1, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 2, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: false, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: true, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ], +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_3/config.json b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_3/config.json new file mode 100644 index 000000000000..c39c8d07f6c9 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_3/config.json @@ -0,0 +1,4 @@ +{ + "switches": true, + "dead_code": true +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_3/input.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_3/input.js new file mode 100644 index 000000000000..c5d398a8e3ee --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_3/input.js @@ -0,0 +1,13 @@ +function test(definitely_true, maybe_true) { + switch (true) { + case maybe_true: + console.log("maybe"); + break; + default: + case definitely_true: + console.log("definitely"); + break; + } +} +test(true, false); +test(true, true); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_3/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_3/output.js new file mode 100644 index 000000000000..b892764257bf --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_3/output.js @@ -0,0 +1,6 @@ +function test(definitely_true, maybe_true) { + if (true === maybe_true) console.log("maybe"); + else console.log("definitely"); +} +test(true, false); +test(true, true); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_3/output.terser.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_3/output.terser.js new file mode 100644 index 000000000000..b892764257bf --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_3/output.terser.js @@ -0,0 +1,6 @@ +function test(definitely_true, maybe_true) { + if (true === maybe_true) console.log("maybe"); + else console.log("definitely"); +} +test(true, false); +test(true, true); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_4/analysis-snapshot.rust-debug b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_4/analysis-snapshot.rust-debug new file mode 100644 index 000000000000..e905e161aa1f --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_4/analysis-snapshot.rust-debug @@ -0,0 +1,156 @@ +TestSnapshot { + vars: [ + ( + ( + Atom('console' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 2, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 2, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: true, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: true, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('definitely_true' type=dynamic), + #2, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: true, + declared_count: 1, + declared_as_fn_param: true, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: false, + is_fn_local: true, + used_by_nested_fn: true, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('maybe_true' type=dynamic), + #2, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: true, + declared_count: 1, + declared_as_fn_param: true, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: false, + is_fn_local: true, + used_by_nested_fn: true, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('test' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 2, + cond_init: false, + declared: true, + declared_count: 1, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 2, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: false, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: true, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ], +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_4/config.json b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_4/config.json new file mode 100644 index 000000000000..c39c8d07f6c9 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_4/config.json @@ -0,0 +1,4 @@ +{ + "switches": true, + "dead_code": true +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_4/input.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_4/input.js new file mode 100644 index 000000000000..ef3a6539544c --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_4/input.js @@ -0,0 +1,13 @@ +function test(definitely_true, maybe_true) { + switch (true) { + case maybe_true: + console.log("maybe"); + break; + case definitely_true: + default: + console.log("definitely"); + break; + } +} +test(true, false); +test(true, true); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_4/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_4/output.js new file mode 100644 index 000000000000..b892764257bf --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_4/output.js @@ -0,0 +1,6 @@ +function test(definitely_true, maybe_true) { + if (true === maybe_true) console.log("maybe"); + else console.log("definitely"); +} +test(true, false); +test(true, true); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_4/output.terser.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_4/output.terser.js new file mode 100644 index 000000000000..b892764257bf --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_4/output.terser.js @@ -0,0 +1,6 @@ +function test(definitely_true, maybe_true) { + if (true === maybe_true) console.log("maybe"); + else console.log("definitely"); +} +test(true, false); +test(true, true); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_5/analysis-snapshot.rust-debug b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_5/analysis-snapshot.rust-debug new file mode 100644 index 000000000000..c75633ae3d23 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_5/analysis-snapshot.rust-debug @@ -0,0 +1,156 @@ +TestSnapshot { + vars: [ + ( + ( + Atom('console' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 3, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 3, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: true, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: true, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('definitely_true' type=dynamic), + #2, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: true, + declared_count: 1, + declared_as_fn_param: true, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: false, + is_fn_local: true, + used_by_nested_fn: true, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('maybe_true' type=dynamic), + #2, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: true, + declared_count: 1, + declared_as_fn_param: true, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: false, + is_fn_local: true, + used_by_nested_fn: true, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('test' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 2, + cond_init: false, + declared: true, + declared_count: 1, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 2, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: false, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: true, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ], +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_5/config.json b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_5/config.json new file mode 100644 index 000000000000..c39c8d07f6c9 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_5/config.json @@ -0,0 +1,4 @@ +{ + "switches": true, + "dead_code": true +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_5/input.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_5/input.js new file mode 100644 index 000000000000..4eacbef4ac0d --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_5/input.js @@ -0,0 +1,15 @@ +function test(definitely_true, maybe_true) { + switch (true) { + default: + console.log("definitely"); + break; + case maybe_true: + console.log("maybe"); + break; + case definitely_true: + console.log("definitely"); + break; + } +} +test(true, false); +test(true, true); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_5/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_5/output.js new file mode 100644 index 000000000000..7e280683d97b --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_5/output.js @@ -0,0 +1,14 @@ +function test(definitely_true, maybe_true) { + switch(true){ + default: + console.log("definitely"); + break; + case maybe_true: + console.log("maybe"); + break; + case definitely_true: + console.log("definitely"); + } +} +test(true, false); +test(true, true); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_5/output.terser.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_5/output.terser.js new file mode 100644 index 000000000000..f107471c8528 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_5/output.terser.js @@ -0,0 +1,14 @@ +function test(definitely_true, maybe_true) { + switch (true) { + default: + console.log("definitely"); + break; + case maybe_true: + console.log("maybe"); + break; + case definitely_true: + console.log("definitely"); + } +} +test(true, false); +test(true, true); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_6/analysis-snapshot.rust-debug b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_6/analysis-snapshot.rust-debug new file mode 100644 index 000000000000..c75633ae3d23 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_6/analysis-snapshot.rust-debug @@ -0,0 +1,156 @@ +TestSnapshot { + vars: [ + ( + ( + Atom('console' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 3, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 3, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: true, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: true, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('definitely_true' type=dynamic), + #2, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: true, + declared_count: 1, + declared_as_fn_param: true, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: false, + is_fn_local: true, + used_by_nested_fn: true, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('maybe_true' type=dynamic), + #2, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 1, + cond_init: false, + declared: true, + declared_count: 1, + declared_as_fn_param: true, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 1, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: false, + is_fn_local: true, + used_by_nested_fn: true, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('test' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 2, + cond_init: false, + declared: true, + declared_count: 1, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 2, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: false, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: true, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ], +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_6/config.json b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_6/config.json new file mode 100644 index 000000000000..c39c8d07f6c9 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_6/config.json @@ -0,0 +1,4 @@ +{ + "switches": true, + "dead_code": true +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_6/input.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_6/input.js new file mode 100644 index 000000000000..42a600de91c1 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_6/input.js @@ -0,0 +1,15 @@ +function test(definitely_true, maybe_true) { + switch (true) { + case definitely_true: + console.log("definitely"); + break; + case maybe_true: + console.log("maybe"); + break; + default: + console.log("definitely"); + break; + } +} +test(true, false); +test(true, true); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_6/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_6/output.js new file mode 100644 index 000000000000..a1327ae6886d --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_6/output.js @@ -0,0 +1,14 @@ +function test(definitely_true, maybe_true) { + switch(true){ + case definitely_true: + console.log("definitely"); + break; + case maybe_true: + console.log("maybe"); + break; + default: + console.log("definitely"); + } +} +test(true, false); +test(true, true); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_6/output.terser.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_6/output.terser.js new file mode 100644 index 000000000000..8909a538a1ad --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1083_6/output.terser.js @@ -0,0 +1,14 @@ +function test(definitely_true, maybe_true) { + switch (true) { + case definitely_true: + console.log("definitely"); + break; + case maybe_true: + console.log("maybe"); + break; + default: + console.log("definitely"); + } +} +test(true, false); +test(true, true); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1679/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1679/output.js index f856f019829a..eefc6f02fd46 100644 --- a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1679/output.js +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1679/output.js @@ -1,15 +1,11 @@ -var a = 100, - b = 10; +var a = 100, b = 10; function f() { - switch (--b) { + switch(--b){ default: case false: - case b--: - switch (0) { - default: - case a--: - } break; + case b--: + a--; case a++: } } diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1680_1/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1680_1/output.js index 8e5058d564bc..7cfad2d7d982 100644 --- a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1680_1/output.js +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1680_1/output.js @@ -2,4 +2,10 @@ function f(x) { console.log(x); return x + 1; } -f(5); +switch(2){ + case f(0): + case f(1): + f(2); + case 2: + f(5); +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1680_2/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1680_2/output.js index 96c4cd443b11..3f19a534b3ef 100644 --- a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1680_2/output.js +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1680_2/output.js @@ -5,7 +5,6 @@ switch (b) { break; case b: var c; - break; case a: case a--: } diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1690_2/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1690_2/output.js index 2d24c7530c8c..5507d9829d7d 100644 --- a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1690_2/output.js +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1690_2/output.js @@ -1,2 +1,2 @@ -switch (console.log("PASS")) { +switch(console.log("PASS")){ } diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1698/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1698/output.js index ccb7fc9aa059..890ec1aa3d8a 100644 --- a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1698/output.js +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1698/output.js @@ -1,6 +1,6 @@ var a = 1; -!(function () { - switch (a++) { +!function() { + switch(a++){ } -})(); +}(); console.log(a); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1705_1/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1705_1/output.js index 5b3eaa6d1847..012de9e478a6 100644 --- a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1705_1/output.js +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1705_1/output.js @@ -1,6 +1,2 @@ var a = 0; -switch (a) { - default: - console.log("FAIL"); - case 0: -} +if (0 !== a) console.log("FAIL"); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1750/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1750/output.js index 5e03cc4a7afd..884c64ff0f19 100644 --- a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1750/output.js +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_1750/output.js @@ -1,3 +1,4 @@ -var a = 0, - b = 1; +var a = 0, b = 1; +a; +b = 2; console.log(a, b); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_376/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_376/output.js index 9e2d9a5c3d7c..20deee1d37a9 100644 --- a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_376/output.js +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_376/output.js @@ -1,4 +1 @@ -switch (true) { - case boolCondition: - console.log(1); -} +if (true === boolCondition) console.log(1); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_441_1/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_441_1/output.js index 859e262ec7fb..3f2d878e6904 100644 --- a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_441_1/output.js +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_441_1/output.js @@ -1 +1,2 @@ +foo; qux(); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_441_2/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_441_2/output.js index 859e262ec7fb..3f2d878e6904 100644 --- a/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_441_2/output.js +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/issue_441_2/output.js @@ -1 +1,2 @@ +foo; qux(); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/keep_case/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/keep_case/output.js index f2b9091386e1..a3a043e13da0 100644 --- a/crates/swc_ecma_minifier/tests/terser/compress/switch/keep_case/output.js +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/keep_case/output.js @@ -1,6 +1 @@ -switch (foo) { - case "bar": - baz(); - break; - case moo: -} +if ("bar" === foo) baz(); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/keep_default/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/keep_default/output.js index 4f2eaddb914e..d3e90e1e1cf9 100644 --- a/crates/swc_ecma_minifier/tests/terser/compress/switch/keep_default/output.js +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/keep_default/output.js @@ -1,6 +1,2 @@ -switch (foo) { - case "bar": - baz(); - default: - something(); -} +if ("bar" === foo) baz(); +something(); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if/analysis-snapshot.rust-debug b/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if/analysis-snapshot.rust-debug new file mode 100644 index 000000000000..962344713970 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if/analysis-snapshot.rust-debug @@ -0,0 +1,80 @@ +TestSnapshot { + vars: [ + ( + ( + Atom('console' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 2, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 2, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: true, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('id' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 2, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 2, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ], +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if/config.json b/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if/config.json new file mode 100644 index 000000000000..c39c8d07f6c9 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if/config.json @@ -0,0 +1,4 @@ +{ + "switches": true, + "dead_code": true +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if/input.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if/input.js new file mode 100644 index 000000000000..a80f5186341d --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if/input.js @@ -0,0 +1,5 @@ +switch (id(1)) { + case id(2): + console.log("FAIL"); +} +console.log("PASS"); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if/output.js new file mode 100644 index 000000000000..5f26a6a1d46c --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if/output.js @@ -0,0 +1,2 @@ +if (id(1) === id(2)) console.log("FAIL"); +console.log("PASS"); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if/output.terser.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if/output.terser.js new file mode 100644 index 000000000000..5f26a6a1d46c --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if/output.terser.js @@ -0,0 +1,2 @@ +if (id(1) === id(2)) console.log("FAIL"); +console.log("PASS"); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if_2/analysis-snapshot.rust-debug b/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if_2/analysis-snapshot.rust-debug new file mode 100644 index 000000000000..962344713970 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if_2/analysis-snapshot.rust-debug @@ -0,0 +1,80 @@ +TestSnapshot { + vars: [ + ( + ( + Atom('console' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 2, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 2, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: true, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: true, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: false, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ( + ( + Atom('id' type=inline), + #1, + ), + VarUsageInfo { + inline_prevented: false, + ref_count: 2, + cond_init: false, + declared: false, + declared_count: 0, + declared_as_fn_param: false, + declared_as_fn_expr: false, + assign_count: 0, + mutation_by_call_count: 0, + usage_count: 2, + reassigned_with_assignment: false, + reassigned_with_var_decl: false, + mutated: false, + has_property_access: false, + has_property_mutation: false, + accessed_props: {}, + exported: false, + used_above_decl: true, + is_fn_local: true, + used_by_nested_fn: false, + executed_multiple_time: false, + used_in_cond: false, + var_kind: None, + var_initialized: false, + declared_as_catch_param: false, + no_side_effect_for_member_access: false, + used_as_callee: true, + used_as_arg: false, + pure_fn: false, + infects: [], + }, + ), + ], +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if_2/config.json b/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if_2/config.json new file mode 100644 index 000000000000..c39c8d07f6c9 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if_2/config.json @@ -0,0 +1,4 @@ +{ + "switches": true, + "dead_code": true +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if_2/input.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if_2/input.js new file mode 100644 index 000000000000..54a54151fa66 --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if_2/input.js @@ -0,0 +1,6 @@ +switch (id(1)) { + case id(2): + console.log("FAIL"); + default: + console.log("PASS"); +} diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if_2/output.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if_2/output.js new file mode 100644 index 000000000000..5f26a6a1d46c --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if_2/output.js @@ -0,0 +1,2 @@ +if (id(1) === id(2)) console.log("FAIL"); +console.log("PASS"); diff --git a/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if_2/output.terser.js b/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if_2/output.terser.js new file mode 100644 index 000000000000..5f26a6a1d46c --- /dev/null +++ b/crates/swc_ecma_minifier/tests/terser/compress/switch/turn_into_if_2/output.terser.js @@ -0,0 +1,2 @@ +if (id(1) === id(2)) console.log("FAIL"); +console.log("PASS"); diff --git a/crates/swc_ecma_utils/src/lib.rs b/crates/swc_ecma_utils/src/lib.rs index 509024634414..8761da9d64af 100644 --- a/crates/swc_ecma_utils/src/lib.rs +++ b/crates/swc_ecma_utils/src/lib.rs @@ -350,13 +350,8 @@ pub fn extract_var_ids>(node: &T) -> Vec { } pub trait StmtExt { - fn into_stmt(self) -> Stmt; - fn as_stmt(&self) -> &Stmt; - /// Extracts hoisted variables - fn extract_var_ids(&self) -> Vec { - extract_var_ids(self.as_stmt()) - } + fn extract_var_ids(&self) -> Vec; fn extract_var_ids_as_var(&self) -> Option { let ids = self.extract_var_ids(); @@ -379,29 +374,55 @@ pub trait StmtExt { .collect(), }) } + + /// stmts contain top level return/break/continue/throw + fn terminates(&self) -> bool; } impl StmtExt for Stmt { - #[inline] - fn into_stmt(self) -> Stmt { - self + fn extract_var_ids(&self) -> Vec { + extract_var_ids(self) } - #[inline] - fn as_stmt(&self) -> &Stmt { - self + fn terminates(&self) -> bool { + match self { + Stmt::Break(_) | Stmt::Continue(_) | Stmt::Throw(_) | Stmt::Return(_) => return true, + Stmt::Block(block) if block.stmts.terminates() => return true, + Stmt::If(IfStmt { + cons, + alt: Some(alt), + .. + }) => return cons.terminates() && alt.terminates(), + _ => (), + } + + false } } impl StmtExt for Box { - #[inline] - fn into_stmt(self) -> Stmt { - *self + fn extract_var_ids(&self) -> Vec { + extract_var_ids(&**self) } - #[inline] - fn as_stmt(&self) -> &Stmt { - &**self + fn terminates(&self) -> bool { + (&**self).terminates() + } +} + +impl StmtExt for Vec { + fn extract_var_ids(&self) -> Vec { + extract_var_ids(self) + } + + fn terminates(&self) -> bool { + for s in self { + if s.terminates() { + return true; + } + } + + false } }