file_path stringlengths 3 280 | file_language stringclasses 66
values | content stringlengths 1 1.04M | repo_name stringlengths 5 92 | repo_stars int64 0 154k | repo_description stringlengths 0 402 | repo_primary_language stringclasses 108
values | developer_username stringlengths 1 25 | developer_name stringlengths 0 30 | developer_company stringlengths 0 82 |
|---|---|---|---|---|---|---|---|---|---|
crates/swc_ecma_minifier/src/compress/pure/dead_code.rs | Rust | #[cfg(feature = "concurrent")]
use rayon::prelude::*;
use swc_common::{util::take::Take, EqIgnoreSpan, Spanned, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_utils::{extract_var_ids, ExprCtx, ExprExt, StmtExt, StmtLike, Value};
use swc_ecma_visit::{noop_visit_type, Visit, VisitWith};
use super::Pure;
use crate::{compress::util::is_fine_for_if_cons, maybe_par, util::ModuleItemExt};
/// Methods related to option `dead_code`.
impl Pure<'_> {
///
/// - Removes `L1: break L1`
pub(super) fn drop_instant_break(&mut self, s: &mut Stmt) {
if let Stmt::Labeled(ls) = s {
if let Stmt::Break(BreakStmt {
label: Some(label), ..
}) = &*ls.body
{
if label.sym == ls.label.sym {
self.changed = true;
report_change!("Dropping instant break `{}`", label);
s.take();
}
}
}
}
/// # Operations
///
///
/// - Convert if break to conditionals
///
/// ```js
/// out: {
/// if (foo) break out;
/// console.log("bar");
/// }
/// ```
///
/// =>
///
/// ```js
/// foo || console.log("bar");
/// ```
pub(super) fn optimize_labeled_stmt(&mut self, s: &mut Stmt) -> Option<()> {
if !self.options.dead_code {
return None;
}
if let Stmt::Labeled(ls) = s {
if let Stmt::Block(bs) = &mut *ls.body {
let first = bs.stmts.first_mut()?;
if let Stmt::If(IfStmt {
test,
cons,
alt: None,
..
}) = first
{
if let Stmt::Break(BreakStmt {
label: Some(label), ..
}) = &**cons
{
if ls.label.sym == label.sym {
self.changed = true;
report_change!(
"Optimizing labeled stmt with a break to if statement: `{}`",
label
);
self.negate(test, true, false);
let test = test.take();
let mut cons = bs.take();
cons.stmts.remove(0);
ls.body = Box::new(
IfStmt {
span: ls.span,
test,
cons: Box::new(Stmt::Block(cons)),
alt: None,
}
.into(),
);
return None;
}
}
}
if let Stmt::If(IfStmt {
test,
cons,
alt: Some(alt),
..
}) = first
{
if let Stmt::Break(BreakStmt {
label: Some(label), ..
}) = &**alt
{
if ls.label.sym == label.sym {
self.changed = true;
report_change!(
"Optimizing labeled stmt with a break in alt to if statement: {}",
ls.label
);
let test = test.take();
let cons = *cons.take();
let mut new_cons = bs.take();
new_cons.stmts[0] = cons;
ls.body = Box::new(
IfStmt {
span: ls.span,
test,
cons: Box::new(Stmt::Block(new_cons)),
alt: None,
}
.into(),
);
return None;
}
}
}
}
}
None
}
/// Remove the last statement of a loop if it's continue
pub(super) fn drop_useless_continue(&mut self, s: &mut Stmt) {
match s {
Stmt::Labeled(ls) => {
let new = self.drop_useless_continue_inner(Some(ls.label.clone()), &mut ls.body);
if let Some(new) = new {
*s = new;
}
}
_ => {
let new = self.drop_useless_continue_inner(None, s);
if let Some(new) = new {
*s = new;
}
}
}
}
/// Returns [Some] if the whole statement should be replaced
fn drop_useless_continue_inner(
&mut self,
label: Option<Ident>,
loop_stmt: &mut Stmt,
) -> Option<Stmt> {
let body = match loop_stmt {
Stmt::While(ws) => &mut *ws.body,
Stmt::For(fs) => &mut *fs.body,
Stmt::ForIn(fs) => &mut *fs.body,
Stmt::ForOf(fs) => &mut *fs.body,
_ => return None,
};
if let Stmt::Block(b) = body {
let last = b.stmts.last_mut()?;
if let Stmt::Continue(last_cs) = last {
if last_cs.label.is_some() {
if label.eq_ignore_span(&last_cs.label) {
} else {
return None;
}
}
} else {
return None;
}
self.changed = true;
report_change!("Remove useless continue (last stmt of a loop)");
b.stmts.remove(b.stmts.len() - 1);
if let Some(label) = &label {
if !contains_label(b, label) {
return Some(loop_stmt.take());
}
}
}
None
}
pub(super) fn drop_unreachable_stmts<T>(&mut self, stmts: &mut Vec<T>)
where
T: StmtLike + ModuleItemExt + Take,
{
if !self.options.dead_code && !self.options.if_return {
return;
}
let idx = stmts.iter().position(|stmt| match stmt.as_stmt() {
Some(s) => s.terminates(),
_ => false,
});
// TODO: let chain
if let Some(idx) = idx {
self.drop_duplicate_terminate(&mut stmts[..=idx]);
// Return at the last is fine
if idx == stmts.len() - 1 {
return;
}
// If only function declarations are left, we should not proceed
if stmts
.iter()
.skip(idx + 1)
.all(|s| matches!(s.as_stmt(), Some(Stmt::Decl(Decl::Fn(_)))))
{
if let Some(Stmt::Return(ReturnStmt { arg: None, .. })) = stmts[idx].as_stmt() {
// Remove last return
stmts.remove(idx);
}
return;
}
self.changed = true;
report_change!("Dropping statements after a control keyword");
let stmts_len = stmts.len();
// Hoist function and `var` declarations above return.
let (decls, hoisted_fns, mut new_stmts) = stmts.iter_mut().skip(idx + 1).fold(
(
Vec::with_capacity(stmts_len),
Vec::<T>::with_capacity(stmts_len),
Vec::with_capacity(stmts_len),
),
|(mut decls, mut hoisted_fns, mut new_stmts), stmt| {
match stmt.take().try_into_stmt() {
Ok(Stmt::Decl(Decl::Fn(f))) => {
hoisted_fns.push(T::from(Stmt::from(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),
};
(decls, hoisted_fns, new_stmts)
},
);
if !decls.is_empty() {
new_stmts.push(T::from(Stmt::from(VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Var,
decls,
declare: false,
..Default::default()
})));
}
new_stmts.extend(stmts.drain(..=idx));
new_stmts.extend(hoisted_fns);
*stmts = new_stmts;
}
}
fn drop_duplicate_terminate<T: StmtLike>(&mut self, stmts: &mut [T]) {
let (last, stmts) = stmts.split_last_mut().unwrap();
let last = match last.as_stmt() {
Some(s @ (Stmt::Break(_) | Stmt::Continue(_) | Stmt::Return(_) | Stmt::Throw(_))) => s,
_ => return,
};
fn drop<T: StmtLike>(stmt: &mut T, last: &Stmt, need_break: bool, ctx: ExprCtx) -> bool {
match stmt.as_stmt_mut() {
Some(s) if s.eq_ignore_span(last) => {
if need_break {
*s = BreakStmt {
label: None,
span: s.span(),
}
.into();
} else {
s.take();
}
true
}
Some(Stmt::If(i)) => {
let mut changed = false;
changed |= drop(&mut *i.cons, last, need_break, ctx);
if let Some(alt) = i.alt.as_mut() {
changed |= drop(&mut **alt, last, need_break, ctx);
}
changed
}
Some(Stmt::Try(t)) => {
let mut changed = false;
// TODO: let chain
if let Some(stmt) = t.block.stmts.last_mut() {
let side_effect = match last {
Stmt::Break(_) | Stmt::Continue(_) => false,
Stmt::Return(ReturnStmt { arg: None, .. }) => false,
Stmt::Return(ReturnStmt { arg: Some(arg), .. }) => {
arg.may_have_side_effects(ctx)
}
Stmt::Throw(_) => true,
_ => unreachable!(),
};
if t.finalizer.is_none() && !side_effect {
changed |= drop(stmt, last, need_break, ctx)
}
}
if let Some(h) = t.handler.as_mut() {
if let Some(stmt) = h.body.stmts.last_mut() {
changed |= drop(stmt, last, need_break, ctx);
}
}
if let Some(f) = t.finalizer.as_mut() {
if let Some(stmt) = f.stmts.last_mut() {
changed |= drop(stmt, last, need_break, ctx);
}
}
changed
}
Some(Stmt::Switch(s)) if !last.is_break_stmt() && !need_break => {
let mut changed = false;
for case in s.cases.iter_mut() {
for stmt in case.cons.iter_mut() {
changed |= drop(stmt, last, true, ctx);
}
}
changed
}
Some(
Stmt::For(ForStmt { body, .. })
| Stmt::ForIn(ForInStmt { body, .. })
| Stmt::ForOf(ForOfStmt { body, .. })
| Stmt::While(WhileStmt { body, .. })
| Stmt::DoWhile(DoWhileStmt { body, .. }),
) if !last.is_break_stmt() && !last.is_continue_stmt() && !need_break => {
if let Stmt::Block(b) = &mut **body {
let mut changed = false;
for stmt in b.stmts.iter_mut() {
changed |= drop(stmt, last, true, ctx);
}
changed
} else {
drop(&mut **body, last, true, ctx)
}
}
Some(Stmt::Block(b)) => {
if let Some(stmt) = b.stmts.last_mut() {
drop(stmt, last, need_break, ctx)
} else {
false
}
}
_ => false,
}
}
if let Some(before_last) = stmts.last_mut() {
if drop(before_last, last, false, self.expr_ctx) {
self.changed = true;
report_change!("Dropping control keyword in nested block");
}
}
}
pub(super) fn drop_useless_blocks<T>(&mut self, stmts: &mut Vec<T>)
where
T: StmtLike,
{
fn is_ok(b: &BlockStmt) -> bool {
maybe_par!(
b.stmts.iter().all(is_fine_for_if_cons),
*crate::LIGHT_TASK_PARALLELS
)
}
if maybe_par!(
stmts
.iter()
.all(|stmt| !matches!(stmt.as_stmt(), Some(Stmt::Block(b)) if is_ok(b))),
*crate::LIGHT_TASK_PARALLELS
) {
return;
}
self.changed = true;
report_change!("Dropping useless block");
let old_stmts = stmts.take();
let new: Vec<T> = if old_stmts.len() >= *crate::LIGHT_TASK_PARALLELS {
#[cfg(feature = "concurrent")]
{
old_stmts
.into_par_iter()
.flat_map(|stmt| match stmt.try_into_stmt() {
Ok(v) => match v {
Stmt::Block(v) if is_ok(&v) => {
let stmts = v.stmts;
maybe_par!(
stmts.into_iter().map(T::from).collect(),
*crate::LIGHT_TASK_PARALLELS
)
}
_ => vec![T::from(v)],
},
Err(v) => vec![v],
})
.collect()
}
#[cfg(not(feature = "concurrent"))]
{
old_stmts
.into_iter()
.flat_map(|stmt| match stmt.try_into_stmt() {
Ok(v) => match v {
Stmt::Block(v) if is_ok(&v) => {
let stmts = v.stmts;
maybe_par!(
stmts.into_iter().map(T::from).collect(),
*crate::LIGHT_TASK_PARALLELS
)
}
_ => vec![T::from(v)],
},
Err(v) => vec![v],
})
.collect()
}
} else {
let mut new = Vec::with_capacity(old_stmts.len() * 2);
old_stmts
.into_iter()
.for_each(|stmt| match stmt.try_into_stmt() {
Ok(v) => match v {
Stmt::Block(v) if is_ok(&v) => {
new.extend(v.stmts.into_iter().map(T::from));
}
_ => new.push(T::from(v)),
},
Err(v) => new.push(v),
});
new
};
*stmts = new;
}
pub(super) fn drop_unused_stmt_at_end_of_fn(&mut self, s: &mut Stmt) {
if let Stmt::Return(r) = s {
if let Some(Expr::Unary(UnaryExpr {
span,
op: op!("void"),
arg,
})) = r.arg.as_deref_mut()
{
report_change!("unused: Removing `return void` in end of a function");
self.changed = true;
*s = ExprStmt {
span: *span,
expr: arg.take(),
}
.into();
}
}
}
pub(super) fn remove_dead_branch<T>(&mut self, stmts: &mut Vec<T>)
where
T: StmtLike,
{
if !self.options.unused {
return;
}
if !maybe_par!(
stmts.iter().any(|stmt| match stmt.as_stmt() {
Some(Stmt::If(s)) => s.test.cast_to_bool(self.expr_ctx).1.is_known(),
_ => false,
}),
*crate::LIGHT_TASK_PARALLELS
) {
return;
}
self.changed = true;
report_change!("dead_code: Removing dead codes");
let mut new = Vec::with_capacity(stmts.len());
stmts
.take()
.into_iter()
.for_each(|stmt| match stmt.try_into_stmt() {
Ok(stmt) => match stmt {
Stmt::If(mut s) => {
if let Value::Known(v) = s.test.cast_to_bool(self.expr_ctx).1 {
let mut var_ids = Vec::new();
new.push(T::from(
ExprStmt {
span: DUMMY_SP,
expr: s.test.take(),
}
.into(),
));
if v {
if let Some(alt) = s.alt.take() {
var_ids = alt
.extract_var_ids()
.into_iter()
.map(|name| VarDeclarator {
span: DUMMY_SP,
name: name.into(),
init: None,
definite: Default::default(),
})
.collect();
}
if !var_ids.is_empty() {
new.push(T::from(
VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Var,
declare: Default::default(),
decls: var_ids,
..Default::default()
}
.into(),
))
}
new.push(T::from(*s.cons.take()));
} else {
var_ids = s
.cons
.extract_var_ids()
.into_iter()
.map(|name| VarDeclarator {
span: DUMMY_SP,
name: name.into(),
init: None,
definite: Default::default(),
})
.collect();
if !var_ids.is_empty() {
new.push(T::from(
VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Var,
declare: Default::default(),
decls: var_ids,
..Default::default()
}
.into(),
))
}
if let Some(alt) = s.alt.take() {
new.push(T::from(*alt));
}
}
} else {
new.push(T::from(s.into()));
}
}
_ => new.push(T::from(stmt)),
},
Err(stmt) => new.push(stmt),
});
*stmts = new;
}
}
fn contains_label<N>(node: &N, label: &Ident) -> bool
where
for<'aa> N: VisitWith<LabelFinder<'aa>>,
{
let mut v = LabelFinder {
label,
found: false,
};
node.visit_with(&mut v);
v.found
}
struct LabelFinder<'a> {
label: &'a Ident,
found: bool,
}
impl Visit for LabelFinder<'_> {
noop_visit_type!();
fn visit_break_stmt(&mut self, s: &BreakStmt) {
if let Some(label) = &s.label {
if label.sym == self.label.sym {
self.found = true;
}
}
}
fn visit_continue_stmt(&mut self, s: &ContinueStmt) {
if let Some(label) = &s.label {
if label.sym == self.label.sym {
self.found = true;
}
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/compress/pure/drop_console.rs | Rust | use swc_common::DUMMY_SP;
use swc_ecma_ast::*;
use super::Pure;
impl Pure<'_> {
pub(super) fn drop_console(&mut self, e: &mut Expr) {
if !self.options.drop_console {
return;
}
let Some(callee) = (match e {
Expr::Call(call) => call.callee.as_expr(),
Expr::OptChain(opt_chain) => opt_chain.base.as_call().map(|call| &call.callee),
_ => None,
}) else {
return;
};
let Some(mut loop_co) = (match callee.as_ref() {
Expr::Member(member) => Some(&member.obj),
Expr::OptChain(opt_chain) => opt_chain.base.as_member().map(|member| &member.obj),
_ => None,
}) else {
return;
};
loop {
match loop_co.as_ref() {
Expr::Ident(obj) => {
if obj.sym != *"console" {
return;
}
break;
}
Expr::Member(MemberExpr {
obj: loop_co_obj,
prop: MemberProp::Ident(_),
..
}) => {
loop_co = loop_co_obj;
}
Expr::OptChain(opt_chain) => match opt_chain.base.as_member() {
Some(member) => loop_co = &member.obj,
None => return,
},
_ => return,
}
}
report_change!("drop_console: Removing console call");
self.changed = true;
*e = *Expr::undefined(DUMMY_SP);
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/compress/pure/evaluate.rs | Rust | use radix_fmt::Radix;
use swc_common::{util::take::Take, Spanned, SyntaxContext};
use swc_ecma_ast::*;
use swc_ecma_utils::{number::ToJsString, ExprExt, IsEmpty, Value};
use super::Pure;
use crate::compress::util::{eval_as_number, is_pure_undefined_or_null};
#[cfg(feature = "debug")]
use crate::debug::dump;
impl Pure<'_> {
pub(super) fn eval_array_method_call(&mut self, e: &mut Expr) {
if !self.options.evaluate {
return;
}
if self.ctx.in_delete || self.ctx.is_update_arg || self.ctx.is_lhs_of_assign {
return;
}
let call = match e {
Expr::Call(e) => e,
_ => return,
};
let has_spread = call.args.iter().any(|arg| arg.spread.is_some());
for arg in &call.args {
if arg.expr.may_have_side_effects(self.expr_ctx) {
return;
}
}
let callee = match &mut call.callee {
Callee::Super(_) | Callee::Import(_) => return,
Callee::Expr(e) => &mut **e,
};
if let Expr::Member(MemberExpr {
span,
obj,
prop: MemberProp::Ident(method_name),
}) = callee
{
if obj.may_have_side_effects(self.expr_ctx) {
return;
}
let arr = match &mut **obj {
Expr::Array(arr) => arr,
_ => return,
};
let has_spread_elem = arr.elems.iter().any(|s| {
matches!(
s,
Some(ExprOrSpread {
spread: Some(..),
..
})
)
});
// Ignore array
if &*method_name.sym == "slice" {
if has_spread || has_spread_elem {
return;
}
match call.args.len() {
0 => {
self.changed = true;
report_change!("evaluate: Dropping array.slice call");
*e = *obj.take();
}
1 => {
if let Value::Known(start) = call.args[0].expr.as_pure_number(self.expr_ctx)
{
if start.is_sign_negative() {
return;
}
let start = start.floor() as usize;
self.changed = true;
report_change!("evaluate: Reducing array.slice({}) call", start);
if start >= arr.elems.len() {
*e = ArrayLit {
span: *span,
elems: Default::default(),
}
.into();
return;
}
let elems = arr.elems.drain(start..).collect();
*e = ArrayLit { span: *span, elems }.into();
}
}
_ => {
let start = call.args[0].expr.as_pure_number(self.expr_ctx);
let end = call.args[1].expr.as_pure_number(self.expr_ctx);
if let Value::Known(start) = start {
if start.is_sign_negative() {
return;
}
let start = start.floor() as usize;
if let Value::Known(end) = end {
if end.is_sign_negative() {
return;
}
let end = end.floor() as usize;
let end = end.min(arr.elems.len());
if start >= end {
return;
}
self.changed = true;
report_change!(
"evaluate: Reducing array.slice({}, {}) call",
start,
end
);
if start >= arr.elems.len() {
*e = ArrayLit {
span: *span,
elems: Default::default(),
}
.into();
return;
}
let elems = arr.elems.drain(start..end).collect();
*e = ArrayLit { span: *span, elems }.into();
}
}
}
}
return;
}
if self.options.unsafe_passes
&& &*method_name.sym == "toString"
&& arr.elems.len() == 1
&& arr.elems[0].is_some()
{
report_change!("evaluate: Reducing array.toString() call");
self.changed = true;
*obj = arr.elems[0]
.take()
.map(|elem| elem.expr)
.unwrap_or_else(|| Expr::undefined(*span));
}
}
}
pub(super) fn eval_fn_method_call(&mut self, e: &mut Expr) {
if !self.options.evaluate {
return;
}
if self.ctx.in_delete || self.ctx.is_update_arg || self.ctx.is_lhs_of_assign {
return;
}
let call = match e {
Expr::Call(e) => e,
_ => return,
};
let has_spread = call.args.iter().any(|arg| arg.spread.is_some());
for arg in &call.args {
if arg.expr.may_have_side_effects(self.expr_ctx) {
return;
}
}
let callee = match &mut call.callee {
Callee::Super(_) | Callee::Import(_) => return,
Callee::Expr(e) => &mut **e,
};
if let Expr::Member(MemberExpr {
obj,
prop: MemberProp::Ident(method_name),
..
}) = callee
{
if obj.may_have_side_effects(self.expr_ctx) {
return;
}
let f = match &mut **obj {
Expr::Fn(v) => v,
_ => return,
};
if &*method_name.sym == "valueOf" {
if has_spread {
return;
}
self.changed = true;
report_change!("evaluate: Reduced `function.valueOf()` into a function expression");
*e = *obj.take();
return;
}
if self.options.unsafe_passes
&& &*method_name.sym == "toString"
&& f.function.params.is_empty()
&& f.function.body.is_empty()
{
if has_spread {
return;
}
self.changed = true;
report_change!("evaluate: Reduced `function.toString()` into a string");
*e = Str {
span: call.span,
value: "function(){}".into(),
raw: None,
}
.into();
}
}
}
pub(super) fn eval_arguments_member_access(&mut self, e: &mut Expr) {
let member = match e {
Expr::Member(e) => e,
_ => return,
};
if !member.obj.is_ident_ref_to("arguments") {
return;
}
match &mut member.prop {
MemberProp::Ident(_) => {}
MemberProp::PrivateName(_) => {}
MemberProp::Computed(p) => {
if let Expr::Lit(Lit::Str(s)) = &*p.expr {
if let Ok(value) = s.value.parse::<u32>() {
p.expr = Lit::Num(Number {
span: s.span,
value: value as f64,
raw: None,
})
.into();
}
}
}
}
}
/// unsafely evaluate call to `Number`.
pub(super) fn eval_number_call(&mut self, e: &mut Expr) {
if self.options.unsafe_passes && self.options.unsafe_math {
if let Expr::Call(CallExpr {
span,
callee: Callee::Expr(callee),
args,
..
}) = e
{
if args.len() == 1 && args[0].spread.is_none() {
if callee.is_ident_ref_to("Number") {
self.changed = true;
report_change!(
"evaluate: Reducing a call to `Number` into an unary operation"
);
*e = UnaryExpr {
span: *span,
op: op!(unary, "+"),
arg: args.take().into_iter().next().unwrap().expr,
}
.into();
}
}
}
}
}
/// Evaluates method calls of a numeric constant.
pub(super) fn eval_number_method_call(&mut self, e: &mut Expr) {
if !self.options.evaluate {
return;
}
let (num, method, args) = match e {
Expr::Call(CallExpr {
callee: Callee::Expr(callee),
args,
..
}) => match &mut **callee {
Expr::Member(MemberExpr {
obj,
prop: MemberProp::Ident(prop),
..
}) => match &mut **obj {
Expr::Lit(Lit::Num(obj)) => (obj, prop, args),
_ => return,
},
_ => return,
},
_ => return,
};
if args
.iter()
.any(|arg| arg.expr.may_have_side_effects(self.expr_ctx))
{
return;
}
if &*method.sym == "toFixed" {
// https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.prototype.tofixed
//
// Note 1: This method returns a String containing this Number value represented
// in decimal fixed-point notation with fractionDigits digits after the decimal
// point. If fractionDigits is undefined, 0 is assumed.
// Note 2: The output of toFixed may be more precise than toString for some
// values because toString only prints enough significant digits to distinguish
// the number from adjacent Number values. For example,
//
// (1000000000000000128).toString() returns "1000000000000000100", while
// (1000000000000000128).toFixed(0) returns "1000000000000000128".
// 1. Let x be ? thisNumberValue(this value).
// 2. Let f be ? ToIntegerOrInfinity(fractionDigits).
if let Some(precision) = args
.first()
// 3. Assert: If fractionDigits is undefined, then f is 0.
.map_or(Some(0f64), |arg| eval_as_number(self.expr_ctx, &arg.expr))
{
let f = precision.trunc() as u8;
// 4. If f is not finite, throw a RangeError exception.
// 5. If f < 0 or f > 100, throw a RangeError exception.
// Note: ES2018 increased the maximum number of fraction digits from 20 to 100.
// It relies on runtime behavior.
if !(0..=20).contains(&f) {
return;
}
let mut buffer = ryu_js::Buffer::new();
let value = buffer.format_to_fixed(num.value, f);
self.changed = true;
report_change!(
"evaluate: Evaluating `{}.toFixed({})` as `{}`",
num,
precision,
value
);
*e = Lit::Str(Str {
span: e.span(),
raw: None,
value: value.into(),
})
.into();
}
return;
}
if &*method.sym == "toPrecision" {
// TODO: handle num.toPrecision(undefined)
if args.is_empty() {
// https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-number.prototype.toprecision
// 2. If precision is undefined, return ! ToString(x).
let value = num.value.to_js_string().into();
self.changed = true;
report_change!(
"evaluate: Evaluating `{}.toPrecision()` as `{}`",
num,
value
);
*e = Lit::Str(Str {
span: e.span(),
raw: None,
value,
})
.into();
return;
}
if let Some(precision) = args
.first()
.and_then(|arg| eval_as_number(self.expr_ctx, &arg.expr))
{
let p = precision.trunc() as usize;
// 5. If p < 1 or p > 100, throw a RangeError exception.
if !(1..=21).contains(&p) {
return;
}
let value = f64_to_precision(num.value, p);
self.changed = true;
report_change!(
"evaluate: Evaluating `{}.toPrecision()` as `{}`",
num,
value
);
*e = Lit::Str(Str {
span: e.span(),
raw: None,
value: value.into(),
})
.into();
return;
}
}
if &*method.sym == "toExponential" {
// TODO: handle num.toExponential(undefined)
if args.is_empty() {
let value = f64_to_exponential(num.value).into();
self.changed = true;
report_change!(
"evaluate: Evaluating `{}.toExponential()` as `{}`",
num,
value
);
*e = Lit::Str(Str {
span: e.span(),
raw: None,
value,
})
.into();
return;
} else if let Some(precision) = args
.first()
.and_then(|arg| eval_as_number(self.expr_ctx, &arg.expr))
{
let p = precision.trunc() as usize;
// 5. If p < 1 or p > 100, throw a RangeError exception.
if !(0..=20).contains(&p) {
return;
}
let value = f64_to_exponential_with_precision(num.value, p).into();
self.changed = true;
report_change!(
"evaluate: Evaluating `{}.toPrecision({})` as `{}`",
num,
precision,
value
);
*e = Lit::Str(Str {
span: e.span(),
raw: None,
value,
})
.into();
return;
}
}
if &*method.sym == "toString" {
if let Some(base) = args
.first()
.map_or(Some(10f64), |arg| eval_as_number(self.expr_ctx, &arg.expr))
{
if base.trunc() == 10. {
let value = num.value.to_js_string().into();
*e = Lit::Str(Str {
span: e.span(),
raw: None,
value,
})
.into();
return;
}
if num.value.fract() == 0.0 && (2.0..=36.0).contains(&base) && base.fract() == 0.0 {
let base = base.floor() as u8;
self.changed = true;
let value = {
let x = num.value;
if x < 0. {
// I don't know if u128 is really needed, but it works.
format!("-{}", Radix::new(-x as u128, base))
} else {
Radix::new(x as u128, base).to_string()
}
}
.into();
*e = Lit::Str(Str {
span: e.span(),
raw: None,
value,
})
.into()
}
}
}
}
pub(super) fn eval_opt_chain(&mut self, e: &mut Expr) {
let opt = match e {
Expr::OptChain(e) => e,
_ => return,
};
match &mut *opt.base {
OptChainBase::Member(MemberExpr { span, obj, .. }) => {
//
if is_pure_undefined_or_null(self.expr_ctx, obj) {
self.changed = true;
report_change!(
"evaluate: Reduced an optional chaining operation because object is \
always null or undefined"
);
*e = *Expr::undefined(*span);
}
}
OptChainBase::Call(OptCall { span, callee, .. }) => {
if is_pure_undefined_or_null(self.expr_ctx, callee) {
self.changed = true;
report_change!(
"evaluate: Reduced a call expression with optional chaining operation \
because object is always null or undefined"
);
*e = *Expr::undefined(*span);
}
}
}
}
/// Note: this method requires boolean context.
///
/// - `foo || 1` => `foo, 1`
pub(super) fn optmize_known_logical_expr(&mut self, e: &mut Expr) {
let bin_expr = match e {
Expr::Bin(
e @ BinExpr {
op: op!("||") | op!("&&"),
..
},
) => e,
_ => return,
};
if bin_expr.op == op!("||") {
if let Value::Known(v) = bin_expr.right.as_pure_bool(self.expr_ctx) {
// foo || 1 => foo, 1
if v {
self.changed = true;
report_change!("evaluate: `foo || true` => `foo, 1`");
*e = SeqExpr {
span: bin_expr.span,
exprs: vec![bin_expr.left.clone(), bin_expr.right.clone()],
}
.into();
} else {
self.changed = true;
report_change!("evaluate: `foo || false` => `foo` (bool ctx)");
*e = *bin_expr.left.take();
}
return;
}
// 1 || foo => foo
if let Value::Known(true) = bin_expr.left.as_pure_bool(self.expr_ctx) {
self.changed = true;
report_change!("evaluate: `true || foo` => `foo`");
*e = *bin_expr.right.take();
}
} else {
debug_assert_eq!(bin_expr.op, op!("&&"));
if let Value::Known(v) = bin_expr.right.as_pure_bool(self.expr_ctx) {
if v {
self.changed = true;
report_change!("evaluate: `foo && true` => `foo` (bool ctx)");
*e = *bin_expr.left.take();
} else {
self.changed = true;
report_change!("evaluate: `foo && false` => `foo, false`");
*e = SeqExpr {
span: bin_expr.span,
exprs: vec![bin_expr.left.clone(), bin_expr.right.clone()],
}
.into();
}
return;
}
if let Value::Known(true) = bin_expr.left.as_pure_bool(self.expr_ctx) {
self.changed = true;
report_change!("evaluate: `true && foo` => `foo`");
*e = *bin_expr.right.take();
}
}
}
pub(super) fn eval_trivial_values_in_expr(&mut self, seq: &mut SeqExpr) {
if seq.exprs.len() < 2 {
return;
}
'outer: for idx in 0..seq.exprs.len() {
let (a, b) = seq.exprs.split_at_mut(idx);
for a in a.iter().rev() {
if let Some(b) = b.first_mut() {
self.eval_trivial_two(a, b);
match &**b {
Expr::Ident(..) | Expr::Lit(..) => {}
_ => break 'outer,
}
}
}
}
}
pub(super) fn eval_member_expr(&mut self, e: &mut Expr) {
let member_expr = match e {
Expr::Member(x) => x,
_ => return,
};
if let Some(replacement) =
self.optimize_member_expr(&mut member_expr.obj, &member_expr.prop)
{
*e = replacement;
self.changed = true;
report_change!(
"member_expr: Optimized member expression as {}",
dump(&*e, false)
);
}
}
fn eval_trivial_two(&mut self, a: &Expr, b: &mut Expr) {
if let Expr::Assign(AssignExpr {
left: a_left,
op: op!("="),
right: a_right,
..
}) = a
{
match &**a_right {
Expr::Lit(..) => {}
_ => return,
}
if let AssignTarget::Simple(SimpleAssignTarget::Ident(a_left)) = a_left {
if let Expr::Ident(b_id) = b {
if b_id.to_id() == a_left.id.to_id() {
report_change!("evaluate: Trivial: `{}`", a_left.id);
*b = *a_right.clone();
self.changed = true;
}
}
}
}
}
}
/// Evaluation of strings.
impl Pure<'_> {
/// Handle calls on string literals, like `'foo'.toUpperCase()`.
pub(super) fn eval_str_method_call(&mut self, e: &mut Expr) {
if !self.options.evaluate {
return;
}
if self.ctx.in_delete || self.ctx.is_update_arg || self.ctx.is_lhs_of_assign {
return;
}
let call = match e {
Expr::Call(v) => v,
_ => return,
};
let (s, method) = match &call.callee {
Callee::Super(_) | Callee::Import(_) => return,
Callee::Expr(callee) => match &**callee {
Expr::Member(MemberExpr {
obj,
prop: MemberProp::Ident(prop),
..
}) => match &**obj {
Expr::Lit(Lit::Str(s)) => (s.clone(), prop.sym.clone()),
_ => return,
},
_ => return,
},
};
let new_val = match &*method {
"toLowerCase" => s.value.to_lowercase(),
"toUpperCase" => s.value.to_uppercase(),
"charCodeAt" => {
if call.args.len() != 1 {
return;
}
if let Expr::Lit(Lit::Num(Number { value, .. })) = &*call.args[0].expr {
if value.fract() != 0.0 {
return;
}
let idx = value.round() as i64 as usize;
let c = s.value.chars().nth(idx);
match c {
Some(v) => {
let mut b = [0; 2];
v.encode_utf16(&mut b);
let v = b[0];
self.changed = true;
report_change!(
"evaluate: Evaluated `charCodeAt` of a string literal as `{}`",
v
);
*e = Lit::Num(Number {
span: call.span,
value: v as usize as f64,
raw: None,
})
.into()
}
None => {
self.changed = true;
report_change!(
"evaluate: Evaluated `charCodeAt` of a string literal as `NaN`",
);
*e = Ident::new("NaN".into(), e.span(), SyntaxContext::empty()).into()
}
}
}
return;
}
"codePointAt" => {
if call.args.len() != 1 {
return;
}
if let Expr::Lit(Lit::Num(Number { value, .. })) = &*call.args[0].expr {
if value.fract() != 0.0 {
return;
}
let idx = value.round() as i64 as usize;
let c = s.value.chars().nth(idx);
match c {
Some(v) => {
self.changed = true;
report_change!(
"evaluate: Evaluated `codePointAt` of a string literal as `{}`",
v
);
*e = Lit::Num(Number {
span: call.span,
value: v as usize as f64,
raw: None,
})
.into()
}
None => {
self.changed = true;
report_change!(
"evaluate: Evaluated `codePointAt` of a string literal as `NaN`",
);
*e = Ident::new(
"NaN".into(),
e.span(),
SyntaxContext::empty().apply_mark(self.marks.unresolved_mark),
)
.into()
}
}
}
return;
}
_ => return,
};
self.changed = true;
report_change!("evaluate: Evaluated `{method}` of a string literal");
*e = Lit::Str(Str {
value: new_val.into(),
raw: None,
..s
})
.into();
}
}
// Code from boa
// https://github.com/boa-dev/boa/blob/f8b682085d7fe0bbfcd0333038e93cf2f5aee710/boa_engine/src/builtins/number/mod.rs#L408
fn f64_to_precision(value: f64, precision: usize) -> String {
let mut x = value;
let p_i32 = precision as i32;
// 7. Let s be the empty String.
let mut s = String::new();
let mut m: String;
let mut e: i32;
// 8. If x < 0, then a. Set s to the code unit 0x002D (HYPHEN-MINUS). b. Set x
// to -x.
if x < 0. {
s.push('-');
x = -x;
}
// 9. If x = 0, then a. Let m be the String value consisting of p occurrences of
// the code unit 0x0030 (DIGIT ZERO). b. Let e be 0.
if x == 0.0 {
m = "0".repeat(precision);
e = 0;
// 10
} else {
// Due to f64 limitations, this part differs a bit from the spec,
// but has the same effect. It manipulates the string constructed
// by `format`: digits with an optional dot between two of them.
m = format!("{x:.100}");
// a: getting an exponent
e = flt_str_to_exp(&m);
// b: getting relevant digits only
if e < 0 {
m = m.split_off((1 - e) as usize);
} else if let Some(n) = m.find('.') {
m.remove(n);
}
// impl: having exactly `precision` digits in `suffix`
if round_to_precision(&mut m, precision) {
e += 1;
}
// c: switching to scientific notation
let great_exp = e >= p_i32;
if e < -6 || great_exp {
assert_ne!(e, 0);
// ii
if precision > 1 {
m.insert(1, '.');
}
// vi
m.push('e');
// iii
if great_exp {
m.push('+');
}
// iv, v
m.push_str(&e.to_string());
return s + &*m;
}
}
// 11
let e_inc = e + 1;
if e_inc == p_i32 {
return s + &*m;
}
// 12
if e >= 0 {
m.insert(e_inc as usize, '.');
// 13
} else {
s.push('0');
s.push('.');
s.push_str(&"0".repeat(-e_inc as usize));
}
// 14
s + &*m
}
fn flt_str_to_exp(flt: &str) -> i32 {
let mut non_zero_encountered = false;
let mut dot_encountered = false;
for (i, c) in flt.chars().enumerate() {
if c == '.' {
if non_zero_encountered {
return (i as i32) - 1;
}
dot_encountered = true;
} else if c != '0' {
if dot_encountered {
return 1 - (i as i32);
}
non_zero_encountered = true;
}
}
(flt.len() as i32) - 1
}
fn round_to_precision(digits: &mut String, precision: usize) -> bool {
if digits.len() > precision {
let to_round = digits.split_off(precision);
let mut digit = digits
.pop()
.expect("already checked that length is bigger than precision")
as u8;
if let Some(first) = to_round.chars().next() {
if first > '4' {
digit += 1;
}
}
if digit as char == ':' {
// ':' is '9' + 1
// need to propagate the increment backward
let mut replacement = String::from("0");
let mut propagated = false;
for c in digits.chars().rev() {
let d = match (c, propagated) {
('0'..='8', false) => (c as u8 + 1) as char,
(_, false) => '0',
(_, true) => c,
};
replacement.push(d);
if d != '0' {
propagated = true;
}
}
digits.clear();
let replacement = if propagated {
replacement.as_str()
} else {
digits.push('1');
&replacement.as_str()[1..]
};
for c in replacement.chars().rev() {
digits.push(c);
}
!propagated
} else {
digits.push(digit as char);
false
}
} else {
digits.push_str(&"0".repeat(precision - digits.len()));
false
}
}
/// Helper function that formats a float as a ES6-style exponential number
/// string.
fn f64_to_exponential(n: f64) -> String {
match n.abs() {
x if x >= 1.0 || x == 0.0 => format!("{n:e}").replace('e', "e+"),
_ => format!("{n:e}"),
}
}
/// Helper function that formats a float as a ES6-style exponential number
/// string with a given precision.
// We can't use the same approach as in `f64_to_exponential`
// because in cases like (0.999).toExponential(0) the result will be 1e0.
// Instead we get the index of 'e', and if the next character is not '-'
// we insert the plus sign
fn f64_to_exponential_with_precision(n: f64, prec: usize) -> String {
let mut res = format!("{n:.prec$e}");
let idx = res.find('e').expect("'e' not found in exponential string");
if res.as_bytes()[idx + 1] != b'-' {
res.insert(idx + 1, '+');
}
res
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/compress/pure/if_return.rs | Rust | use swc_common::{util::take::Take, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_utils::prepend_stmt;
use super::Pure;
use crate::compress::util::{is_fine_for_if_cons, negate};
impl Pure<'_> {
/// # Input
///
/// ```js
/// function f(a, b) {
/// if (a) return;
/// console.log(b);
/// }
/// ```
///
/// # Output
/// ```js
/// function f(a, b) {
/// if (!a)
/// console.log(b);
/// }
/// ```
#[allow(clippy::unnecessary_filter_map)]
pub(super) fn negate_if_terminate(
&mut self,
stmts: &mut Vec<Stmt>,
handle_return: bool,
handle_continue: bool,
) {
if handle_return {
if !self.options.if_return || !self.options.bools {
return;
}
if stmts.len() == 1 {
for s in stmts.iter_mut() {
if let Stmt::If(s) = s {
if let Stmt::Block(cons) = &mut *s.cons {
self.negate_if_terminate(&mut cons.stmts, true, false);
}
}
}
}
}
let len = stmts.len();
let pos_of_if = stmts.iter().enumerate().rposition(|(idx, s)| {
idx != len - 1
&& match s {
Stmt::If(IfStmt {
cons, alt: None, ..
}) => match &**cons {
Stmt::Return(ReturnStmt { arg: None, .. }) => handle_return,
Stmt::Continue(ContinueStmt { label: None, .. }) => handle_continue,
_ => false,
},
_ => false,
}
});
let pos_of_if = match pos_of_if {
Some(v) => v,
_ => return,
};
// If we negate a block, these variables will have narrower scope.
if stmts[pos_of_if..].iter().any(|s| match s {
Stmt::Decl(Decl::Var(v))
if matches!(
&**v,
VarDecl {
kind: VarDeclKind::Const | VarDeclKind::Let,
..
}
) =>
{
true
}
_ => false,
}) {
return;
}
self.changed = true;
report_change!(
"if_return: Negating `foo` in `if (foo) return; bar()` to make it `if (!foo) bar()`"
);
let mut new = Vec::with_capacity(stmts.len());
let mut fn_decls = Vec::with_capacity(stmts.len());
new.extend(stmts.drain(..pos_of_if));
let cons = stmts
.drain(1..)
.filter_map(|stmt| {
if matches!(stmt, Stmt::Decl(Decl::Fn(..))) {
fn_decls.push(stmt);
return None;
}
Some(stmt)
})
.collect::<Vec<_>>();
let if_stmt = stmts.take().into_iter().next().unwrap();
match if_stmt {
Stmt::If(mut s) => {
assert_eq!(s.alt, None);
negate(self.expr_ctx, &mut s.test, false, false);
s.cons = if cons.len() == 1 && is_fine_for_if_cons(&cons[0]) {
Box::new(cons.into_iter().next().unwrap())
} else {
Box::new(
BlockStmt {
span: DUMMY_SP,
stmts: cons,
..Default::default()
}
.into(),
)
};
new.push(s.into())
}
_ => {
unreachable!()
}
}
new.extend(fn_decls);
*stmts = new;
}
pub(super) fn merge_else_if(&mut self, s: &mut IfStmt) {
if let Some(Stmt::If(IfStmt {
span: span_of_alt,
test: test_of_alt,
cons: cons_of_alt,
alt: Some(alt_of_alt),
..
})) = s.alt.as_deref_mut()
{
match &**cons_of_alt {
Stmt::Return(..) | Stmt::Continue(ContinueStmt { label: None, .. }) => {}
_ => return,
}
match &mut **alt_of_alt {
Stmt::Block(..) => {}
Stmt::Expr(..) => {
*alt_of_alt = Box::new(
BlockStmt {
span: DUMMY_SP,
stmts: vec![*alt_of_alt.take()],
..Default::default()
}
.into(),
);
}
_ => {
return;
}
}
self.changed = true;
report_change!("if_return: Merging `else if` into `else`");
match &mut **alt_of_alt {
Stmt::Block(alt_of_alt) => {
prepend_stmt(
&mut alt_of_alt.stmts,
IfStmt {
span: *span_of_alt,
test: test_of_alt.take(),
cons: cons_of_alt.take(),
alt: None,
}
.into(),
);
}
_ => {
unreachable!()
}
}
s.alt = Some(alt_of_alt.take());
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/compress/pure/loops.rs | Rust | use swc_common::{util::take::Take, Spanned};
use swc_ecma_ast::*;
use swc_ecma_utils::{ExprExt, Value};
use super::Pure;
impl Pure<'_> {
///
/// - `while(test);` => `for(;;test);
/// - `do; while(true)` => `for(;;);
pub(super) fn loop_to_for_stmt(&mut self, s: &mut Stmt) {
if !self.options.loops {
return;
}
match s {
Stmt::While(stmt) => {
self.changed = true;
report_change!("loops: Converting a while loop to a for loop");
*s = ForStmt {
span: stmt.span,
init: None,
test: Some(stmt.test.take()),
update: None,
body: stmt.body.take(),
}
.into();
}
Stmt::DoWhile(stmt) => {
let val = stmt.test.as_pure_bool(self.expr_ctx);
if let Value::Known(true) = val {
self.changed = true;
report_change!("loops: Converting an always-true do-while loop to a for loop");
*s = ForStmt {
span: stmt.span,
init: None,
test: Some(stmt.test.take()),
update: None,
body: stmt.body.take(),
}
.into();
}
}
_ => {}
}
}
/// ## Input
/// ```js
/// for(; bar();){
/// if (x(), y(), foo()) break;
/// z(), k();
/// }
/// ```
///
/// ## Output
///
/// ```js
/// for(; bar() && (x(), y(), !foo());)z(), k();
/// ```
pub(super) fn optimize_for_if_break(&mut self, s: &mut ForStmt) -> Option<()> {
if !self.options.loops {
return None;
}
if let Stmt::Block(body) = &mut *s.body {
let first = body.stmts.get_mut(0)?;
if let Stmt::If(IfStmt {
span,
test,
cons,
alt: None,
..
}) = first
{
if let Stmt::Break(BreakStmt { label: None, .. }) = &**cons {
self.negate(test, false, false);
match s.test.as_deref_mut() {
Some(e) => {
let orig_test = e.take();
*e = BinExpr {
span: *span,
op: op!("&&"),
left: Box::new(orig_test),
right: test.take(),
}
.into();
}
None => {
s.test = Some(test.take());
}
}
report_change!("loops: Optimizing a for loop with an if-then-break");
first.take();
return None;
}
}
if let Stmt::If(IfStmt {
span,
test,
cons,
alt: Some(alt),
..
}) = first
{
if let Stmt::Break(BreakStmt { label: None, .. }) = &**alt {
match s.test.as_deref_mut() {
Some(e) => {
let orig_test = e.take();
*e = BinExpr {
span: *span,
op: op!("&&"),
left: Box::new(orig_test),
right: test.take(),
}
.into();
}
None => {
s.test = Some(test.take());
}
}
report_change!("loops: Optimizing a for loop with an if-else-break");
*first = *cons.take();
return None;
}
}
}
None
}
/// # Input
///
/// ```js
/// for(; size--;)
/// if (!(result = eq(a[size], b[size], aStack, bStack)))
/// break;
/// ```
///
///
/// # Output
///
/// ```js
/// for (; size-- && (result = eq(a[size], b[size], aStack, bStack)););
/// ```
pub(super) fn merge_for_if_break(&mut self, s: &mut ForStmt) {
if let Stmt::If(IfStmt {
test,
cons,
alt: None,
..
}) = &mut *s.body
{
if let Stmt::Break(BreakStmt { label: None, .. }) = &**cons {
// We only care about instant breaks.
//
// Note: As the minifier of swc is very fast, we don't
// care about block statements with a single break as a
// body.
//
// If it's optimizable, other pass for if statements
// will remove block and with the next pass we can apply
// this pass.
self.changed = true;
report_change!("loops: Compressing for-if-break into a for statement");
// We negate because this `test` is used as a condition for `break`.
self.negate(test, true, false);
match s.test.take() {
Some(left) => {
s.test = Some(
BinExpr {
span: s.test.span(),
op: op!("&&"),
left,
right: test.take(),
}
.into(),
);
}
None => {
s.test = Some(test.take());
}
}
// Remove body
s.body.take();
}
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/compress/pure/member_expr.rs | Rust | use phf::phf_set;
use swc_atoms::Atom;
use swc_common::Spanned;
use swc_ecma_ast::{
ArrayLit, Expr, ExprOrSpread, IdentName, Lit, MemberExpr, MemberProp, ObjectLit, Prop,
PropOrSpread, SeqExpr, Str,
};
use swc_ecma_utils::{prop_name_eq, ExprExt, Known};
use super::Pure;
/// Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
static ARRAY_SYMBOLS: phf::Set<&str> = phf_set!(
// Constructor
"constructor",
// Properties
"length",
// Methods
"at",
"concat",
"copyWithin",
"entries",
"every",
"fill",
"filter",
"find",
"findIndex",
"findLast",
"findLastIndex",
"flat",
"flatMap",
"forEach",
"includes",
"indexOf",
"join",
"keys",
"lastIndexOf",
"map",
"pop",
"push",
"reduce",
"reduceRight",
"reverse",
"shift",
"slice",
"some",
"sort",
"splice",
"toLocaleString",
"toReversed",
"toSorted",
"toSpliced",
"toString",
"unshift",
"values",
"with"
);
/// Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
static STRING_SYMBOLS: phf::Set<&str> = phf_set!(
// Constructor
"constructor",
// Properties
"length",
// Methods
"anchor",
"at",
"big",
"blink",
"bold",
"charAt",
"charCodeAt",
"codePointAt",
"concat",
"endsWith",
"fixed",
"fontcolor",
"fontsize",
"includes",
"indexOf",
"isWellFormed",
"italics",
"lastIndexOf",
"link",
"localeCompare",
"match",
"matchAll",
"normalize",
"padEnd",
"padStart",
"repeat",
"replace",
"replaceAll",
"search",
"slice",
"small",
"split",
"startsWith",
"strike",
"sub",
"substr",
"substring",
"sup",
"toLocaleLowerCase",
"toLocaleUpperCase",
"toLowerCase",
"toString",
"toUpperCase",
"toWellFormed",
"trim",
"trimEnd",
"trimStart",
"valueOf"
);
/// Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
static OBJECT_SYMBOLS: phf::Set<&str> = phf_set!(
// Constructor
"constructor",
// Properties
"__proto__",
// Methods
"__defineGetter__",
"__defineSetter__",
"__lookupGetter__",
"__lookupSetter__",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"toLocaleString",
"toString",
"valueOf",
// removed, but kept in as these are often checked and polyfilled
"watch",
"unwatch"
);
fn is_object_symbol(sym: &str) -> bool {
OBJECT_SYMBOLS.contains(sym)
}
fn is_array_symbol(sym: &str) -> bool {
// Inherits: Object
ARRAY_SYMBOLS.contains(sym) || is_object_symbol(sym)
}
fn is_string_symbol(sym: &str) -> bool {
// Inherits: Object
STRING_SYMBOLS.contains(sym) || is_object_symbol(sym)
}
/// Checks if the given key exists in the given properties, taking the
/// `__proto__` property and order of keys into account (the order of keys
/// matters for nested `__proto__` properties).
///
/// Returns `None` if the key's existence is uncertain, or `Some` if it is
/// certain.
///
/// A key's existence is uncertain if a `__proto__` property exists and the
/// value is non-literal.
fn does_key_exist(key: &str, props: &Vec<PropOrSpread>) -> Option<bool> {
for prop in props {
match prop {
PropOrSpread::Prop(prop) => match &**prop {
Prop::Shorthand(ident) => {
if ident.sym == key {
return Some(true);
}
}
Prop::KeyValue(prop) => {
if key != "__proto__" && prop_name_eq(&prop.key, "__proto__") {
// If __proto__ is defined, we need to check the contents of it,
// as well as any nested __proto__ objects
if let Some(object) = prop.value.as_object() {
// __proto__ is an ObjectLiteral, check if key exists in it
let exists = does_key_exist(key, &object.props);
if exists.is_none() {
return None;
} else if exists.is_some_and(|exists| exists) {
return Some(true);
}
} else {
// __proto__ is not a literal, it is impossible to know if the
// key exists or not
return None;
}
} else {
// Normal key
if prop_name_eq(&prop.key, key) {
return Some(true);
}
}
}
// invalid
Prop::Assign(_) => {
return None;
}
Prop::Getter(getter) => {
if prop_name_eq(&getter.key, key) {
return Some(true);
}
}
Prop::Setter(setter) => {
if prop_name_eq(&setter.key, key) {
return Some(true);
}
}
Prop::Method(method) => {
if prop_name_eq(&method.key, key) {
return Some(true);
}
}
},
_ => {
return None;
}
}
}
// No key was found and there's no uncertainty, meaning the key certainly
// doesn't exist
Some(false)
}
impl Pure<'_> {
/// Optimizes the following:
///
/// - `''[0]`, `''[1]`, `''[-1]` -> `void 0`
/// - `''[[]]` -> `void 0`
/// - `''["a"]`, `''.a` -> `void 0`
///
/// For String, Array and Object literals.
/// Special cases like `''.charCodeAt`, `[].push` etc are kept intact.
/// In-bound indexes (like `[1][0]`) and `length` are handled in the
/// simplifier.
///
/// Does nothing if `pristine_globals` is `false`.
pub(super) fn optimize_member_expr(
&mut self,
obj: &mut Expr,
prop: &MemberProp,
) -> Option<Expr> {
if !self.options.pristine_globals || self.ctx.is_lhs_of_assign || self.ctx.is_callee {
return None;
}
/// Taken from `simplify::expr`.
///
/// `x.length` is handled as `IndexStr`, since `x.length` calls for
/// String and Array are handled in `simplify::expr` (the `length`
/// prototype for both of these types cannot be changed).
#[derive(Clone, PartialEq)]
enum KnownOp {
// [a, b][2]
//
// ({})[1]
Index(f64),
/// ({}).foo
///
/// ({}).length
IndexStr(Atom),
}
let op = match prop {
MemberProp::Ident(IdentName { sym, .. }) => {
if self.ctx.is_callee {
return None;
}
KnownOp::IndexStr(sym.clone())
}
MemberProp::Computed(c) => match &*c.expr {
Expr::Lit(Lit::Num(n)) => KnownOp::Index(n.value),
Expr::Ident(..) => {
return None;
}
_ => {
let Known(s) = c.expr.as_pure_string(self.expr_ctx) else {
return None;
};
if let Ok(n) = s.parse::<f64>() {
KnownOp::Index(n)
} else {
KnownOp::IndexStr(Atom::from(s))
}
}
},
_ => {
return None;
}
};
match obj {
Expr::Seq(SeqExpr { exprs, span }) => {
// Optimize when last value in a SeqExpr is being indexed
// while preserving side effects.
//
// (0, {a: 5}).a
//
// (0, f(), {a: 5}).a
//
// (0, f(), [1, 2])[0]
//
// etc.
// Try to optimize with obj being the last expr
let replacement = self.optimize_member_expr(exprs.last_mut()?, prop)?;
// Replace last element with replacement
let mut exprs: Vec<Box<Expr>> = exprs.drain(..(exprs.len() - 1)).collect();
exprs.push(Box::new(replacement));
Some(SeqExpr { span: *span, exprs }.into())
}
Expr::Lit(Lit::Str(Str { value, span, .. })) => {
match op {
KnownOp::Index(idx) => {
if idx.fract() != 0.0 || idx < 0.0 || idx as usize >= value.len() {
Some(*Expr::undefined(*span))
} else {
// idx is in bounds, this is handled in simplify
None
}
}
KnownOp::IndexStr(key) => {
if key == "length" {
// handled in simplify::expr
return None;
}
if is_string_symbol(key.as_str()) {
None
} else {
Some(*Expr::undefined(*span))
}
}
}
}
Expr::Array(ArrayLit { elems, span, .. }) => {
// do nothing if spread exists
let has_spread = elems.iter().any(|elem| {
elem.as_ref()
.map(|elem| elem.spread.is_some())
.unwrap_or(false)
});
if has_spread {
return None;
}
match op {
KnownOp::Index(idx) => {
if idx >= 0.0 && (idx as usize) < elems.len() && idx.fract() == 0.0 {
// idx is in bounds, handled in simplify
return None;
}
// Replacement is certain at this point, and is always undefined
// Extract side effects
let mut exprs = Vec::new();
elems.drain(..).flatten().for_each(|elem| {
self.expr_ctx.extract_side_effects_to(&mut exprs, *elem.expr);
});
Some(if exprs.is_empty() {
// No side effects, replacement is:
// (0, void 0)
SeqExpr {
span: *span,
exprs: vec![0.into(), Expr::undefined(*span)]
}.into()
} else {
// Side effects exist, replacement is:
// (x(), y(), void 0)
// Where `x()` and `y()` are side effects.
exprs.push(Expr::undefined(*span));
SeqExpr {
span: *span,
exprs
}.into()
})
}
KnownOp::IndexStr(key) if key != "length" /* handled in simplify */ => {
// If the property is a known symbol, e.g. [].push
let is_known_symbol = is_array_symbol(&key);
if is_known_symbol {
// We need to check if this is already optimized as if we don't,
// it'll lead to infinite optimization when the visitor visits
// again.
//
// A known symbol expression is already optimized if all
// non-side effects have been removed.
let optimized_len = elems
.iter()
.flatten()
.filter(|elem| elem.expr.may_have_side_effects(self.expr_ctx))
.count();
if optimized_len == elems.len() {
// Already optimized
return None;
}
}
// Extract side effects
let mut exprs = Vec::new();
elems.drain(..).flatten().for_each(|elem| {
self.expr_ctx.extract_side_effects_to(&mut exprs, *elem.expr);
});
Some(if is_known_symbol {
// [x(), y()].push
MemberExpr {
span: *span,
obj: ArrayLit {
span: *span,
elems: exprs
.into_iter()
.map(|elem| Some(ExprOrSpread {
spread: None,
expr: elem,
}))
.collect()
}.into(),
prop: prop.clone(),
}.into()
} else {
let val = Expr::undefined(
*span);
if exprs.is_empty() {
// No side effects, replacement is:
// (0, void 0)
SeqExpr {
span: val.span(),
exprs: vec![0.into(), val]
}.into()
} else {
// Side effects exist, replacement is:
// (x(), y(), void 0)
// Where `x()` and `y()` are side effects.
exprs.push(val);
SeqExpr {
span: *span,
exprs
}.into()
}
})
}
_ => None
}
}
Expr::Object(ObjectLit { props, span }) => {
// Do nothing if there are invalid keys.
//
// Objects with one or more keys that are not literals or identifiers
// are impossible to optimize as we don't know for certain if a given
// key is actually invalid, e.g. `{[bar()]: 5}`, since we don't know
// what `bar()` returns.
let contains_invalid_key = props
.iter()
.any(|prop| !matches!(prop, PropOrSpread::Prop(prop) if matches!(&**prop, Prop::KeyValue(kv) if kv.key.is_ident() || kv.key.is_str() || kv.key.is_num())));
if contains_invalid_key {
return None;
}
// Get key as Atom
let key = match op {
KnownOp::Index(i) => Atom::from(i.to_string()),
KnownOp::IndexStr(key) if key != *"yield" => key,
_ => {
return None;
}
};
// Check if key exists
let exists = does_key_exist(&key, props);
if exists.is_none() || exists.is_some_and(|exists| exists) {
// Valid properties are handled in simplify
return None;
}
let is_known_symbol = is_object_symbol(&key);
if is_known_symbol {
// Like with arrays, we need to check if this is already optimized
// before returning Some so we don't end up in an infinite loop.
//
// The same logic with arrays applies; read above.
let optimized_len = props
.iter()
.filter(|prop| {
matches!(prop, PropOrSpread::Prop(prop) if matches!(&**prop, Prop::KeyValue(prop) if prop.value.may_have_side_effects(self.expr_ctx)))
})
.count();
if optimized_len == props.len() {
// Already optimized
return None;
}
}
// Can be optimized fully or partially
Some(*self.expr_ctx.preserve_effects(
*span,
if is_known_symbol {
// Valid key, e.g. "hasOwnProperty". Replacement:
// (foo(), bar(), {}.hasOwnProperty)
MemberExpr {
span: *span,
obj: ObjectLit {
span: *span,
props: Vec::new(),
}
.into(),
prop: MemberProp::Ident(IdentName::new(key, *span)),
}
.into()
} else {
// Invalid key. Replace with side effects plus `undefined`.
Expr::undefined(*span)
},
props.drain(..).map(|x| match x {
PropOrSpread::Prop(prop) => match *prop {
Prop::KeyValue(kv) => kv.value,
_ => unreachable!(),
},
_ => unreachable!(),
}),
))
}
_ => None,
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/compress/pure/misc.rs | Rust | use std::{fmt::Write, num::FpCategory};
use rustc_hash::FxHashSet;
use swc_atoms::{atom, Atom};
use swc_common::{iter::IdentifyLast, util::take::Take, Span, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_transforms_optimization::debug_assert_valid;
use swc_ecma_usage_analyzer::util::is_global_var_with_pure_property_access;
use swc_ecma_utils::{
ExprExt, ExprFactory, IdentUsageFinder, Type,
Value::{self, Known},
};
use super::Pure;
use crate::compress::{
pure::strings::{convert_str_value_to_tpl_cooked, convert_str_value_to_tpl_raw},
util::is_pure_undefined,
};
fn is_definitely_string(expr: &Expr) -> bool {
match expr {
Expr::Lit(Lit::Str(_)) => true,
Expr::Tpl(_) => true,
Expr::Bin(BinExpr {
op: BinaryOp::Add,
left,
right,
..
}) => is_definitely_string(left) || is_definitely_string(right),
Expr::Paren(ParenExpr { expr, .. }) => is_definitely_string(expr),
_ => false,
}
}
/// Check whether we can compress `new RegExp(…)` to `RegExp(…)`. That's sound
/// unless the first argument is already a RegExp object and the second is
/// undefined. We check for the common case where we can prove one of the first
/// two arguments is a string.
fn can_compress_new_regexp(args: Option<&[ExprOrSpread]>) -> bool {
if let Some(args) = args {
if let Some(first) = args.first() {
if first.spread.is_some() {
false
} else if is_definitely_string(&first.expr) {
true
} else if let Some(second) = args.get(1) {
second.spread.is_none() && is_definitely_string(&second.expr)
} else {
false
}
} else {
true
}
} else {
true
}
}
fn collect_exprs_from_object(obj: &mut ObjectLit) -> Vec<Box<Expr>> {
let mut exprs = Vec::new();
for prop in obj.props.take() {
if let PropOrSpread::Prop(p) = prop {
match *p {
Prop::Shorthand(p) => {
exprs.push(p.into());
}
Prop::KeyValue(p) => {
if let PropName::Computed(e) = p.key {
exprs.push(e.expr);
}
exprs.push(p.value);
}
Prop::Getter(p) => {
if let PropName::Computed(e) = p.key {
exprs.push(e.expr);
}
}
Prop::Setter(p) => {
if let PropName::Computed(e) = p.key {
exprs.push(e.expr);
}
}
Prop::Method(p) => {
if let PropName::Computed(e) = p.key {
exprs.push(e.expr);
}
}
_ => {}
}
}
}
exprs
}
impl Pure<'_> {
/// `foo(...[1, 2])`` => `foo(1, 2)`
pub(super) fn eval_spread_array(&mut self, args: &mut Vec<ExprOrSpread>) {
if args
.iter()
.all(|arg| arg.spread.is_none() || !arg.expr.is_array())
{
return;
}
let mut new_args = Vec::new();
for arg in args.take() {
match arg {
ExprOrSpread {
spread: Some(spread),
expr,
} => match *expr {
Expr::Array(ArrayLit { elems, .. }) => {
for elem in elems {
match elem {
Some(ExprOrSpread { expr, spread }) => {
new_args.push(ExprOrSpread { spread, expr });
}
None => {
new_args.push(ExprOrSpread {
spread: None,
expr: Expr::undefined(DUMMY_SP),
});
}
}
}
}
_ => {
new_args.push(ExprOrSpread {
spread: Some(spread),
expr,
});
}
},
arg => new_args.push(arg),
}
}
self.changed = true;
report_change!("Compressing spread array");
*args = new_args;
}
pub(super) fn remove_invalid(&mut self, e: &mut Expr) {
match e {
Expr::Seq(seq) => {
for e in &mut seq.exprs {
self.remove_invalid(e);
}
if seq.exprs.len() == 1 {
*e = *seq.exprs.pop().unwrap();
}
}
Expr::Bin(BinExpr { left, right, .. }) => {
self.remove_invalid(left);
self.remove_invalid(right);
if left.is_invalid() {
*e = *right.take();
self.remove_invalid(e);
} else if right.is_invalid() {
*e = *left.take();
self.remove_invalid(e);
}
}
_ => {}
}
}
pub(super) fn compress_array_join(&mut self, e: &mut Expr) {
let call = match e {
Expr::Call(e) => e,
_ => return,
};
let callee = match &mut call.callee {
Callee::Super(_) | Callee::Import(_) => return,
Callee::Expr(callee) => &mut **callee,
};
let separator = if call.args.is_empty() {
",".into()
} else if call.args.len() == 1 {
if call.args[0].spread.is_some() {
return;
}
if is_pure_undefined(self.expr_ctx, &call.args[0].expr) {
",".into()
} else {
match &*call.args[0].expr {
Expr::Lit(Lit::Str(s)) => s.value.clone(),
Expr::Lit(Lit::Null(..)) => "null".into(),
_ => return,
}
}
} else {
return;
};
let arr = match callee {
Expr::Member(MemberExpr {
obj,
prop: MemberProp::Ident(IdentName { sym, .. }),
..
}) if *sym == *"join" => {
if let Expr::Array(arr) = &mut **obj {
arr
} else {
return;
}
}
_ => return,
};
if arr.elems.iter().any(|elem| {
matches!(
elem,
Some(ExprOrSpread {
spread: Some(..),
..
})
)
}) {
return;
}
let cannot_join_as_str_lit = arr
.elems
.iter()
.filter_map(|v| v.as_ref())
.any(|v| match &*v.expr {
e if is_pure_undefined(self.expr_ctx, e) => false,
Expr::Lit(lit) => !matches!(lit, Lit::Str(..) | Lit::Num(..) | Lit::Null(..)),
_ => true,
});
if cannot_join_as_str_lit {
if let Some(new_expr) =
self.compress_array_join_as_tpl(arr.span, &mut arr.elems, &separator)
{
self.changed = true;
*e = new_expr;
return;
}
if !self.options.unsafe_passes {
return;
}
// TODO: Partial join
if arr
.elems
.iter()
.filter_map(|v| v.as_ref())
.any(|v| match &*v.expr {
e if is_pure_undefined(self.expr_ctx, e) => false,
Expr::Lit(lit) => !matches!(lit, Lit::Str(..) | Lit::Num(..) | Lit::Null(..)),
// This can change behavior if the value is `undefined` or `null`.
Expr::Ident(..) => false,
_ => true,
})
{
return;
}
let sep: Box<Expr> = Lit::Str(Str {
span: DUMMY_SP,
raw: None,
value: separator,
})
.into();
let mut res = Lit::Str(Str {
span: DUMMY_SP,
raw: None,
value: atom!(""),
})
.into();
fn add(to: &mut Expr, right: Box<Expr>) {
let lhs = to.take();
*to = BinExpr {
span: DUMMY_SP,
left: Box::new(lhs),
op: op!(bin, "+"),
right,
}
.into();
}
for (last, elem) in arr.elems.take().into_iter().identify_last() {
if let Some(ExprOrSpread { spread: None, expr }) = elem {
match &*expr {
e if is_pure_undefined(self.expr_ctx, e) => {}
Expr::Lit(Lit::Null(..)) => {}
_ => {
add(&mut res, expr);
}
}
}
if !last {
add(&mut res, sep.clone());
}
}
*e = res;
return;
}
let mut res = String::new();
for (last, elem) in arr.elems.iter().identify_last() {
if let Some(elem) = elem {
debug_assert_eq!(elem.spread, None);
match &*elem.expr {
Expr::Lit(Lit::Str(s)) => {
res.push_str(&s.value);
}
Expr::Lit(Lit::Num(n)) => {
write!(res, "{}", n.value).unwrap();
}
e if is_pure_undefined(self.expr_ctx, e) => {}
Expr::Lit(Lit::Null(..)) => {}
_ => {
unreachable!(
"Expression {:#?} cannot be joined and it should be filtered out",
elem.expr
)
}
}
}
if !last {
res.push_str(&separator);
}
}
report_change!("Compressing array.join()");
self.changed = true;
*e = Lit::Str(Str {
span: call.span,
raw: None,
value: res.into(),
})
.into()
}
pub(super) fn drop_undefined_from_return_arg(&mut self, s: &mut ReturnStmt) {
if let Some(e) = s.arg.as_deref() {
if is_pure_undefined(self.expr_ctx, e) {
self.changed = true;
report_change!("Dropped `undefined` from `return undefined`");
s.arg.take();
}
}
}
pub(super) fn remove_useless_return(&mut self, stmts: &mut Vec<Stmt>) {
if !self.options.dead_code {
return;
}
if let Some(Stmt::Return(ReturnStmt { arg: None, .. })) = stmts.last() {
self.changed = true;
report_change!("misc: Removing useless return");
stmts.pop();
}
}
/// `new RegExp("([Sap]+)", "ig")` => `/([Sap]+)/gi`
fn optimize_regex(&mut self, args: &mut Vec<ExprOrSpread>, span: &mut Span) -> Option<Expr> {
fn valid_pattern(pattern: &Expr) -> Option<Atom> {
if let Expr::Lit(Lit::Str(s)) = pattern {
if s.value.contains(|c: char| {
// whitelist
!c.is_ascii_alphanumeric()
&& !matches!(c, '$' | '[' | ']' | '(' | ')' | '{' | '}' | '-' | '+' | '_')
}) {
None
} else {
Some(s.value.clone())
}
} else {
None
}
}
fn valid_flag(flag: &Expr, es_version: EsVersion) -> Option<Atom> {
if let Expr::Lit(Lit::Str(s)) = flag {
let mut set = FxHashSet::default();
for c in s.value.chars() {
if !(matches!(c, 'g' | 'i' | 'm')
|| (es_version >= EsVersion::Es2015 && matches!(c, 'u' | 'y'))
|| (es_version >= EsVersion::Es2018 && matches!(c, 's')))
|| (es_version >= EsVersion::Es2022 && matches!(c, 'd'))
{
return None;
}
if !set.insert(c) {
return None;
}
}
Some(s.value.clone())
} else {
None
}
}
let (pattern, flag) = match args.as_slice() {
[ExprOrSpread { spread: None, expr }] => (valid_pattern(expr)?, "".into()),
[ExprOrSpread {
spread: None,
expr: pattern,
}, ExprOrSpread {
spread: None,
expr: flag,
}] => (
valid_pattern(pattern)?,
valid_flag(flag, self.options.ecma)?,
),
_ => return None,
};
if pattern.is_empty() {
// For some expressions `RegExp()` and `RegExp("")`
// Theoretically we can use `/(?:)/` to achieve shorter code
// But some browsers released in 2015 don't support them yet.
return None;
}
report_change!("Optimized regex");
Some(
Lit::Regex(Regex {
span: *span,
exp: pattern,
flags: {
let flag = flag.to_string();
let mut bytes = flag.into_bytes();
bytes.sort_unstable();
String::from_utf8(bytes).unwrap().into()
},
})
.into(),
)
}
/// Array() -> []
fn optimize_array(&mut self, args: &mut Vec<ExprOrSpread>, span: &mut Span) -> Option<Expr> {
if args.len() == 1 {
if let ExprOrSpread { spread: None, expr } = &args[0] {
match &**expr {
Expr::Lit(Lit::Num(num)) => {
if num.value <= 5_f64 && num.value >= 0_f64 {
Some(
ArrayLit {
span: *span,
elems: vec![None; num.value as usize],
}
.into(),
)
} else {
None
}
}
Expr::Lit(_) => Some(
ArrayLit {
span: *span,
elems: vec![args.take().into_iter().next()],
}
.into(),
),
_ => None,
}
} else {
None
}
} else {
Some(
ArrayLit {
span: *span,
elems: args.take().into_iter().map(Some).collect(),
}
.into(),
)
}
}
/// Object -> {}
fn optimize_object(&mut self, args: &mut Vec<ExprOrSpread>, span: &mut Span) -> Option<Expr> {
if args.is_empty() {
Some(
ObjectLit {
span: *span,
props: Vec::new(),
}
.into(),
)
} else {
None
}
}
pub(super) fn optimize_opt_chain(&mut self, e: &mut Expr) {
let opt = match e {
Expr::OptChain(c) => c,
_ => return,
};
if let OptChainBase::Member(base) = &mut *opt.base {
if match &*base.obj {
Expr::Lit(Lit::Null(..)) => false,
Expr::Lit(..) | Expr::Object(..) | Expr::Array(..) => true,
_ => false,
} {
self.changed = true;
report_change!("Optimized optional chaining expression where object is not null");
*e = MemberExpr {
span: opt.span,
obj: base.obj.take(),
prop: base.prop.take(),
}
.into();
}
}
}
/// new Array(...) -> Array(...)
pub(super) fn optimize_builtin_object(&mut self, e: &mut Expr) {
if !self.options.pristine_globals {
return;
}
match e {
Expr::New(NewExpr {
span,
callee,
args: Some(args),
..
})
| Expr::Call(CallExpr {
span,
callee: Callee::Expr(callee),
args,
..
}) if callee.is_one_of_global_ref_to(self.expr_ctx, &["Array", "Object", "RegExp"]) => {
let new_expr = match &**callee {
Expr::Ident(Ident { sym, .. }) if &**sym == "RegExp" => {
self.optimize_regex(args, span)
}
Expr::Ident(Ident { sym, .. }) if &**sym == "Array" => {
self.optimize_array(args, span)
}
Expr::Ident(Ident { sym, .. }) if &**sym == "Object" => {
self.optimize_object(args, span)
}
_ => unreachable!(),
};
if let Some(new_expr) = new_expr {
report_change!(
"Converting Regexp/Array/Object call to native constructor into literal"
);
self.changed = true;
*e = new_expr;
return;
}
}
Expr::Call(CallExpr {
span,
callee: Callee::Expr(callee),
args,
..
}) if callee.is_one_of_global_ref_to(
self.expr_ctx,
&["Boolean", "Number", "String", "Symbol"],
) =>
{
let new_expr = match &**callee {
Expr::Ident(Ident { sym, .. }) if &**sym == "Boolean" => match &mut args[..] {
[] => Some(
Lit::Bool(Bool {
span: *span,
value: false,
})
.into(),
),
[ExprOrSpread { spread: None, expr }] => Some(
UnaryExpr {
span: *span,
op: op!("!"),
arg: UnaryExpr {
span: *span,
op: op!("!"),
arg: expr.take(),
}
.into(),
}
.into(),
),
_ => None,
},
Expr::Ident(Ident { sym, .. }) if &**sym == "Number" => match &mut args[..] {
[] => Some(
Lit::Num(Number {
span: *span,
value: 0.0,
raw: None,
})
.into(),
),
// this is indeed very unsafe in case of BigInt
[ExprOrSpread { spread: None, expr }] if self.options.unsafe_math => Some(
UnaryExpr {
span: *span,
op: op!(unary, "+"),
arg: expr.take(),
}
.into(),
),
_ => None,
},
Expr::Ident(Ident { sym, .. }) if &**sym == "String" => match &mut args[..] {
[] => Some(
Lit::Str(Str {
span: *span,
value: "".into(),
raw: None,
})
.into(),
),
// this is also very unsafe in case of Symbol
[ExprOrSpread { spread: None, expr }] if self.options.unsafe_passes => {
Some(
BinExpr {
span: *span,
left: expr.take(),
op: op!(bin, "+"),
right: Lit::Str(Str {
span: *span,
value: "".into(),
raw: None,
})
.into(),
}
.into(),
)
}
_ => None,
},
Expr::Ident(Ident { sym, .. }) if &**sym == "Symbol" => {
if let [ExprOrSpread { spread: None, .. }] = &mut args[..] {
if self.options.unsafe_symbols {
args.clear();
report_change!("Remove Symbol call parameter");
self.changed = true;
}
}
None
}
_ => unreachable!(),
};
if let Some(new_expr) = new_expr {
report_change!(
"Converting Boolean/Number/String/Symbol call to native constructor to \
literal"
);
self.changed = true;
*e = new_expr;
return;
}
}
_ => {}
};
match e {
Expr::New(NewExpr {
span,
ctxt,
callee,
args,
..
}) if callee.is_one_of_global_ref_to(
self.expr_ctx,
&[
"Object",
// https://262.ecma-international.org/12.0/#sec-array-constructor
"Array",
// https://262.ecma-international.org/12.0/#sec-function-constructor
"Function",
// https://262.ecma-international.org/12.0/#sec-error-constructor
"Error",
// https://262.ecma-international.org/12.0/#sec-aggregate-error-constructor
"AggregateError",
// https://262.ecma-international.org/12.0/#sec-nativeerror-object-structure
"EvalError",
"RangeError",
"ReferenceError",
"SyntaxError",
"TypeError",
"URIError",
],
) || (callee.is_global_ref_to(self.expr_ctx, "RegExp")
&& can_compress_new_regexp(args.as_deref())) =>
{
self.changed = true;
report_change!(
"new operator: Compressing `new Array/RegExp/..` => `Array()/RegExp()/..`"
);
*e = CallExpr {
span: *span,
ctxt: *ctxt,
callee: callee.take().as_callee(),
args: args.take().unwrap_or_default(),
..Default::default()
}
.into()
}
_ => {}
}
}
/// Removes last return statement. This should be callled only if the return
/// value of function is ignored.
///
/// Returns true if something is modified.
fn drop_return_value(&mut self, stmts: &mut Vec<Stmt>) -> bool {
for s in stmts.iter_mut() {
if let Stmt::Return(ReturnStmt {
arg: arg @ Some(..),
..
}) = s
{
self.ignore_return_value(
arg.as_deref_mut().unwrap(),
DropOpts {
drop_global_refs_if_unused: true,
drop_zero: true,
drop_str_lit: true,
..Default::default()
},
);
if let Some(Expr::Invalid(..)) = arg.as_deref() {
self.changed = true;
*arg = None;
}
}
}
if let Some(last) = stmts.last_mut() {
self.drop_return_value_of_stmt(last)
} else {
false
}
}
fn compress_array_join_as_tpl(
&mut self,
span: Span,
elems: &mut Vec<Option<ExprOrSpread>>,
sep: &str,
) -> Option<Expr> {
if !self.options.evaluate {
return None;
}
if elems.iter().flatten().any(|elem| match &*elem.expr {
Expr::Tpl(t) => t.quasis.iter().any(|q| q.cooked.is_none()),
Expr::Lit(Lit::Str(..)) => false,
_ => true,
}) {
return None;
}
self.changed = true;
report_change!("Compressing array.join() as template literal");
let mut new_tpl = Tpl {
span,
quasis: Vec::new(),
exprs: Vec::new(),
};
let mut cur_raw = String::new();
let mut cur_cooked = String::new();
let mut first = true;
for elem in elems.take().into_iter().flatten() {
if first {
first = false;
} else {
cur_raw.push_str(sep);
cur_cooked.push_str(sep);
}
match *elem.expr {
Expr::Tpl(mut tpl) => {
//
for idx in 0..(tpl.quasis.len() + tpl.exprs.len()) {
if idx % 2 == 0 {
// quasis
let e = tpl.quasis[idx / 2].take();
cur_cooked.push_str(&e.cooked.unwrap());
cur_raw.push_str(&e.raw);
} else {
new_tpl.quasis.push(TplElement {
span: DUMMY_SP,
tail: false,
cooked: Some((&*cur_cooked).into()),
raw: (&*cur_raw).into(),
});
cur_raw.clear();
cur_cooked.clear();
let e = tpl.exprs[idx / 2].take();
new_tpl.exprs.push(e);
}
}
}
Expr::Lit(Lit::Str(s)) => {
cur_cooked.push_str(&convert_str_value_to_tpl_cooked(&s.value));
cur_raw.push_str(&convert_str_value_to_tpl_raw(&s.value));
}
_ => {
unreachable!()
}
}
}
new_tpl.quasis.push(TplElement {
span: DUMMY_SP,
tail: false,
cooked: Some(cur_cooked.into()),
raw: cur_raw.into(),
});
Some(new_tpl.into())
}
/// Returns true if something is modified.
fn drop_return_value_of_stmt(&mut self, s: &mut Stmt) -> bool {
match s {
Stmt::Block(s) => self.drop_return_value(&mut s.stmts),
Stmt::Return(ret) => {
self.changed = true;
report_change!("Dropping `return` token");
let span = ret.span;
match ret.arg.take() {
Some(arg) => {
*s = ExprStmt { span, expr: arg }.into();
}
None => {
*s = EmptyStmt { span }.into();
}
}
true
}
Stmt::Labeled(s) => self.drop_return_value_of_stmt(&mut s.body),
Stmt::If(s) => {
let c = self.drop_return_value_of_stmt(&mut s.cons);
let a = s
.alt
.as_deref_mut()
.map(|s| self.drop_return_value_of_stmt(s))
.unwrap_or_default();
c || a
}
Stmt::Try(s) => {
let a = if s.finalizer.is_none() {
self.drop_return_value(&mut s.block.stmts)
} else {
false
};
let b = s
.finalizer
.as_mut()
.map(|s| self.drop_return_value(&mut s.stmts))
.unwrap_or_default();
a || b
}
_ => false,
}
}
fn make_ignored_expr(
&mut self,
span: Span,
exprs: impl Iterator<Item = Box<Expr>>,
) -> Option<Expr> {
let mut exprs = exprs
.filter_map(|mut e| {
self.ignore_return_value(
&mut e,
DropOpts {
drop_global_refs_if_unused: true,
drop_str_lit: true,
drop_zero: true,
},
);
if let Expr::Invalid(..) = &*e {
None
} else {
Some(e)
}
})
.collect::<Vec<_>>();
if exprs.is_empty() {
return None;
}
if exprs.len() == 1 {
let mut new = *exprs.remove(0);
new.set_span(span);
return Some(new);
}
Some(
SeqExpr {
span: DUMMY_SP,
exprs,
}
.into(),
)
}
/// Calls [`Self::ignore_return_value`] on the arguments of return
/// statemetns.
///
/// This function is recursive but does not go into nested scopes.
pub(super) fn ignore_return_value_of_return_stmt(&mut self, s: &mut Stmt, opts: DropOpts) {
match s {
Stmt::Return(s) => {
if let Some(arg) = &mut s.arg {
self.ignore_return_value(arg, opts);
if arg.is_invalid() {
report_change!(
"Dropped the argument of a return statement because the return value \
is ignored"
);
s.arg = None;
}
}
}
Stmt::Block(s) => {
for stmt in &mut s.stmts {
self.ignore_return_value_of_return_stmt(stmt, opts);
}
}
Stmt::If(s) => {
self.ignore_return_value_of_return_stmt(&mut s.cons, opts);
if let Some(alt) = &mut s.alt {
self.ignore_return_value_of_return_stmt(alt, opts);
}
}
Stmt::Switch(s) => {
for case in &mut s.cases {
for stmt in &mut case.cons {
self.ignore_return_value_of_return_stmt(stmt, opts);
}
}
}
_ => {}
}
}
pub(super) fn ignore_return_value(&mut self, e: &mut Expr, opts: DropOpts) {
if e.is_invalid() {
return;
}
debug_assert_valid(e);
self.optimize_expr_in_bool_ctx(e, true);
match e {
Expr::Seq(seq) => {
if seq.exprs.is_empty() {
e.take();
return;
}
if seq.exprs.len() == 1 {
*e = *seq.exprs.remove(0);
}
}
Expr::Call(CallExpr {
span, ctxt, args, ..
}) if ctxt.has_mark(self.marks.pure) => {
report_change!("ignore_return_value: Dropping a pure call");
self.changed = true;
let new =
self.make_ignored_expr(*span, args.take().into_iter().map(|arg| arg.expr));
*e = new.unwrap_or(Invalid { span: DUMMY_SP }.into());
return;
}
Expr::TaggedTpl(TaggedTpl {
span, ctxt, tpl, ..
}) if ctxt.has_mark(self.marks.pure) => {
report_change!("ignore_return_value: Dropping a pure call");
self.changed = true;
let new = self.make_ignored_expr(*span, tpl.exprs.take().into_iter());
*e = new.unwrap_or(Invalid { span: DUMMY_SP }.into());
return;
}
Expr::New(NewExpr {
span, ctxt, args, ..
}) if ctxt.has_mark(self.marks.pure) => {
report_change!("ignore_return_value: Dropping a pure call");
self.changed = true;
let new = self.make_ignored_expr(
*span,
args.take().into_iter().flatten().map(|arg| arg.expr),
);
*e = new.unwrap_or(Invalid { span: DUMMY_SP }.into());
return;
}
_ => {}
}
match e {
Expr::Call(CallExpr {
span,
callee: Callee::Expr(callee),
args,
..
}) => {
if callee.is_pure_callee(self.expr_ctx) {
self.changed = true;
report_change!("Dropping pure call as callee is pure");
*e = self
.make_ignored_expr(*span, args.take().into_iter().map(|arg| arg.expr))
.unwrap_or(Invalid { span: DUMMY_SP }.into());
return;
}
}
Expr::TaggedTpl(TaggedTpl {
span,
tag: callee,
tpl,
..
}) => {
if callee.is_pure_callee(self.expr_ctx) {
self.changed = true;
report_change!("Dropping pure tag tpl as callee is pure");
*e = self
.make_ignored_expr(*span, tpl.exprs.take().into_iter())
.unwrap_or(Invalid { span: DUMMY_SP }.into());
return;
}
}
_ => (),
}
if self.options.unused {
if let Expr::Lit(Lit::Num(n)) = e {
// Skip 0
if n.value != 0.0 && n.value.classify() == FpCategory::Normal {
self.changed = true;
*e = Invalid { span: DUMMY_SP }.into();
return;
}
}
}
if let Expr::Ident(i) = e {
// If it's not a top level, it's a reference to a declared variable.
if i.ctxt.outer() == self.marks.unresolved_mark {
if self.options.side_effects
|| (self.options.unused && opts.drop_global_refs_if_unused)
{
if is_global_var_with_pure_property_access(&i.sym) {
report_change!("Dropping a reference to a global variable");
*e = Invalid { span: DUMMY_SP }.into();
return;
}
}
} else {
report_change!("Dropping an identifier as it's declared");
*e = Invalid { span: DUMMY_SP }.into();
return;
}
}
if self.options.side_effects {
match e {
Expr::Unary(UnaryExpr {
op: op!("void") | op!(unary, "+") | op!(unary, "-") | op!("!") | op!("~"),
arg,
..
}) => {
self.ignore_return_value(
arg,
DropOpts {
drop_str_lit: true,
drop_global_refs_if_unused: true,
drop_zero: true,
..opts
},
);
if arg.is_invalid() {
report_change!("Dropping an unary expression");
*e = Invalid { span: DUMMY_SP }.into();
return;
}
}
Expr::Bin(
be @ BinExpr {
op: op!("||") | op!("&&"),
..
},
) => {
self.ignore_return_value(&mut be.right, opts);
if be.right.is_invalid() {
report_change!("Dropping the RHS of a binary expression ('&&' / '||')");
*e = *be.left.take();
return;
}
}
Expr::Tpl(tpl) => {
self.changed = true;
report_change!("Dropping a template literal");
for expr in tpl.exprs.iter_mut() {
self.ignore_return_value(&mut *expr, opts);
}
tpl.exprs.retain(|expr| !expr.is_invalid());
if tpl.exprs.is_empty() {
e.take();
} else {
if tpl.exprs.len() == 1 {
*e = *tpl.exprs.remove(0);
} else {
*e = SeqExpr {
span: tpl.span,
exprs: tpl.exprs.take(),
}
.into();
}
}
return;
}
Expr::Member(MemberExpr {
obj,
prop: MemberProp::Ident(prop),
..
}) => {
if obj.is_ident_ref_to("arguments") {
if &*prop.sym == "callee" {
return;
}
e.take();
return;
}
}
_ => {}
}
}
if self.options.unused || self.options.side_effects {
match e {
Expr::Lit(Lit::Num(n)) => {
if n.value == 0.0 && opts.drop_zero {
self.changed = true;
*e = Invalid { span: DUMMY_SP }.into();
return;
}
}
Expr::Ident(i) => {
if i.ctxt.outer() != self.marks.unresolved_mark {
report_change!("Dropping an identifier as it's declared");
self.changed = true;
*e = Invalid { span: DUMMY_SP }.into();
return;
}
}
Expr::Lit(Lit::Null(..) | Lit::BigInt(..) | Lit::Bool(..) | Lit::Regex(..)) => {
report_change!("Dropping literals");
self.changed = true;
*e = Invalid { span: DUMMY_SP }.into();
return;
}
Expr::Bin(
bin @ BinExpr {
op:
op!(bin, "+")
| op!(bin, "-")
| op!("*")
| op!("%")
| op!("**")
| op!("^")
| op!("&")
| op!("|")
| op!(">>")
| op!("<<")
| op!(">>>")
| op!("===")
| op!("!==")
| op!("==")
| op!("!=")
| op!("<")
| op!("<=")
| op!(">")
| op!(">="),
..
},
) => {
self.ignore_return_value(
&mut bin.left,
DropOpts {
drop_zero: true,
drop_global_refs_if_unused: true,
drop_str_lit: true,
..opts
},
);
self.ignore_return_value(
&mut bin.right,
DropOpts {
drop_zero: true,
drop_global_refs_if_unused: true,
drop_str_lit: true,
..opts
},
);
let span = bin.span;
if bin.left.is_invalid() && bin.right.is_invalid() {
*e = Invalid { span: DUMMY_SP }.into();
return;
} else if bin.right.is_invalid() {
*e = *bin.left.take();
return;
} else if bin.left.is_invalid() {
*e = *bin.right.take();
return;
}
if matches!(*bin.left, Expr::Await(..) | Expr::Update(..)) {
self.changed = true;
report_change!("ignore_return_value: Compressing binary as seq");
*e = SeqExpr {
span,
exprs: vec![bin.left.take(), bin.right.take()],
}
.into();
return;
}
}
Expr::Assign(assign @ AssignExpr { op: op!("="), .. }) => {
// Convert `a = a` to `a`.
if let Some(l) = assign.left.as_ident() {
if let Expr::Ident(r) = &*assign.right {
if l.to_id() == r.to_id() && l.ctxt != self.expr_ctx.unresolved_ctxt {
self.changed = true;
*e = *assign.right.take();
}
}
}
}
_ => {}
}
}
match e {
Expr::Lit(Lit::Str(s)) => {
if (self.options.directives && !matches!(&*s.value, "use strict" | "use asm"))
|| opts.drop_str_lit
|| (s.value.starts_with("@swc/helpers")
|| s.value.starts_with("@babel/helpers"))
{
self.changed = true;
*e = Invalid { span: DUMMY_SP }.into();
return;
}
}
Expr::Seq(seq) => {
self.drop_useless_ident_ref_in_seq(seq);
if let Some(last) = seq.exprs.last_mut() {
// Non-last elements are already processed.
self.ignore_return_value(last, opts);
}
let len = seq.exprs.len();
seq.exprs.retain(|e| !e.is_invalid());
if seq.exprs.len() != len {
self.changed = true;
}
if seq.exprs.len() == 1 {
*e = *seq.exprs.remove(0);
}
return;
}
Expr::Call(CallExpr {
callee: Callee::Expr(callee),
..
}) if callee.is_fn_expr() => match &mut **callee {
Expr::Fn(callee) => {
if callee.ident.is_none() {
if let Some(body) = &mut callee.function.body {
if self.options.side_effects {
self.drop_return_value(&mut body.stmts);
}
}
}
}
_ => {
unreachable!()
}
},
_ => {}
}
if self.options.side_effects {
if let Expr::Call(CallExpr {
callee: Callee::Expr(callee),
..
}) = e
{
match &mut **callee {
Expr::Fn(callee) => {
if let Some(body) = &mut callee.function.body {
if let Some(ident) = &callee.ident {
if IdentUsageFinder::find(&ident.to_id(), body) {
return;
}
}
for stmt in &mut body.stmts {
self.ignore_return_value_of_return_stmt(stmt, opts);
}
}
}
Expr::Arrow(callee) => match &mut *callee.body {
BlockStmtOrExpr::BlockStmt(body) => {
for stmt in &mut body.stmts {
self.ignore_return_value_of_return_stmt(stmt, opts);
}
}
BlockStmtOrExpr::Expr(body) => {
self.ignore_return_value(body, opts);
if body.is_invalid() {
*body = 0.into();
return;
}
}
},
_ => {}
}
}
}
if self.options.side_effects && self.options.pristine_globals {
match e {
Expr::New(NewExpr {
span, callee, args, ..
}) if callee.is_one_of_global_ref_to(
self.expr_ctx,
&[
"Map", "Set", "Array", "Object", "Boolean", "Number", "String",
],
) =>
{
report_change!("Dropping a pure new expression");
self.changed = true;
*e = self
.make_ignored_expr(
*span,
args.iter_mut().flatten().map(|arg| arg.expr.take()),
)
.unwrap_or(Invalid { span: DUMMY_SP }.into());
return;
}
Expr::Call(CallExpr {
span,
callee: Callee::Expr(callee),
args,
..
}) if callee.is_one_of_global_ref_to(
self.expr_ctx,
&["Array", "Object", "Boolean", "Number"],
) =>
{
report_change!("Dropping a pure call expression");
self.changed = true;
*e = self
.make_ignored_expr(*span, args.iter_mut().map(|arg| arg.expr.take()))
.unwrap_or(Invalid { span: DUMMY_SP }.into());
return;
}
Expr::Object(obj) => {
if obj.props.iter().all(|prop| !prop.is_spread()) {
let exprs = collect_exprs_from_object(obj);
*e = self
.make_ignored_expr(obj.span, exprs.into_iter())
.unwrap_or(Invalid { span: DUMMY_SP }.into());
report_change!("Ignored an object literal");
self.changed = true;
return;
}
}
Expr::Array(arr) => {
if arr.elems.iter().any(|e| match e {
Some(ExprOrSpread {
spread: Some(..), ..
}) => true,
_ => false,
}) {
*e = ArrayLit {
elems: arr
.elems
.take()
.into_iter()
.flatten()
.filter_map(|mut e| {
if e.spread.is_some() {
return Some(e);
}
self.ignore_return_value(
&mut e.expr,
DropOpts {
drop_global_refs_if_unused: true,
drop_zero: true,
drop_str_lit: true,
..opts
},
);
if e.expr.is_invalid() {
return None;
}
Some(ExprOrSpread {
spread: None,
expr: e.expr,
})
})
.map(Some)
.collect(),
..*arr
}
.into();
return;
}
let mut exprs = Vec::new();
//
for ExprOrSpread { mut expr, .. } in arr.elems.take().into_iter().flatten() {
self.ignore_return_value(
&mut expr,
DropOpts {
drop_str_lit: true,
drop_zero: true,
drop_global_refs_if_unused: true,
..opts
},
);
if !expr.is_invalid() {
exprs.push(expr);
}
}
*e = self
.make_ignored_expr(arr.span, exprs.into_iter())
.unwrap_or(Invalid { span: DUMMY_SP }.into());
report_change!("Ignored an array literal");
self.changed = true;
return;
}
// terser compiles
//
// [1,foo(),...bar()][{foo}]
//
// as
//
// foo(),basr(),foo;
Expr::Member(MemberExpr {
span,
obj,
prop: MemberProp::Computed(prop),
..
}) => match obj.as_mut() {
Expr::Object(object) => {
// Accessing getters and setters may cause side effect
// More precision is possible if comparing the lit prop names
if object.props.iter().all(|p| match p {
PropOrSpread::Spread(..) => false,
PropOrSpread::Prop(p) => match &**p {
Prop::Getter(..) | Prop::Setter(..) => false,
_ => true,
},
}) {
let mut exprs = collect_exprs_from_object(object);
exprs.push(prop.expr.take());
*e = self
.make_ignored_expr(*span, exprs.into_iter())
.unwrap_or(Invalid { span: DUMMY_SP }.into());
return;
}
}
Expr::Array(..) => {
self.ignore_return_value(obj, opts);
*e = self
.make_ignored_expr(
*span,
vec![obj.take(), prop.expr.take()].into_iter(),
)
.unwrap_or(Invalid { span: DUMMY_SP }.into());
return;
}
_ => {}
},
_ => {}
}
}
// Remove pure member expressions.
if self.options.pristine_globals {
if let Expr::Member(MemberExpr { obj, prop, .. }) = e {
if let Expr::Ident(obj) = &**obj {
if obj.ctxt.outer() == self.marks.unresolved_mark {
if is_pure_member_access(obj, prop) {
self.changed = true;
report_change!("Remving pure member access to global var");
*e = Invalid { span: DUMMY_SP }.into();
}
}
}
}
}
}
///
/// - `!(x == y)` => `x != y`
/// - `!(x === y)` => `x !== y`
pub(super) fn compress_negated_bin_eq(&self, e: &mut Expr) {
let unary = match e {
Expr::Unary(e @ UnaryExpr { op: op!("!"), .. }) => e,
_ => return,
};
match &mut *unary.arg {
Expr::Bin(BinExpr {
op: op @ op!("=="),
left,
right,
..
})
| Expr::Bin(BinExpr {
op: op @ op!("==="),
left,
right,
..
}) => {
*e = BinExpr {
span: unary.span,
op: if *op == op!("==") {
op!("!=")
} else {
op!("!==")
},
left: left.take(),
right: right.take(),
}
.into()
}
_ => {}
}
}
pub(super) fn optimize_nullish_coalescing(&mut self, e: &mut Expr) {
let (l, r) = match e {
Expr::Bin(BinExpr {
op: op!("??"),
left,
right,
..
}) => (&mut **left, &mut **right),
_ => return,
};
match l {
Expr::Lit(Lit::Null(..)) => {
report_change!("Removing null from lhs of ??");
self.changed = true;
*e = r.take();
}
Expr::Lit(Lit::Num(..))
| Expr::Lit(Lit::Str(..))
| Expr::Lit(Lit::BigInt(..))
| Expr::Lit(Lit::Bool(..))
| Expr::Lit(Lit::Regex(..)) => {
report_change!("Removing rhs of ?? as lhs cannot be null nor undefined");
self.changed = true;
*e = l.take();
}
_ => {}
}
}
///
/// - `a ? true : false` => `!!a`
pub(super) fn compress_useless_cond_expr(&mut self, expr: &mut Expr) {
let cond = match expr {
Expr::Cond(c) => c,
_ => return,
};
let lt = cond.cons.get_type(self.expr_ctx);
let rt = cond.alt.get_type(self.expr_ctx);
match (lt, rt) {
(Known(Type::Bool), Known(Type::Bool)) => {}
_ => return,
}
let lb = cond.cons.as_pure_bool(self.expr_ctx);
let rb = cond.alt.as_pure_bool(self.expr_ctx);
let lb = match lb {
Value::Known(v) => v,
Value::Unknown => return,
};
let rb = match rb {
Value::Known(v) => v,
Value::Unknown => return,
};
// `cond ? true : false` => !!cond
if lb && !rb {
self.negate(&mut cond.test, false, false);
self.negate(&mut cond.test, false, false);
*expr = *cond.test.take();
return;
}
// `cond ? false : true` => !cond
if !lb && rb {
self.negate(&mut cond.test, false, false);
*expr = *cond.test.take();
}
}
}
#[derive(Debug, Default, Clone, Copy)]
pub(super) struct DropOpts {
/// If true and `unused` option is enabled, references to global variables
/// will be dropped, even if `side_effects` is false.
pub drop_global_refs_if_unused: bool,
pub drop_zero: bool,
pub drop_str_lit: bool,
}
/// `obj` should have top level syntax context.
fn is_pure_member_access(obj: &Ident, prop: &MemberProp) -> bool {
macro_rules! check {
(
$obj:ident.
$prop:ident
) => {{
if &*obj.sym == stringify!($obj) {
if let MemberProp::Ident(prop) = prop {
if &*prop.sym == stringify!($prop) {
return true;
}
}
}
}};
}
macro_rules! pure {
(
$(
$(
$i:ident
).*
),*
) => {
$(
check!($($i).*);
)*
};
}
pure!(
Array.isArray,
ArrayBuffer.isView,
Boolean.toSource,
Date.parse,
Date.UTC,
Date.now,
Error.captureStackTrace,
Error.stackTraceLimit,
Function.bind,
Function.call,
Function.length,
console.log,
Error.name,
Math.random,
Number.isNaN,
Object.defineProperty,
String.fromCharCode
);
false
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/compress/pure/mod.rs | Rust | #![allow(clippy::needless_update)]
use swc_common::{pass::Repeated, util::take::Take, SyntaxContext, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_transforms_optimization::debug_assert_valid;
use swc_ecma_usage_analyzer::marks::Marks;
use swc_ecma_utils::{
parallel::{cpu_count, Parallel, ParallelExt},
ExprCtx,
};
use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith, VisitWith};
#[cfg(feature = "debug")]
use tracing::{debug, span, Level};
use self::{ctx::Ctx, misc::DropOpts};
use super::util::is_pure_undefined_or_null;
#[cfg(feature = "debug")]
use crate::debug::dump;
use crate::{debug::AssertValid, maybe_par, option::CompressOptions, util::ModuleItemExt};
mod arrows;
mod bools;
mod conds;
mod ctx;
mod dead_code;
mod drop_console;
mod evaluate;
mod if_return;
mod loops;
mod member_expr;
mod misc;
mod numbers;
mod properties;
mod sequences;
mod strings;
mod unsafes;
mod vars;
#[derive(Debug, Clone, Copy)]
pub(crate) struct PureOptimizerConfig {
/// pass > 1
pub enable_join_vars: bool,
pub force_str_for_tpl: bool,
#[cfg(feature = "debug")]
pub debug_infinite_loop: bool,
}
#[allow(clippy::needless_lifetimes)]
pub(crate) fn pure_optimizer<'a>(
options: &'a CompressOptions,
marks: Marks,
config: PureOptimizerConfig,
) -> impl 'a + VisitMut + Repeated {
Pure {
options,
config,
marks,
expr_ctx: ExprCtx {
unresolved_ctxt: SyntaxContext::empty().apply_mark(marks.unresolved_mark),
is_unresolved_ref_safe: false,
in_strict: options.module,
remaining_depth: 6,
},
ctx: Default::default(),
changed: Default::default(),
}
}
struct Pure<'a> {
options: &'a CompressOptions,
config: PureOptimizerConfig,
marks: Marks,
expr_ctx: ExprCtx,
ctx: Ctx,
changed: bool,
}
impl Parallel for Pure<'_> {
fn create(&self) -> Self {
Self { ..*self }
}
fn merge(&mut self, other: Self) {
if other.changed {
self.changed = true;
}
}
}
impl Repeated for Pure<'_> {
fn changed(&self) -> bool {
self.changed
}
fn reset(&mut self) {
self.ctx = Default::default();
self.changed = false;
}
}
impl Pure<'_> {
fn handle_stmt_likes<T>(&mut self, stmts: &mut Vec<T>)
where
T: ModuleItemExt + Take,
Vec<T>: VisitWith<self::vars::VarWithOutInitCounter>
+ VisitMutWith<self::vars::VarPrepender>
+ VisitMutWith<self::vars::VarMover>
+ VisitWith<AssertValid>,
{
self.remove_dead_branch(stmts);
#[cfg(debug_assertions)]
{
stmts.visit_with(&mut AssertValid);
}
self.drop_unreachable_stmts(stmts);
#[cfg(debug_assertions)]
{
stmts.visit_with(&mut AssertValid);
}
self.drop_useless_blocks(stmts);
#[cfg(debug_assertions)]
{
stmts.visit_with(&mut AssertValid);
}
self.collapse_vars_without_init(stmts, VarDeclKind::Let);
#[cfg(debug_assertions)]
{
stmts.visit_with(&mut AssertValid);
}
self.collapse_vars_without_init(stmts, VarDeclKind::Var);
#[cfg(debug_assertions)]
{
stmts.visit_with(&mut AssertValid);
}
if self.config.enable_join_vars {
self.join_vars(stmts);
#[cfg(debug_assertions)]
{
stmts.visit_with(&mut AssertValid);
}
}
stmts.retain(|s| !matches!(s.as_stmt(), Some(Stmt::Empty(..))));
}
fn optimize_fn_stmts(&mut self, stmts: &mut Vec<Stmt>) {
if !stmts.is_empty() {
if let Stmt::Expr(ExprStmt { expr, .. }) = &stmts[0] {
if let Expr::Lit(Lit::Str(v)) = &**expr {
if v.value == *"use asm" {
return;
}
}
}
}
self.remove_useless_return(stmts);
self.negate_if_terminate(stmts, true, false);
if let Some(last) = stmts.last_mut() {
self.drop_unused_stmt_at_end_of_fn(last);
}
}
/// Visit `nodes`, maybe in parallel.
fn visit_par<N>(&mut self, nodes: &mut Vec<N>)
where
N: for<'aa> VisitMutWith<Pure<'aa>> + Send + Sync,
{
self.maybe_par(cpu_count() * 2, nodes, |v, node| {
node.visit_mut_with(v);
});
}
}
impl VisitMut for Pure<'_> {
noop_visit_mut_type!();
fn visit_mut_assign_expr(&mut self, e: &mut AssignExpr) {
{
let ctx = Ctx {
is_lhs_of_assign: true,
..self.ctx
};
e.left.visit_mut_children_with(&mut *self.with_ctx(ctx));
}
e.right.visit_mut_with(self);
}
fn visit_mut_bin_expr(&mut self, e: &mut BinExpr) {
self.visit_mut_expr(&mut e.left);
self.visit_mut_expr(&mut e.right);
self.compress_cmp_with_long_op(e);
if e.op == op!(bin, "+") {
self.concat_tpl(&mut e.left, &mut e.right);
}
}
fn visit_mut_block_stmt_or_expr(&mut self, body: &mut BlockStmtOrExpr) {
body.visit_mut_children_with(self);
match body {
BlockStmtOrExpr::BlockStmt(b) => self.optimize_fn_stmts(&mut b.stmts),
BlockStmtOrExpr::Expr(_) => {}
}
self.optimize_arrow_body(body);
}
fn visit_mut_call_expr(&mut self, e: &mut CallExpr) {
{
let ctx = Ctx {
is_callee: true,
..self.ctx
};
e.callee.visit_mut_with(&mut *self.with_ctx(ctx));
}
e.args.visit_mut_with(self);
self.eval_spread_array(&mut e.args);
self.drop_arguments_of_symbol_call(e);
}
fn visit_mut_class_member(&mut self, m: &mut ClassMember) {
m.visit_mut_children_with(self);
if let ClassMember::StaticBlock(sb) = m {
if sb.body.stmts.is_empty() {
*m = ClassMember::Empty(EmptyStmt { span: DUMMY_SP });
}
}
}
fn visit_mut_class_members(&mut self, m: &mut Vec<ClassMember>) {
self.visit_par(m);
m.retain(|m| {
if let ClassMember::Empty(..) = m {
return false;
}
true
});
}
fn visit_mut_cond_expr(&mut self, e: &mut CondExpr) {
e.visit_mut_children_with(self);
self.optimize_expr_in_bool_ctx(&mut e.test, false);
self.negate_cond_expr(e);
}
fn visit_mut_expr(&mut self, e: &mut Expr) {
{
let ctx = Ctx {
in_first_expr: false,
..self.ctx
};
e.visit_mut_children_with(&mut *self.with_ctx(ctx));
}
match e {
Expr::Seq(seq) => {
if seq.exprs.len() == 1 {
*e = *seq.exprs.pop().unwrap();
}
}
Expr::Invalid(..) | Expr::Lit(..) => return,
_ => {}
}
if e.is_seq() {
debug_assert_valid(e);
}
if self.options.unused {
if let Expr::Unary(UnaryExpr {
span,
op: op!("void"),
arg,
}) = e
{
if !arg.is_lit() {
self.ignore_return_value(
arg,
DropOpts {
drop_global_refs_if_unused: true,
drop_zero: true,
drop_str_lit: true,
},
);
if arg.is_invalid() {
*e = *Expr::undefined(*span);
return;
}
}
}
}
self.eval_nested_tpl(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.eval_tpl_as_str(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.eval_str_addition(e);
self.remove_invalid(e);
self.drop_console(e);
self.remove_invalid(e);
if let Expr::Seq(seq) = e {
if seq.exprs.is_empty() {
*e = Invalid { span: DUMMY_SP }.into();
return;
}
if seq.exprs.len() == 1 {
self.changed = true;
*e = *seq.exprs.take().into_iter().next().unwrap();
}
}
self.compress_array_join(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.unsafe_optimize_fn_as_arrow(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.eval_opt_chain(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.eval_number_call(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.eval_arguments_member_access(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.eval_number_method_call(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.swap_bin_operands(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.optimize_bools(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.drop_logical_operands(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.optimize_negate_eq(e);
self.lift_minus(e);
self.optimize_to_number(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.convert_tpl_to_str(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.drop_useless_addition_of_str(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.compress_useless_deletes(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.remove_useless_logical_rhs(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.handle_negated_seq(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.concat_str(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.eval_array_method_call(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.eval_fn_method_call(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.eval_str_method_call(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.compress_conds_as_logical(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.compress_cond_with_logical_as_logical(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.compress_conds_as_arithmetic(e);
self.lift_seqs_of_bin(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.lift_seqs_of_cond_assign(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.optimize_nullish_coalescing(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.compress_negated_bin_eq(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.compress_useless_cond_expr(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.optimize_builtin_object(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.optimize_opt_chain(e);
if e.is_seq() {
debug_assert_valid(e);
}
self.eval_member_expr(e);
}
fn visit_mut_expr_or_spreads(&mut self, nodes: &mut Vec<ExprOrSpread>) {
self.visit_par(nodes);
}
fn visit_mut_expr_stmt(&mut self, s: &mut ExprStmt) {
s.visit_mut_children_with(self);
if s.expr.is_seq() {
debug_assert_valid(&s.expr);
}
self.ignore_return_value(
&mut s.expr,
DropOpts {
drop_zero: true,
drop_global_refs_if_unused: true,
drop_str_lit: false,
},
);
if s.expr.is_seq() {
debug_assert_valid(&s.expr);
}
}
fn visit_mut_exprs(&mut self, nodes: &mut Vec<Box<Expr>>) {
self.visit_par(nodes);
}
fn visit_mut_fn_decl(&mut self, n: &mut FnDecl) {
#[cfg(feature = "debug")]
let _tracing = tracing::span!(
Level::ERROR,
"visit_mut_fn_decl",
id = tracing::field::display(&n.ident)
)
.entered();
n.visit_mut_children_with(self);
}
fn visit_mut_for_in_stmt(&mut self, n: &mut ForInStmt) {
n.right.visit_mut_with(self);
n.left.visit_mut_with(self);
n.body.visit_mut_with(self);
if let Stmt::Block(body) = &mut *n.body {
self.negate_if_terminate(&mut body.stmts, false, true);
}
}
fn visit_mut_for_of_stmt(&mut self, n: &mut ForOfStmt) {
n.right.visit_mut_with(self);
n.left.visit_mut_with(self);
n.body.visit_mut_with(self);
if let Stmt::Block(body) = &mut *n.body {
self.negate_if_terminate(&mut body.stmts, false, true);
}
}
fn visit_mut_for_stmt(&mut self, s: &mut ForStmt) {
s.visit_mut_children_with(self);
self.optimize_for_if_break(s);
self.merge_for_if_break(s);
if let Some(test) = &mut s.test {
self.optimize_expr_in_bool_ctx(test, false);
}
if let Stmt::Block(body) = &mut *s.body {
self.negate_if_terminate(&mut body.stmts, false, true);
}
}
fn visit_mut_function(&mut self, f: &mut Function) {
{
let ctx = Ctx {
_in_try_block: false,
..self.ctx
};
f.visit_mut_children_with(&mut *self.with_ctx(ctx));
}
if let Some(body) = &mut f.body {
self.optimize_fn_stmts(&mut body.stmts)
}
}
fn visit_mut_if_stmt(&mut self, s: &mut IfStmt) {
s.visit_mut_children_with(self);
self.optimize_expr_in_bool_ctx(&mut s.test, false);
self.merge_else_if(s);
}
fn visit_mut_member_expr(&mut self, e: &mut MemberExpr) {
e.obj.visit_mut_with(self);
if let MemberProp::Computed(c) = &mut e.prop {
c.visit_mut_with(self);
// TODO: unify these two
if let Some(ident) = self.optimize_property_of_member_expr(Some(&e.obj), c) {
e.prop = MemberProp::Ident(ident);
return;
};
if let Some(ident) = self.handle_known_computed_member_expr(c) {
e.prop = MemberProp::Ident(ident)
};
}
}
fn visit_mut_module_items(&mut self, items: &mut Vec<ModuleItem>) {
self.visit_par(items);
self.handle_stmt_likes(items);
}
fn visit_mut_new_expr(&mut self, e: &mut NewExpr) {
{
let ctx = Ctx {
is_callee: true,
..self.ctx
};
e.callee.visit_mut_with(&mut *self.with_ctx(ctx));
}
e.args.visit_mut_with(self);
}
fn visit_mut_opt_call(&mut self, opt_call: &mut OptCall) {
{
let ctx = Ctx {
is_callee: true,
..self.ctx
};
opt_call.callee.visit_mut_with(&mut *self.with_ctx(ctx));
}
opt_call.args.visit_mut_with(self);
self.eval_spread_array(&mut opt_call.args);
}
fn visit_mut_opt_var_decl_or_expr(&mut self, n: &mut Option<VarDeclOrExpr>) {
n.visit_mut_children_with(self);
if self.options.side_effects {
if let Some(VarDeclOrExpr::Expr(e)) = n {
self.ignore_return_value(
e,
DropOpts {
drop_zero: true,
drop_global_refs_if_unused: true,
drop_str_lit: true,
..Default::default()
},
);
if e.is_invalid() {
*n = None;
}
}
}
}
fn visit_mut_opt_vec_expr_or_spreads(&mut self, nodes: &mut Vec<Option<ExprOrSpread>>) {
self.visit_par(nodes);
}
fn visit_mut_prop(&mut self, p: &mut Prop) {
p.visit_mut_children_with(self);
self.optimize_arrow_method_prop(p);
#[cfg(debug_assertions)]
{
p.visit_with(&mut AssertValid);
}
}
fn visit_mut_prop_name(&mut self, p: &mut PropName) {
p.visit_mut_children_with(self);
self.optimize_computed_prop_name_as_normal(p);
self.optimize_prop_name(p);
}
fn visit_mut_prop_or_spreads(&mut self, exprs: &mut Vec<PropOrSpread>) {
self.visit_par(exprs);
exprs.retain(|e| {
if let PropOrSpread::Spread(spread) = e {
if is_pure_undefined_or_null(self.expr_ctx, &spread.expr) {
return false;
}
}
true
})
}
fn visit_mut_return_stmt(&mut self, s: &mut ReturnStmt) {
s.visit_mut_children_with(self);
self.drop_undefined_from_return_arg(s);
}
fn visit_mut_seq_expr(&mut self, e: &mut SeqExpr) {
e.visit_mut_children_with(self);
let exprs = &e.exprs;
if maybe_par!(
exprs.iter().any(|e| e.is_seq()),
*crate::LIGHT_TASK_PARALLELS
) {
let mut exprs = Vec::new();
for e in e.exprs.take() {
if let Expr::Seq(seq) = *e {
exprs.extend(seq.exprs);
} else {
exprs.push(e);
}
}
e.exprs = exprs;
}
e.exprs.retain(|e| {
if e.is_invalid() {
self.changed = true;
report_change!("Removing invalid expr in seq");
return false;
}
true
});
if e.exprs.is_empty() {
return;
}
self.eval_trivial_values_in_expr(e);
self.merge_seq_call(e);
let can_drop_zero = matches!(&**e.exprs.last().unwrap(), Expr::Arrow(..));
let len = e.exprs.len();
for (idx, e) in e.exprs.iter_mut().enumerate() {
let is_last = idx == len - 1;
if !is_last {
self.ignore_return_value(
e,
DropOpts {
drop_zero: can_drop_zero,
drop_global_refs_if_unused: false,
drop_str_lit: true,
},
);
}
}
e.exprs.retain(|e| !e.is_invalid());
#[cfg(debug_assertions)]
{
e.exprs.visit_with(&mut AssertValid);
}
}
fn visit_mut_stmt(&mut self, s: &mut Stmt) {
#[cfg(feature = "debug")]
let _tracing = if self.config.debug_infinite_loop {
let text = dump(&*s, false);
if text.lines().count() < 10 {
Some(span!(Level::ERROR, "visit_mut_stmt", "start" = &*text).entered())
} else {
None
}
} else {
None
};
{
let ctx = Ctx {
is_update_arg: false,
is_callee: false,
in_delete: false,
in_first_expr: true,
..self.ctx
};
s.visit_mut_children_with(&mut *self.with_ctx(ctx));
}
match s {
Stmt::Expr(ExprStmt { expr, .. }) if expr.is_invalid() => {
*s = EmptyStmt { span: DUMMY_SP }.into();
return;
}
_ => {}
}
debug_assert_valid(s);
#[cfg(feature = "debug")]
if self.config.debug_infinite_loop {
let text = dump(&*s, false);
if text.lines().count() < 10 {
debug!("after: visit_mut_children_with: {}", text);
}
}
if self.options.drop_debugger {
if let Stmt::Debugger(..) = s {
self.changed = true;
*s = EmptyStmt { span: DUMMY_SP }.into();
report_change!("drop_debugger: Dropped a debugger statement");
return;
}
}
self.loop_to_for_stmt(s);
debug_assert_valid(s);
self.drop_instant_break(s);
debug_assert_valid(s);
self.optimize_labeled_stmt(s);
debug_assert_valid(s);
self.drop_useless_continue(s);
debug_assert_valid(s);
if let Stmt::Expr(es) = s {
if es.expr.is_invalid() {
*s = EmptyStmt { span: DUMMY_SP }.into();
return;
}
}
#[cfg(feature = "debug")]
if self.config.debug_infinite_loop {
let text = dump(&*s, false);
if text.lines().count() < 10 {
debug!("after: visit_mut_stmt: {}", text);
}
}
debug_assert_valid(s);
}
fn visit_mut_stmts(&mut self, items: &mut Vec<Stmt>) {
if !items.is_empty() {
if let Stmt::Expr(ExprStmt { expr, .. }) = &items[0] {
if let Expr::Lit(Lit::Str(v)) = &**expr {
if v.value == *"use asm" {
return;
}
}
}
}
self.visit_par(items);
self.handle_stmt_likes(items);
items.retain(|s| !matches!(s, Stmt::Empty(..)));
#[cfg(debug_assertions)]
{
items.visit_with(&mut AssertValid);
}
}
fn visit_mut_super_prop_expr(&mut self, e: &mut SuperPropExpr) {
if let SuperProp::Computed(c) = &mut e.prop {
c.visit_mut_with(self);
if let Some(ident) = self.optimize_property_of_member_expr(None, c) {
e.prop = SuperProp::Ident(ident);
return;
};
if let Some(ident) = self.handle_known_computed_member_expr(c) {
e.prop = SuperProp::Ident(ident)
};
}
}
fn visit_mut_tagged_tpl(&mut self, n: &mut TaggedTpl) {
n.tag.visit_mut_with(self);
n.tpl.exprs.visit_mut_with(self);
}
fn visit_mut_tpl(&mut self, n: &mut Tpl) {
n.visit_mut_children_with(self);
debug_assert_eq!(n.exprs.len() + 1, n.quasis.len());
self.compress_tpl(n);
debug_assert_eq!(
n.exprs.len() + 1,
n.quasis.len(),
"tagged template literal compressor created an invalid template literal"
);
}
fn visit_mut_try_stmt(&mut self, n: &mut TryStmt) {
let ctx = Ctx {
_in_try_block: true,
..self.ctx
};
n.block.visit_mut_with(&mut *self.with_ctx(ctx));
n.handler.visit_mut_with(self);
n.finalizer.visit_mut_with(self);
}
fn visit_mut_unary_expr(&mut self, e: &mut UnaryExpr) {
{
let ctx = Ctx {
in_delete: e.op == op!("delete"),
..self.ctx
};
e.visit_mut_children_with(&mut *self.with_ctx(ctx));
}
match e.op {
op!("!") => {
self.optimize_expr_in_bool_ctx(&mut e.arg, false);
}
op!(unary, "+") | op!(unary, "-") => {
self.optimize_expr_in_num_ctx(&mut e.arg);
}
_ => {}
}
}
fn visit_mut_update_expr(&mut self, e: &mut UpdateExpr) {
let ctx = Ctx {
is_update_arg: true,
..self.ctx
};
e.visit_mut_children_with(&mut *self.with_ctx(ctx));
}
fn visit_mut_var_decl(&mut self, v: &mut VarDecl) {
v.visit_mut_children_with(self);
if v.kind == VarDeclKind::Var {
self.remove_duplicate_vars(&mut v.decls);
}
}
fn visit_mut_var_declarators(&mut self, nodes: &mut Vec<VarDeclarator>) {
self.visit_par(nodes);
}
fn visit_mut_while_stmt(&mut self, s: &mut WhileStmt) {
s.visit_mut_children_with(self);
self.optimize_expr_in_bool_ctx(&mut s.test, false);
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/compress/pure/numbers.rs | Rust | use swc_common::{util::take::Take, EqIgnoreSpan, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_utils::num_from_str;
use super::Pure;
impl Pure<'_> {
pub(super) fn optimize_expr_in_num_ctx(&mut self, e: &mut Expr) {
if let Expr::Lit(Lit::Str(Str { span, value, .. })) = e {
let value = if value.is_empty() {
0f64
} else {
match num_from_str(value).into_result() {
Ok(f) if f.is_finite() => f,
_ => return,
}
};
self.changed = true;
report_change!("numbers: Converting a string literal to {:?}", value);
*e = Lit::Num(Number {
span: *span,
value,
raw: None,
})
.into();
}
}
///
/// - `1 / -0` => `- 1 / 0`
pub(super) fn lift_minus(&mut self, e: &mut Expr) {
if !self.options.evaluate {
return;
}
if let Expr::Bin(arg) = e {
if arg.op != op!("*") && arg.op != op!("/") {
return;
}
match &mut *arg.right {
Expr::Unary(UnaryExpr {
op: op!(unary, "-"),
arg: right_arg,
..
}) => {
self.changed = true;
report_change!("numbers: Lifting `-`");
*e = UnaryExpr {
span: arg.span,
op: op!(unary, "-"),
arg: BinExpr {
span: arg.span,
op: arg.op,
left: arg.left.take(),
right: right_arg.take(),
}
.into(),
}
.into();
}
Expr::Lit(Lit::Num(Number { span, value, .. })) => {
if value.is_sign_negative() {
self.changed = true;
report_change!("numbers: Lifting `-` in a literal");
*e = UnaryExpr {
span: arg.span,
op: op!(unary, "-"),
arg: BinExpr {
span: arg.span,
op: arg.op,
left: arg.left.take(),
right: Box::new(Expr::Lit(Lit::Num(Number {
span: *span,
value: -*value,
raw: None,
}))),
}
.into(),
}
.into();
}
}
_ => {}
}
}
}
pub(super) fn optimize_to_number(&mut self, e: &mut Expr) {
match e {
Expr::Bin(bin) => {
if bin.op == op!("*")
&& matches!(&*bin.left, Expr::Lit(Lit::Num(Number { value: 1.0, .. })))
{
report_change!("numbers: Turn '1 *' into '+'");
self.changed = true;
let value = bin.right.take();
let span = bin.span;
*e = Expr::Unary(UnaryExpr {
span,
op: op!(unary, "+"),
arg: value,
})
}
}
Expr::Assign(a @ AssignExpr { op: op!("="), .. }) => {
if let (
AssignTarget::Simple(SimpleAssignTarget::Ident(l_id)),
Expr::Unary(UnaryExpr {
op: op!(unary, "+"),
arg,
..
}),
) = (&a.left, &*a.right)
{
if let Expr::Ident(r_id) = &**arg {
if l_id.id.eq_ignore_span(r_id) {
report_change!("numbers: Turn a = +a into a *= 1");
self.changed = true;
a.op = op!("*=");
a.right = Box::new(Expr::Lit(Lit::Num(Number {
span: DUMMY_SP,
value: 1.0,
raw: None,
})))
}
}
}
}
_ => (),
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/compress/pure/properties.rs | Rust | use swc_atoms::atom;
use swc_ecma_ast::*;
use super::Pure;
use crate::compress::util::is_valid_identifier;
impl Pure<'_> {
pub(super) fn optimize_property_of_member_expr(
&mut self,
obj: Option<&Expr>,
c: &mut ComputedPropName,
) -> Option<IdentName> {
if !self.options.props {
return None;
}
if let Some(Expr::Array(..) | Expr::Await(..) | Expr::Yield(..) | Expr::Lit(..)) = obj {
return None;
}
match &*c.expr {
Expr::Lit(Lit::Str(s))
if s.value.is_reserved()
|| s.value.is_reserved_in_es3()
|| is_valid_identifier(&s.value, true) =>
{
self.changed = true;
report_change!(
"properties: Computed member => member expr with identifier as a prop"
);
Some(IdentName {
span: s.span,
sym: s.value.clone(),
})
}
_ => None,
}
}
/// If a key of is `'str'` (like `{ 'str': 1 }`) change it to [Ident] like
/// (`{ str: 1, }`)
pub(super) fn optimize_computed_prop_name_as_normal(&mut self, p: &mut PropName) {
if !self.options.computed_props {
return;
}
if let PropName::Computed(c) = p {
match &mut *c.expr {
Expr::Lit(Lit::Str(s)) => {
if s.value == *"constructor" || s.value == *"__proto__" {
return;
}
if s.value.is_reserved()
|| s.value.is_reserved_in_es3()
|| is_valid_identifier(&s.value, false)
{
*p = PropName::Ident(IdentName::new(s.value.clone(), s.span));
} else {
*p = PropName::Str(s.clone());
}
}
Expr::Lit(Lit::Num(n)) => {
if n.value.is_sign_positive() {
*p = PropName::Num(n.clone());
}
}
_ => {}
}
}
}
pub(super) fn optimize_prop_name(&mut self, name: &mut PropName) {
if let PropName::Str(s) = name {
if s.value.is_reserved()
|| s.value.is_reserved_in_es3()
|| is_valid_identifier(&s.value, false)
{
self.changed = true;
report_change!("misc: Optimizing string property name");
*name = PropName::Ident(IdentName {
span: s.span,
sym: s.value.clone(),
});
return;
}
if (!s.value.starts_with('0') && !s.value.starts_with('+')) || s.value.len() <= 1 {
if let Ok(v) = s.value.parse::<u32>() {
self.changed = true;
report_change!("misc: Optimizing numeric property name");
*name = PropName::Num(Number {
span: s.span,
value: v as _,
raw: None,
});
}
}
}
}
pub(super) fn handle_known_computed_member_expr(
&mut self,
c: &mut ComputedPropName,
) -> Option<IdentName> {
if !self.options.props || !self.options.evaluate {
return None;
}
match &*c.expr {
Expr::Lit(Lit::Str(s)) => {
if s.value == atom!("")
|| s.value.starts_with(|c: char| c.is_ascii_digit())
|| s.value
.contains(|c: char| !matches!(c, '0'..='9' | 'a'..='z' | 'A'..='Z' | '$'))
{
return None;
}
self.changed = true;
Some(IdentName::new(s.value.clone(), s.span))
}
_ => None,
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/compress/pure/sequences.rs | Rust | use swc_common::{util::take::Take, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_utils::ExprFactory;
use super::Pure;
impl Pure<'_> {
pub(super) fn drop_useless_ident_ref_in_seq(&mut self, seq: &mut SeqExpr) {
if !self.options.collapse_vars {
return;
}
if seq.exprs.len() < 2 {
return;
}
if let (Expr::Assign(assign @ AssignExpr { op: op!("="), .. }), Expr::Ident(ident)) = (
&*seq.exprs[seq.exprs.len() - 2],
&*seq.exprs[seq.exprs.len() - 1],
) {
// Check if lhs is same as `ident`.
if let AssignTarget::Simple(SimpleAssignTarget::Ident(left)) = &assign.left {
if left.id.sym == ident.sym && left.id.ctxt == ident.ctxt {
report_change!(
"drop_useless_ident_ref_in_seq: Dropping `{}` as it's useless",
left.id
);
self.changed = true;
seq.exprs.pop();
}
}
}
}
///
/// - `(a, b, c) && d` => `a, b, c && d`
pub(super) fn lift_seqs_of_bin(&mut self, e: &mut Expr) {
let bin = match e {
Expr::Bin(b) => b,
_ => return,
};
if let Expr::Seq(left) = &mut *bin.left {
if left.exprs.is_empty() {
return;
}
self.changed = true;
report_change!("sequences: Lifting sequence in a binary expression");
let left_last = left.exprs.pop().unwrap();
let mut exprs = left.exprs.take();
exprs.push(
BinExpr {
span: left.span,
op: bin.op,
left: left_last,
right: bin.right.take(),
}
.into(),
);
*e = SeqExpr {
span: bin.span,
exprs,
}
.into()
}
}
///
/// - `x = (foo(), bar(), baz()) ? 10 : 20` => `foo(), bar(), x = baz() ? 10
/// : 20;`
pub(super) fn lift_seqs_of_cond_assign(&mut self, e: &mut Expr) {
if !self.options.sequences() {
return;
}
let assign = match e {
Expr::Assign(v @ AssignExpr { op: op!("="), .. }) => v,
_ => return,
};
let cond = match &mut *assign.right {
Expr::Cond(v) => v,
_ => return,
};
if let Expr::Seq(test) = &mut *cond.test {
//
if test.exprs.len() >= 2 {
let mut new_seq = Vec::new();
new_seq.extend(test.exprs.drain(..test.exprs.len() - 1));
self.changed = true;
report_change!("sequences: Lifting sequences in a assignment with cond expr");
let new_cond = CondExpr {
span: cond.span,
test: test.exprs.pop().unwrap(),
cons: cond.cons.take(),
alt: cond.alt.take(),
};
new_seq.push(
AssignExpr {
span: assign.span,
op: assign.op,
left: assign.left.take(),
right: Box::new(new_cond.into()),
}
.into(),
);
*e = SeqExpr {
span: assign.span,
exprs: new_seq,
}
.into();
}
}
}
/// `(a = foo, a.apply())` => `(a = foo).apply()`
///
/// This is useful for outputs of swc/babel
pub(super) fn merge_seq_call(&mut self, e: &mut SeqExpr) {
if !self.options.sequences() {
return;
}
for idx in 0..e.exprs.len() {
let (e1, e2) = e.exprs.split_at_mut(idx);
let a = match e1.last_mut() {
Some(v) => &mut **v,
None => continue,
};
let b = match e2.first_mut() {
Some(v) => &mut **v,
None => continue,
};
if let (
Expr::Assign(a_assign @ AssignExpr { op: op!("="), .. }),
Expr::Call(CallExpr {
callee: Callee::Expr(b_callee),
args,
..
}),
) = (&mut *a, &mut *b)
{
let var_name = a_assign.left.as_ident();
let var_name = match var_name {
Some(v) => v,
None => continue,
};
match &mut **b_callee {
Expr::Member(MemberExpr {
obj: b_callee_obj,
prop,
..
}) if prop.is_ident_with("apply") || prop.is_ident_with("call") => {
//
if let Expr::Ident(b_callee_obj) = &**b_callee_obj {
if b_callee_obj.to_id() != var_name.to_id() {
continue;
}
} else {
continue;
}
let span = a_assign.span;
let obj = Box::new(a.take());
let new = CallExpr {
span,
callee: MemberExpr {
span: DUMMY_SP,
obj,
prop: prop.take(),
}
.as_callee(),
args: args.take(),
..Default::default()
}
.into();
b.take();
self.changed = true;
report_change!(
"sequences: Reducing `(a = foo, a.call())` to `((a = foo).call())`"
);
*a = new;
}
_ => (),
};
}
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/compress/pure/strings.rs | Rust | use std::{borrow::Cow, mem::take};
use swc_atoms::Atom;
use swc_common::{util::take::Take, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_utils::{ExprExt, Type, Value};
use Value::Known;
use super::Pure;
impl Pure<'_> {
/// This only handles `'foo' + ('bar' + baz) because others are handled by
/// expression simplifier.
pub(super) fn eval_str_addition(&mut self, e: &mut Expr) {
let (span, l_l, r_l, r_r) = match e {
Expr::Bin(
e @ BinExpr {
op: op!(bin, "+"), ..
},
) => match &mut *e.right {
Expr::Bin(
r @ BinExpr {
op: op!(bin, "+"), ..
},
) => (e.span, &mut *e.left, &mut *r.left, &mut r.right),
_ => return,
},
_ => return,
};
match l_l.get_type(self.expr_ctx) {
Known(Type::Str) => {}
_ => return,
}
match r_l.get_type(self.expr_ctx) {
Known(Type::Str) => {}
_ => return,
}
let lls = l_l.as_pure_string(self.expr_ctx);
let rls = r_l.as_pure_string(self.expr_ctx);
if let (Known(lls), Known(rls)) = (lls, rls) {
self.changed = true;
report_change!("evaluate: 'foo' + ('bar' + baz) => 'foobar' + baz");
let s = lls.into_owned() + &*rls;
*e = BinExpr {
span,
op: op!(bin, "+"),
left: s.into(),
right: r_r.take(),
}
.into();
}
}
pub(super) fn eval_tpl_as_str(&mut self, e: &mut Expr) {
if !self.options.evaluate {
return;
}
fn need_unsafe(e: &Expr) -> bool {
match e {
Expr::Lit(..) => false,
Expr::Bin(e) => need_unsafe(&e.left) || need_unsafe(&e.right),
_ => true,
}
}
let tpl = match e {
Expr::Tpl(e) => e,
_ => return,
};
if tpl.quasis.len() == 2
&& (tpl.quasis[0].cooked.is_some() || !tpl.quasis[0].raw.contains('\\'))
&& tpl.quasis[1].raw.is_empty()
{
if !self.options.unsafe_passes && need_unsafe(&tpl.exprs[0]) {
return;
}
self.changed = true;
report_change!("evaluating a template to a string");
*e = BinExpr {
span: tpl.span,
op: op!(bin, "+"),
left: tpl.quasis[0]
.cooked
.clone()
.unwrap_or_else(|| tpl.quasis[0].raw.clone())
.into(),
right: tpl.exprs[0].take(),
}
.into();
}
}
pub(super) fn eval_nested_tpl(&mut self, e: &mut Expr) {
let tpl = match e {
Expr::Tpl(e) => e,
_ => return,
};
if !tpl.exprs.iter().any(|e| match &**e {
Expr::Tpl(t) => t
.quasis
.iter()
.all(|q| q.cooked.is_some() && !q.raw.contains('\\')),
_ => false,
}) {
return;
}
self.changed = true;
report_change!("evaluating nested template literals");
let mut new_tpl = Tpl {
span: tpl.span,
quasis: Default::default(),
exprs: Default::default(),
};
let mut cur_cooked_str = String::new();
let mut cur_raw_str = String::new();
for idx in 0..(tpl.quasis.len() + tpl.exprs.len()) {
if idx % 2 == 0 {
let q = tpl.quasis[idx / 2].take();
cur_cooked_str.push_str(&Str::from_tpl_raw(&q.raw));
cur_raw_str.push_str(&q.raw);
} else {
let mut e = tpl.exprs[idx / 2].take();
self.eval_nested_tpl(&mut e);
match *e {
Expr::Tpl(mut e) => {
// We loop again
//
// I think we can merge this code...
for idx in 0..(e.quasis.len() + e.exprs.len()) {
if idx % 2 == 0 {
let q = e.quasis[idx / 2].take();
cur_cooked_str.push_str(Str::from_tpl_raw(&q.raw).as_ref());
cur_raw_str.push_str(&q.raw);
} else {
let cooked = Atom::from(&*cur_cooked_str);
let raw = Atom::from(&*cur_raw_str);
cur_cooked_str.clear();
cur_raw_str.clear();
new_tpl.quasis.push(TplElement {
span: DUMMY_SP,
tail: false,
cooked: Some(cooked),
raw,
});
let e = e.exprs[idx / 2].take();
new_tpl.exprs.push(e);
}
}
}
_ => {
let cooked = Atom::from(&*cur_cooked_str);
let raw = Atom::from(&*cur_raw_str);
cur_cooked_str.clear();
cur_raw_str.clear();
new_tpl.quasis.push(TplElement {
span: DUMMY_SP,
tail: false,
cooked: Some(cooked),
raw,
});
new_tpl.exprs.push(e);
}
}
}
}
let cooked = Atom::from(&*cur_cooked_str);
let raw = Atom::from(&*cur_raw_str);
new_tpl.quasis.push(TplElement {
span: DUMMY_SP,
tail: false,
cooked: Some(cooked),
raw,
});
*e = new_tpl.into();
}
/// Converts template literals to string if `exprs` of [Tpl] is empty.
pub(super) fn convert_tpl_to_str(&mut self, e: &mut Expr) {
match e {
Expr::Tpl(t) if t.quasis.len() == 1 && t.exprs.is_empty() => {
if let Some(value) = &t.quasis[0].cooked {
if value.chars().all(|c| match c {
'\\' => false,
'\u{0020}'..='\u{007e}' => true,
'\n' | '\r' => self.config.force_str_for_tpl,
_ => false,
}) {
report_change!("converting a template literal to a string literal");
*e = Lit::Str(Str {
span: t.span,
raw: None,
value: value.clone(),
})
.into();
return;
}
}
let c = &t.quasis[0].raw;
if c.chars().all(|c| match c {
'\u{0020}'..='\u{007e}' => true,
'\n' | '\r' => self.config.force_str_for_tpl,
_ => false,
}) && (self.config.force_str_for_tpl
|| c.contains("\\`")
|| (!c.contains("\\n") && !c.contains("\\r")))
&& !c.contains("\\0")
&& !c.contains("\\x")
&& !c.contains("\\u")
{
let value = Str::from_tpl_raw(c);
report_change!("converting a template literal to a string literal");
*e = Lit::Str(Str {
span: t.span,
raw: None,
value,
})
.into();
}
}
_ => {}
}
}
/// This compresses a template literal by inlining string literals in
/// expresions into quasis.
///
/// Note that this pass only cares about string literals and conversion to a
/// string literal should be done before calling this pass.
pub(super) fn compress_tpl(&mut self, tpl: &mut Tpl) {
debug_assert_eq!(tpl.exprs.len() + 1, tpl.quasis.len());
let has_str_lit = tpl
.exprs
.iter()
.any(|expr| matches!(&**expr, Expr::Lit(Lit::Str(..))));
if !has_str_lit {
return;
}
trace_op!("compress_tpl");
let mut quasis = Vec::new();
let mut exprs = Vec::new();
let mut cur_raw = String::new();
let mut cur_cooked = Some(String::new());
for i in 0..(tpl.exprs.len() + tpl.quasis.len()) {
if i % 2 == 0 {
let i = i / 2;
let q = tpl.quasis[i].clone();
if q.cooked.is_some() {
if let Some(cur_cooked) = &mut cur_cooked {
cur_cooked.push_str("");
}
} else {
// If cooked is None, it means that the template literal contains invalid escape
// sequences.
cur_cooked = None;
}
} else {
let i = i / 2;
let e = &tpl.exprs[i];
match &**e {
Expr::Lit(Lit::Str(s)) => {
if cur_cooked.is_none() && s.raw.is_none() {
return;
}
if let Some(cur_cooked) = &mut cur_cooked {
cur_cooked.push_str("");
}
}
_ => {
cur_cooked = Some(String::new());
}
}
}
}
cur_cooked = Some(Default::default());
for i in 0..(tpl.exprs.len() + tpl.quasis.len()) {
if i % 2 == 0 {
let i = i / 2;
let q = tpl.quasis[i].take();
cur_raw.push_str(&q.raw);
if let Some(cooked) = q.cooked {
if let Some(cur_cooked) = &mut cur_cooked {
cur_cooked.push_str(&cooked);
}
} else {
// If cooked is None, it means that the template literal contains invalid escape
// sequences.
cur_cooked = None;
}
} else {
let i = i / 2;
let e = tpl.exprs[i].take();
match *e {
Expr::Lit(Lit::Str(s)) => {
if let Some(cur_cooked) = &mut cur_cooked {
cur_cooked.push_str(&convert_str_value_to_tpl_cooked(&s.value));
}
if let Some(raw) = &s.raw {
if raw.len() >= 2 {
// Exclude quotes
cur_raw
.push_str(&convert_str_raw_to_tpl_raw(&raw[1..raw.len() - 1]));
}
} else {
cur_raw.push_str(&convert_str_value_to_tpl_raw(&s.value));
}
}
_ => {
quasis.push(TplElement {
span: DUMMY_SP,
tail: true,
cooked: cur_cooked.take().map(From::from),
raw: take(&mut cur_raw).into(),
});
cur_cooked = Some(String::new());
exprs.push(e);
}
}
}
}
report_change!("compressing template literals");
quasis.push(TplElement {
span: DUMMY_SP,
tail: true,
cooked: cur_cooked.map(From::from),
raw: cur_raw.into(),
});
debug_assert_eq!(exprs.len() + 1, quasis.len());
tpl.quasis = quasis;
tpl.exprs = exprs;
}
/// Called for binary operations with `+`.
pub(super) fn concat_tpl(&mut self, l: &mut Expr, r: &mut Expr) {
match (&mut *l, &mut *r) {
(Expr::Tpl(l), Expr::Lit(Lit::Str(rs))) => {
if let Some(raw) = &rs.raw {
if raw.len() <= 2 {
return;
}
}
// Append
if let Some(l_last) = l.quasis.last_mut() {
self.changed = true;
report_change!(
"template: Concatted a string (`{}`) on rhs of `+` to a template literal",
rs.value
);
if let Some(cooked) = &mut l_last.cooked {
*cooked =
format!("{}{}", cooked, convert_str_value_to_tpl_cooked(&rs.value))
.into();
}
l_last.raw = format!(
"{}{}",
l_last.raw,
rs.raw
.clone()
.map(|s| convert_str_raw_to_tpl_raw(&s[1..s.len() - 1]))
.unwrap_or_else(|| convert_str_value_to_tpl_raw(&rs.value).into())
)
.into();
r.take();
}
}
(Expr::Lit(Lit::Str(ls)), Expr::Tpl(r)) => {
if let Some(raw) = &ls.raw {
if raw.len() <= 2 {
return;
}
}
// Append
if let Some(r_first) = r.quasis.first_mut() {
self.changed = true;
report_change!(
"template: Prepended a string (`{}`) on lhs of `+` to a template literal",
ls.value
);
if let Some(cooked) = &mut r_first.cooked {
*cooked =
format!("{}{}", convert_str_value_to_tpl_cooked(&ls.value), cooked)
.into()
}
let new: Atom = format!(
"{}{}",
ls.raw
.clone()
.map(|s| convert_str_raw_to_tpl_raw(&s[1..s.len() - 1]))
.unwrap_or_else(|| convert_str_value_to_tpl_raw(&ls.value).into()),
r_first.raw
)
.into();
r_first.raw = new;
l.take();
}
}
(Expr::Tpl(l), Expr::Tpl(rt)) => {
// We prepend the last quasis of l to the first quasis of r.
// After doing so, we can append all data of r to l.
{
let l_last = l.quasis.pop().unwrap();
let r_first = rt.quasis.first_mut().unwrap();
let new: Atom = format!("{}{}", l_last.raw, r_first.raw).into();
r_first.raw = new;
}
l.quasis.extend(rt.quasis.take());
l.exprs.extend(rt.exprs.take());
// Remove r
r.take();
debug_assert!(l.quasis.len() == l.exprs.len() + 1, "{:?} is invalid", l);
self.changed = true;
report_change!("strings: Merged two template literals");
}
_ => {}
}
}
///
/// - `a + 'foo' + 'bar'` => `a + 'foobar'`
pub(super) fn concat_str(&mut self, e: &mut Expr) {
if let Expr::Bin(
bin @ BinExpr {
op: op!(bin, "+"), ..
},
) = e
{
if let Expr::Bin(
left @ BinExpr {
op: op!(bin, "+"), ..
},
) = &mut *bin.left
{
let type_of_second = left.right.get_type(self.expr_ctx);
let type_of_third = bin.right.get_type(self.expr_ctx);
if let Value::Known(Type::Str) = type_of_second {
if let Value::Known(Type::Str) = type_of_third {
if let Value::Known(second_str) = left.right.as_pure_string(self.expr_ctx) {
if let Value::Known(third_str) = bin.right.as_pure_string(self.expr_ctx)
{
let new_str = format!("{}{}", second_str, third_str);
let left_span = left.span;
self.changed = true;
report_change!(
"strings: Concatting `{} + {}` to `{}`",
second_str,
third_str,
new_str
);
*e = BinExpr {
span: bin.span,
op: op!(bin, "+"),
left: left.left.take(),
right: Lit::Str(Str {
span: left_span,
raw: None,
value: new_str.into(),
})
.into(),
}
.into();
}
}
}
}
}
}
}
pub(super) fn drop_useless_addition_of_str(&mut self, e: &mut Expr) {
if let Expr::Bin(BinExpr {
op: op!(bin, "+"),
left,
right,
..
}) = e
{
let lt = left.get_type(self.expr_ctx);
let rt = right.get_type(self.expr_ctx);
if let Value::Known(Type::Str) = lt {
if let Value::Known(Type::Str) = rt {
match &**left {
Expr::Lit(Lit::Str(Str { value, .. })) if value.is_empty() => {
self.changed = true;
report_change!(
"string: Dropping empty string literal (in lhs) because it does \
not changes type"
);
*e = *right.take();
return;
}
_ => (),
}
match &**right {
Expr::Lit(Lit::Str(Str { value, .. })) if value.is_empty() => {
self.changed = true;
report_change!(
"string: Dropping empty string literal (in rhs) because it does \
not changes type"
);
*e = *left.take();
}
_ => (),
}
}
}
}
}
}
pub(super) fn convert_str_value_to_tpl_cooked(value: &Atom) -> Cow<str> {
value
.replace("\\\\", "\\")
.replace("\\`", "`")
.replace("\\$", "$")
.into()
}
pub(super) fn convert_str_value_to_tpl_raw(value: &Atom) -> Cow<str> {
value
.replace('\\', "\\\\")
.replace('`', "\\`")
.replace('$', "\\$")
.replace('\n', "\\n")
.replace('\r', "\\r")
.into()
}
pub(super) fn convert_str_raw_to_tpl_raw(value: &str) -> Atom {
value.replace('`', "\\`").replace('$', "\\$").into()
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/compress/pure/unsafes.rs | Rust | use swc_ecma_ast::*;
use swc_ecma_utils::ExprExt;
use super::Pure;
impl Pure<'_> {
/// Drop arguments of `Symbol()` call.
pub(super) fn drop_arguments_of_symbol_call(&mut self, e: &mut CallExpr) {
if !self.options.unsafe_symbols {
return;
}
match &e.callee {
Callee::Super(_) | Callee::Import(_) => return,
Callee::Expr(callee) => match &**callee {
Expr::Ident(Ident { sym, .. }) if &**sym == "Symbol" => {}
_ => return,
},
}
e.args
.retain(|arg| arg.expr.may_have_side_effects(self.expr_ctx));
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/compress/pure/vars.rs | Rust | use rustc_hash::FxHashSet;
use swc_common::{util::take::Take, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_utils::{prepend_stmt, StmtLike};
use swc_ecma_visit::{
noop_visit_mut_type, noop_visit_type, Visit, VisitMut, VisitMutWith, VisitWith,
};
use super::Pure;
use crate::{
compress::util::{drop_invalid_stmts, is_directive},
util::ModuleItemExt,
};
impl Pure<'_> {
/// Join variables.
///
/// This method may move variables to head of for statements like
///
/// `var a; for(var b;;);` => `for(var a, b;;);`
pub(super) fn join_vars<T>(&mut self, stmts: &mut Vec<T>)
where
T: ModuleItemExt,
{
if !self.options.join_vars {
return;
}
{
// Check if we can join variables.
let can_work =
stmts
.windows(2)
.any(|stmts| match (stmts[0].as_stmt(), stmts[1].as_stmt()) {
(Some(Stmt::Decl(Decl::Var(l))), Some(r)) => match r {
Stmt::Decl(Decl::Var(r)) => l.kind == r.kind,
Stmt::For(ForStmt { init: None, .. }) => l.kind == VarDeclKind::Var,
Stmt::For(ForStmt {
init: Some(VarDeclOrExpr::VarDecl(v)),
..
}) if matches!(
&**v,
VarDecl {
kind: VarDeclKind::Var,
..
},
) =>
{
l.kind == VarDeclKind::Var
}
_ => false,
},
_ => false,
});
if !can_work {
return;
}
}
report_change!("join_vars: Joining variables");
self.changed = true;
let mut cur: Option<Box<VarDecl>> = None;
let mut new: Vec<T> = Vec::with_capacity(stmts.len() * 2 + 1);
stmts.take().into_iter().for_each(|stmt| {
match stmt.try_into_stmt() {
Ok(stmt) => {
if is_directive(&stmt) {
return new.push(T::from(stmt));
}
match stmt {
Stmt::Decl(Decl::Var(var)) => match &mut cur {
Some(v) if var.kind == v.kind => {
v.decls.extend(var.decls);
}
_ => {
if let Some(s) = cur.take().map(|c| c.into()) {
new.push(T::from(s));
}
cur = Some(var);
}
},
Stmt::For(mut stmt) => match &mut stmt.init {
Some(VarDeclOrExpr::VarDecl(var))
if matches!(
&**var,
VarDecl {
kind: VarDeclKind::Var,
..
}
) =>
{
match &mut cur {
Some(cur) if cur.kind == var.kind => {
// Merge
cur.decls.append(&mut var.decls);
var.decls = cur.decls.take();
new.push(T::from(stmt.into()));
}
_ => {
if let Some(s) = cur.take() {
new.push(T::from(s.into()));
}
new.push(T::from(stmt.into()));
}
}
}
None if cur
.as_ref()
.map(|v| v.kind == VarDeclKind::Var)
.unwrap_or(true) =>
{
stmt.init = cur
.take()
.and_then(|v| if v.decls.is_empty() { None } else { Some(v) })
.map(VarDeclOrExpr::VarDecl);
new.push(T::from(stmt.into()));
}
_ => {
if let Some(s) = cur.take() {
new.push(T::from(s.into()));
}
new.push(T::from(stmt.into()));
}
},
_ => {
if let Some(s) = cur.take() {
new.push(T::from(s.into()));
}
new.push(T::from(stmt));
}
}
}
Err(item) => {
if let Some(s) = cur.take() {
new.push(T::from(s.into()));
}
new.push(item);
}
}
});
if let Some(s) = cur.take() {
new.push(T::from(s.into()));
}
drop_invalid_stmts(&mut new);
*stmts = new;
}
/// TypeScript namespace results in lots of `var ts` declarations.
pub(super) fn remove_duplicate_vars(&mut self, vars: &mut Vec<VarDeclarator>) {
let mut found = FxHashSet::default();
vars.retain(|v| {
if v.init.is_some() {
return true;
}
match &v.name {
Pat::Ident(i) => found.insert(i.to_id()),
_ => true,
}
})
}
/// Collapse single-use non-constant variables, side effects permitting.
///
/// This merges all variables to first variable declartion with an
/// initializer. If such variable declaration is not found, variables are
/// prepended to `stmts`.
pub(super) fn collapse_vars_without_init<T>(&mut self, stmts: &mut Vec<T>, target: VarDeclKind)
where
T: StmtLike,
Vec<T>:
VisitWith<VarWithOutInitCounter> + VisitMutWith<VarMover> + VisitMutWith<VarPrepender>,
{
if !self.options.collapse_vars {
return;
}
{
let mut need_work = false;
let mut found_vars_without_init = false;
let mut found_other = false;
let if_need_work = stmts.iter().any(|stmt| {
match stmt.as_stmt() {
Some(Stmt::Decl(Decl::Var(v))) if v.kind == target => {
if !(found_other && found_vars_without_init)
&& v.decls.iter().all(|v| v.init.is_none())
{
if found_other {
need_work = true;
}
found_vars_without_init = true;
} else {
if found_vars_without_init && self.options.join_vars {
need_work = true;
}
found_other = true;
}
}
// Directives
Some(Stmt::Expr(s)) => match &*s.expr {
Expr::Lit(Lit::Str(..)) => {}
_ => {
found_other = true;
}
},
_ => {
found_other = true;
}
}
need_work
});
// Check for nested variable declartions.
let visitor_need_work = if target == VarDeclKind::Var {
let mut v = VarWithOutInitCounter {
target,
need_work: Default::default(),
found_var_without_init: Default::default(),
found_var_with_init: Default::default(),
};
stmts.visit_with(&mut v);
v.need_work
} else {
false
};
if !if_need_work && !visitor_need_work {
return;
}
}
// TODO(kdy1): Fix this. This results in an infinite loop.
// self.changed = true;
report_change!("collapse_vars: Collapsing variables without an initializer");
let vars = {
let mut v = VarMover {
target,
vars: Default::default(),
var_decl_kind: Default::default(),
};
stmts.visit_mut_with(&mut v);
v.vars
};
// Prepend vars
let mut prepender = VarPrepender { target, vars };
if target == VarDeclKind::Var {
stmts.visit_mut_with(&mut prepender);
}
if !prepender.vars.is_empty() {
match stmts.get_mut(0).and_then(|v| v.as_stmt_mut()) {
Some(Stmt::Decl(Decl::Var(v))) if v.kind == target => {
prepender.vars.append(&mut v.decls);
v.decls = prepender.vars;
}
_ => {
prepend_stmt(
stmts,
T::from(
VarDecl {
span: DUMMY_SP,
kind: target,
declare: Default::default(),
decls: prepender.vars,
..Default::default()
}
.into(),
),
);
}
}
}
}
}
/// See if there's two [VarDecl] which has [VarDeclarator] without the
/// initializer.
pub(super) struct VarWithOutInitCounter {
target: VarDeclKind,
need_work: bool,
found_var_without_init: bool,
found_var_with_init: bool,
}
impl Visit for VarWithOutInitCounter {
noop_visit_type!();
fn visit_arrow_expr(&mut self, _: &ArrowExpr) {}
fn visit_constructor(&mut self, _: &Constructor) {}
fn visit_function(&mut self, _: &Function) {}
fn visit_getter_prop(&mut self, _: &GetterProp) {}
fn visit_setter_prop(&mut self, _: &SetterProp) {}
fn visit_var_decl(&mut self, v: &VarDecl) {
v.visit_children_with(self);
if v.kind != self.target {
return;
}
let mut found_init = false;
for d in &v.decls {
if d.init.is_some() {
found_init = true;
} else {
if found_init {
self.need_work = true;
return;
}
}
}
if v.decls.iter().all(|v| v.init.is_none()) {
if self.found_var_without_init || self.found_var_with_init {
self.need_work = true;
}
self.found_var_without_init = true;
} else {
self.found_var_with_init = true;
}
}
fn visit_module_item(&mut self, s: &ModuleItem) {
if let ModuleItem::Stmt(_) = s {
s.visit_children_with(self);
}
}
fn visit_block_stmt(&mut self, n: &BlockStmt) {
if self.target != VarDeclKind::Var {
// noop
return;
}
n.visit_children_with(self);
}
fn visit_for_head(&mut self, _: &ForHead) {}
}
/// Moves all variable without initializer.
pub(super) struct VarMover {
target: VarDeclKind,
vars: Vec<VarDeclarator>,
var_decl_kind: Option<VarDeclKind>,
}
impl VisitMut for VarMover {
noop_visit_mut_type!();
/// Noop
fn visit_mut_arrow_expr(&mut self, _: &mut ArrowExpr) {}
/// Noop
fn visit_mut_constructor(&mut self, _: &mut Constructor) {}
/// Noop
fn visit_mut_function(&mut self, _: &mut Function) {}
fn visit_mut_getter_prop(&mut self, _: &mut GetterProp) {}
fn visit_mut_setter_prop(&mut self, _: &mut SetterProp) {}
fn visit_mut_module_item(&mut self, s: &mut ModuleItem) {
if let ModuleItem::Stmt(_) = s {
s.visit_mut_children_with(self);
}
}
fn visit_mut_block_stmt(&mut self, n: &mut BlockStmt) {
if self.target != VarDeclKind::Var {
// noop
return;
}
n.visit_mut_children_with(self);
}
fn visit_mut_opt_var_decl_or_expr(&mut self, n: &mut Option<VarDeclOrExpr>) {
n.visit_mut_children_with(self);
if let Some(VarDeclOrExpr::VarDecl(var)) = n {
if var.decls.is_empty() {
*n = None;
}
}
}
fn visit_mut_stmt(&mut self, s: &mut Stmt) {
s.visit_mut_children_with(self);
match s {
Stmt::Decl(Decl::Var(v)) if v.decls.is_empty() => {
s.take();
}
_ => {}
}
}
fn visit_mut_var_decl(&mut self, v: &mut VarDecl) {
let old = self.var_decl_kind.take();
self.var_decl_kind = Some(v.kind);
v.visit_mut_children_with(self);
self.var_decl_kind = old;
}
fn visit_mut_for_head(&mut self, _: &mut ForHead) {}
fn visit_mut_var_declarators(&mut self, d: &mut Vec<VarDeclarator>) {
d.visit_mut_children_with(self);
if self.var_decl_kind != Some(self.target) {
return;
}
if d.iter().all(|v| v.init.is_some()) {
return;
}
let has_init = d.iter().any(|v| v.init.is_some());
if has_init {
if self.target == VarDeclKind::Let {
return;
}
let mut new = Vec::with_capacity(d.len());
d.take().into_iter().for_each(|v| {
if v.init.is_some() {
new.push(v)
} else {
self.vars.push(v)
}
});
*d = new;
}
let mut new = Vec::new();
if has_init {
new.append(&mut self.vars);
}
d.take().into_iter().for_each(|v| {
if v.init.is_some() {
new.push(v)
} else {
self.vars.push(v)
}
});
*d = new;
}
fn visit_mut_module_decl(&mut self, _: &mut ModuleDecl) {}
}
pub(super) struct VarPrepender {
target: VarDeclKind,
vars: Vec<VarDeclarator>,
}
impl VisitMut for VarPrepender {
noop_visit_mut_type!();
/// Noop
fn visit_mut_arrow_expr(&mut self, _: &mut ArrowExpr) {}
/// Noop
fn visit_mut_constructor(&mut self, _: &mut Constructor) {}
/// Noop
fn visit_mut_function(&mut self, _: &mut Function) {}
fn visit_mut_getter_prop(&mut self, _: &mut GetterProp) {}
fn visit_mut_setter_prop(&mut self, _: &mut SetterProp) {}
fn visit_mut_block_stmt(&mut self, n: &mut BlockStmt) {
if self.target != VarDeclKind::Var {
// noop
return;
}
n.visit_mut_children_with(self);
}
fn visit_mut_var_decl(&mut self, v: &mut VarDecl) {
if self.vars.is_empty() {
return;
}
if v.kind != self.target {
return;
}
if v.decls.iter().any(|d| d.init.is_some()) {
let mut decls = self.vars.take();
decls.extend(v.decls.take());
v.decls = decls;
}
}
fn visit_mut_module_decl(&mut self, _: &mut ModuleDecl) {}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/compress/util/mod.rs | Rust | use std::{cmp::Ordering, f64};
use swc_common::{util::take::Take, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_utils::{number::JsNumber, ExprCtx, ExprExt, IdentUsageFinder, Type, Value};
use swc_ecma_visit::{
noop_visit_mut_type, noop_visit_type, Visit, VisitMut, VisitMutWith, VisitWith,
};
#[cfg(feature = "debug")]
use crate::debug::dump;
use crate::util::ModuleItemExt;
#[cfg(test)]
mod tests;
/// Creates `!e` where e is the expression passed as an argument.
///
/// Returns true if this modified ast.
///
/// # Note
///
/// This method returns `!e` if `!!e` is given as a argument.
///
/// TODO: Handle special cases like !1 or !0
pub(super) fn negate(expr_ctx: ExprCtx, e: &mut Expr, in_bool_ctx: bool, is_ret_val_ignored: bool) {
negate_inner(expr_ctx, e, in_bool_ctx, is_ret_val_ignored);
}
fn negate_inner(
expr_ctx: ExprCtx,
e: &mut Expr,
in_bool_ctx: bool,
is_ret_val_ignored: bool,
) -> bool {
#[cfg(feature = "debug")]
let start_str = dump(&*e, false);
match e {
Expr::Bin(bin @ BinExpr { op: op!("=="), .. })
| Expr::Bin(bin @ BinExpr { op: op!("!="), .. })
| Expr::Bin(bin @ BinExpr { op: op!("==="), .. })
| Expr::Bin(bin @ BinExpr { op: op!("!=="), .. }) => {
bin.op = match bin.op {
op!("==") => {
op!("!=")
}
op!("!=") => {
op!("==")
}
op!("===") => {
op!("!==")
}
op!("!==") => {
op!("===")
}
_ => {
unreachable!()
}
};
report_change!("negate: binary");
return true;
}
Expr::Bin(BinExpr {
left,
right,
op: op @ op!("&&"),
..
}) if is_ok_to_negate_rhs(expr_ctx, right) => {
trace_op!("negate: a && b => !a || !b");
let a = negate_inner(expr_ctx, left, in_bool_ctx, false);
let b = negate_inner(expr_ctx, right, in_bool_ctx, is_ret_val_ignored);
*op = op!("||");
return a || b;
}
Expr::Bin(BinExpr {
left,
right,
op: op @ op!("||"),
..
}) if is_ok_to_negate_rhs(expr_ctx, right) => {
trace_op!("negate: a || b => !a && !b");
let a = negate_inner(expr_ctx, left, in_bool_ctx, false);
let b = negate_inner(expr_ctx, right, in_bool_ctx, is_ret_val_ignored);
*op = op!("&&");
return a || b;
}
Expr::Cond(CondExpr { cons, alt, .. })
if is_ok_to_negate_for_cond(cons) && is_ok_to_negate_for_cond(alt) =>
{
trace_op!("negate: cond");
let a = negate_inner(expr_ctx, cons, in_bool_ctx, false);
let b = negate_inner(expr_ctx, alt, in_bool_ctx, is_ret_val_ignored);
return a || b;
}
Expr::Seq(SeqExpr { exprs, .. }) => {
if let Some(last) = exprs.last_mut() {
trace_op!("negate: seq");
return negate_inner(expr_ctx, last, in_bool_ctx, is_ret_val_ignored);
}
}
_ => {}
}
let mut arg = Box::new(e.take());
if let Expr::Unary(UnaryExpr {
op: op!("!"), arg, ..
}) = &mut *arg
{
match &mut **arg {
Expr::Unary(UnaryExpr { op: op!("!"), .. }) => {
report_change!("negate: !!bool => !bool");
*e = *arg.take();
return true;
}
Expr::Bin(BinExpr { op: op!("in"), .. })
| Expr::Bin(BinExpr {
op: op!("instanceof"),
..
}) => {
report_change!("negate: !bool => bool");
*e = *arg.take();
return true;
}
_ => {
if in_bool_ctx {
report_change!("negate: !expr => expr (in bool context)");
*e = *arg.take();
return true;
}
if is_ret_val_ignored {
report_change!("negate: !expr => expr (return value ignored)");
*e = *arg.take();
return true;
}
}
}
}
if is_ret_val_ignored {
log_abort!("negate: noop because it's ignored");
*e = *arg;
false
} else {
report_change!("negate: e => !e");
*e = UnaryExpr {
span: DUMMY_SP,
op: op!("!"),
arg,
}
.into();
dump_change_detail!("Negated `{}` as `{}`", start_str, dump(&*e, false));
true
}
}
pub(crate) fn is_ok_to_negate_for_cond(e: &Expr) -> bool {
!matches!(e, Expr::Update(..))
}
pub(crate) fn is_ok_to_negate_rhs(expr_ctx: ExprCtx, rhs: &Expr) -> bool {
match rhs {
Expr::Member(..) => true,
Expr::Bin(BinExpr {
op: op!("===") | op!("!==") | op!("==") | op!("!="),
..
}) => true,
Expr::Call(..) | Expr::New(..) => false,
Expr::Update(..) => false,
Expr::Bin(BinExpr {
op: op!("&&") | op!("||"),
left,
right,
..
}) => is_ok_to_negate_rhs(expr_ctx, left) && is_ok_to_negate_rhs(expr_ctx, right),
Expr::Bin(BinExpr { left, right, .. }) => {
is_ok_to_negate_rhs(expr_ctx, left) && is_ok_to_negate_rhs(expr_ctx, right)
}
Expr::Assign(e) => is_ok_to_negate_rhs(expr_ctx, &e.right),
Expr::Unary(UnaryExpr {
op: op!("!") | op!("delete"),
..
}) => true,
Expr::Seq(e) => {
if let Some(last) = e.exprs.last() {
is_ok_to_negate_rhs(expr_ctx, last)
} else {
true
}
}
Expr::Cond(e) => {
is_ok_to_negate_rhs(expr_ctx, &e.cons) && is_ok_to_negate_rhs(expr_ctx, &e.alt)
}
_ => {
if !rhs.may_have_side_effects(expr_ctx) {
return true;
}
#[cfg(feature = "debug")]
{
tracing::warn!("unimplemented: is_ok_to_negate_rhs: `{}`", dump(rhs, false));
}
false
}
}
}
/// A negative value means that it's efficient to negate the expression.
#[cfg_attr(feature = "debug", tracing::instrument(skip(e)))]
#[allow(clippy::let_and_return)]
pub(crate) fn negate_cost(
expr_ctx: ExprCtx,
e: &Expr,
in_bool_ctx: bool,
is_ret_val_ignored: bool,
) -> isize {
#[allow(clippy::only_used_in_recursion)]
#[cfg_attr(test, tracing::instrument(skip(e)))]
fn cost(
expr_ctx: ExprCtx,
e: &Expr,
in_bool_ctx: bool,
bin_op: Option<BinaryOp>,
is_ret_val_ignored: bool,
) -> isize {
let cost = (|| {
match e {
Expr::Unary(UnaryExpr {
op: op!("!"), arg, ..
}) => {
// TODO: Check if this argument is actually start of line.
if let Expr::Call(CallExpr {
callee: Callee::Expr(callee),
..
}) = &**arg
{
if let Expr::Fn(..) = &**callee {
return 0;
}
}
match &**arg {
Expr::Bin(BinExpr {
op: op!("&&") | op!("||"),
..
}) => {}
_ => {
if in_bool_ctx {
let c = -cost(expr_ctx, arg, true, None, is_ret_val_ignored);
return c.min(-1);
}
}
}
match &**arg {
Expr::Unary(UnaryExpr { op: op!("!"), .. }) => -1,
_ => {
if in_bool_ctx {
-1
} else {
1
}
}
}
}
Expr::Bin(BinExpr {
op: op!("===") | op!("!==") | op!("==") | op!("!="),
..
}) => 0,
Expr::Bin(BinExpr {
op: op @ op!("||") | op @ op!("&&"),
left,
right,
..
}) => {
let l_cost = cost(expr_ctx, left, in_bool_ctx, Some(*op), false);
if !is_ret_val_ignored && !is_ok_to_negate_rhs(expr_ctx, right) {
return l_cost + 3;
}
l_cost + cost(expr_ctx, right, in_bool_ctx, Some(*op), is_ret_val_ignored)
}
Expr::Cond(CondExpr { cons, alt, .. })
if is_ok_to_negate_for_cond(cons) && is_ok_to_negate_for_cond(alt) =>
{
cost(expr_ctx, cons, in_bool_ctx, bin_op, is_ret_val_ignored)
+ cost(expr_ctx, alt, in_bool_ctx, bin_op, is_ret_val_ignored)
}
Expr::Cond(..)
| Expr::Update(..)
| Expr::Bin(BinExpr {
op: op!("in") | op!("instanceof"),
..
}) => 3,
Expr::Assign(..) => {
if is_ret_val_ignored {
0
} else {
3
}
}
Expr::Seq(e) => {
if let Some(last) = e.exprs.last() {
return cost(expr_ctx, last, in_bool_ctx, bin_op, is_ret_val_ignored);
}
isize::from(!is_ret_val_ignored)
}
_ => isize::from(!is_ret_val_ignored),
}
})();
cost
}
let cost = cost(expr_ctx, e, in_bool_ctx, None, is_ret_val_ignored);
cost
}
pub(crate) fn is_pure_undefined(expr_ctx: ExprCtx, e: &Expr) -> bool {
match e {
Expr::Unary(UnaryExpr {
op: UnaryOp::Void,
arg,
..
}) if !arg.may_have_side_effects(expr_ctx) => true,
_ => e.is_undefined(expr_ctx),
}
}
pub(crate) fn is_primitive(expr_ctx: ExprCtx, e: &Expr) -> Option<&Expr> {
if is_pure_undefined(expr_ctx, 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 && !s.is_ascii() {
return false;
}
s.starts_with(Ident::is_valid_start)
&& s.chars().skip(1).all(Ident::is_valid_continue)
&& !s.is_reserved()
}
pub(crate) fn is_directive(e: &Stmt) -> bool {
match e {
Stmt::Expr(s) => match &*s.expr {
Expr::Lit(Lit::Str(Str { value, .. })) => value.starts_with("use "),
_ => false,
},
_ => false,
}
}
pub(crate) fn is_pure_undefined_or_null(expr_ctx: ExprCtx, e: &Expr) -> bool {
is_pure_undefined(expr_ctx, e) || matches!(e, Expr::Lit(Lit::Null(..)))
}
/// This method does **not** modifies `e`.
///
/// This method is used to test if a whole call can be replaced, while
/// preserving standalone constants.
pub(crate) fn eval_as_number(expr_ctx: ExprCtx, e: &Expr) -> Option<f64> {
match e {
Expr::Bin(BinExpr {
op: op!(bin, "-"),
left,
right,
..
}) => {
let l = eval_as_number(expr_ctx, left)?;
let r = eval_as_number(expr_ctx, right)?;
return Some(l - r);
}
Expr::Call(CallExpr {
callee: Callee::Expr(callee),
args,
..
}) => {
for arg in args {
if arg.spread.is_some() || arg.expr.may_have_side_effects(expr_ctx) {
return None;
}
}
if let Expr::Member(MemberExpr {
obj,
prop: MemberProp::Ident(prop),
..
}) = &**callee
{
match &**obj {
Expr::Ident(obj) if &*obj.sym == "Math" => match &*prop.sym {
"cos" => {
let v = eval_as_number(expr_ctx, &args.first()?.expr)?;
return Some(v.cos());
}
"sin" => {
let v = eval_as_number(expr_ctx, &args.first()?.expr)?;
return Some(v.sin());
}
"max" => {
let mut numbers = Vec::new();
for arg in args {
let v = eval_as_number(expr_ctx, &arg.expr)?;
if v.is_infinite() || v.is_nan() {
return None;
}
numbers.push(v);
}
return Some(
numbers
.into_iter()
.max_by(|&a, &b| cmp_num(a, b))
.unwrap_or(f64::NEG_INFINITY),
);
}
"min" => {
let mut numbers = Vec::new();
for arg in args {
let v = eval_as_number(expr_ctx, &arg.expr)?;
if v.is_infinite() || v.is_nan() {
return None;
}
numbers.push(v);
}
return Some(
numbers
.into_iter()
.min_by(|&a, &b| cmp_num(a, b))
.unwrap_or(f64::INFINITY),
);
}
"pow" => {
if args.len() != 2 {
return None;
}
let base: JsNumber = eval_as_number(expr_ctx, &args[0].expr)?.into();
let exponent: JsNumber =
eval_as_number(expr_ctx, &args[1].expr)?.into();
return Some(base.pow(exponent).into());
}
_ => {}
},
_ => {}
}
}
}
Expr::Member(MemberExpr {
obj,
prop: MemberProp::Ident(prop),
..
}) => match &**obj {
Expr::Ident(obj) if &*obj.sym == "Math" => match &*prop.sym {
"PI" => return Some(f64::consts::PI),
"E" => return Some(f64::consts::E),
"LN10" => return Some(f64::consts::LN_10),
_ => {}
},
_ => {}
},
_ => {
if let Value::Known(v) = e.as_pure_number(expr_ctx) {
return Some(v);
}
}
}
None
}
pub(crate) fn is_ident_used_by<N>(id: Id, node: &N) -> bool
where
N: for<'aa> VisitWith<IdentUsageFinder<'aa>>,
{
IdentUsageFinder::find(&id, node)
}
pub struct ExprReplacer<F>
where
F: FnMut(&mut Expr),
{
op: F,
}
impl<F> VisitMut for ExprReplacer<F>
where
F: FnMut(&mut Expr),
{
noop_visit_mut_type!();
fn visit_mut_expr(&mut self, e: &mut Expr) {
e.visit_mut_children_with(self);
(self.op)(e);
}
}
pub fn replace_expr<N, F>(node: &mut N, op: F)
where
N: VisitMutWith<ExprReplacer<F>>,
F: FnMut(&mut Expr),
{
node.visit_mut_with(&mut ExprReplacer { op })
}
pub(super) fn is_fine_for_if_cons(s: &Stmt) -> bool {
match s {
Stmt::Decl(Decl::Fn(FnDecl {
ident: Ident { sym, .. },
..
})) if &**sym == "undefined" => false,
Stmt::Decl(Decl::Var(v))
if matches!(
&**v,
VarDecl {
kind: VarDeclKind::Var,
..
}
) =>
{
true
}
Stmt::Decl(Decl::Fn(..)) => true,
Stmt::Decl(..) => false,
_ => true,
}
}
pub(super) fn drop_invalid_stmts<T>(stmts: &mut Vec<T>)
where
T: ModuleItemExt,
{
stmts.retain(|s| match s.as_module_decl() {
Ok(s) => match s {
ModuleDecl::ExportDecl(ExportDecl {
decl: Decl::Var(v), ..
}) => !v.decls.is_empty(),
_ => true,
},
Err(s) => match s {
Stmt::Empty(..) => false,
Stmt::Decl(Decl::Var(v)) => !v.decls.is_empty(),
_ => true,
},
});
}
#[derive(Debug, Default)]
pub(super) struct UnreachableHandler {
vars: Vec<Ident>,
in_var_name: bool,
in_hoisted_var: bool,
}
impl UnreachableHandler {
/// Assumes `s` is not reachable, and preserves variable declarations and
/// function declarations in `s`.
///
/// Returns true if statement is changed.
pub fn preserve_vars(s: &mut Stmt) -> bool {
if s.is_empty() {
return false;
}
if let Stmt::Decl(Decl::Var(v)) = s {
let mut changed = false;
for decl in &mut v.decls {
if decl.init.is_some() {
decl.init = None;
changed = true;
}
}
return changed;
}
let mut v = Self::default();
s.visit_mut_with(&mut v);
if v.vars.is_empty() {
*s = EmptyStmt { span: DUMMY_SP }.into();
} else {
*s = VarDecl {
span: DUMMY_SP,
kind: VarDeclKind::Var,
declare: false,
decls: v
.vars
.into_iter()
.map(BindingIdent::from)
.map(Pat::Ident)
.map(|name| VarDeclarator {
span: DUMMY_SP,
name,
init: None,
definite: false,
})
.collect(),
..Default::default()
}
.into()
}
true
}
}
impl VisitMut for UnreachableHandler {
noop_visit_mut_type!();
fn visit_mut_arrow_expr(&mut self, _: &mut ArrowExpr) {}
fn visit_mut_fn_decl(&mut self, n: &mut FnDecl) {
self.vars.push(n.ident.clone());
n.function.visit_mut_with(self);
}
fn visit_mut_function(&mut self, _: &mut Function) {}
fn visit_mut_pat(&mut self, n: &mut Pat) {
n.visit_mut_children_with(self);
if self.in_var_name && self.in_hoisted_var {
if let Pat::Ident(i) = n {
self.vars.push(i.id.clone());
}
}
}
fn visit_mut_var_decl(&mut self, n: &mut VarDecl) {
self.in_hoisted_var = n.kind == VarDeclKind::Var;
n.visit_mut_children_with(self);
}
fn visit_mut_var_declarator(&mut self, n: &mut VarDeclarator) {
self.in_var_name = true;
n.name.visit_mut_with(self);
self.in_var_name = false;
n.init.visit_mut_with(self);
}
}
// TODO: remove
pub(crate) fn contains_super<N>(body: &N) -> bool
where
N: VisitWith<SuperFinder>,
{
let mut visitor = SuperFinder { found: false };
body.visit_with(&mut visitor);
visitor.found
}
pub struct SuperFinder {
found: bool,
}
impl Visit for SuperFinder {
noop_visit_type!();
/// Don't recurse into constructor
fn visit_constructor(&mut self, _: &Constructor) {}
/// Don't recurse into fn
fn visit_function(&mut self, _: &Function) {}
fn visit_prop(&mut self, n: &Prop) {
n.visit_children_with(self);
if let Prop::Shorthand(Ident { sym, .. }) = n {
if &**sym == "arguments" {
self.found = true;
}
}
}
fn visit_super(&mut self, _: &Super) {
self.found = true;
}
}
fn cmp_num(a: f64, b: f64) -> Ordering {
if a == 0.0 && a.is_sign_negative() && b == 0.0 && b.is_sign_positive() {
return Ordering::Less;
}
if a == 0.0 && a.is_sign_positive() && b == 0.0 && b.is_sign_negative() {
return Ordering::Greater;
}
a.partial_cmp(&b).unwrap()
}
pub(crate) fn is_eq(op: BinaryOp) -> bool {
matches!(op, op!("==") | op!("===") | op!("!=") | op!("!=="))
}
pub(crate) fn can_absorb_negate(e: &Expr, expr_ctx: ExprCtx) -> bool {
match e {
Expr::Lit(_) => true,
Expr::Bin(BinExpr {
op: op!("&&") | op!("||"),
left,
right,
..
}) => can_absorb_negate(left, expr_ctx) && can_absorb_negate(right, expr_ctx),
Expr::Bin(BinExpr { op, .. }) if is_eq(*op) => true,
Expr::Unary(UnaryExpr {
op: op!("!"), arg, ..
}) => arg.get_type(expr_ctx) == Value::Known(Type::Bool),
_ => false,
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/compress/util/tests.rs | Rust | use swc_common::{util::take::Take, FileName, Mark, SyntaxContext};
use swc_ecma_ast::*;
use swc_ecma_parser::parse_file_as_expr;
use swc_ecma_transforms_base::fixer::fixer;
use swc_ecma_utils::ExprCtx;
use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith};
use tracing::{info, warn};
use super::negate_cost;
use crate::{compress::util::negate, debug::dump};
struct UnwrapParen;
impl VisitMut for UnwrapParen {
noop_visit_mut_type!();
fn visit_mut_expr(&mut self, e: &mut Expr) {
e.visit_mut_children_with(self);
if let Expr::Paren(p) = e {
*e = *p.expr.take();
}
}
}
fn assert_negate_cost(s: &str, in_bool_ctx: bool, is_ret_val_ignored: bool, expected: isize) {
testing::run_test2(false, |cm, handler| {
let fm = cm.new_source_file(FileName::Anon.into(), s.to_string());
let mut e = parse_file_as_expr(
&fm,
Default::default(),
swc_ecma_ast::EsVersion::latest(),
None,
&mut Vec::new(),
)
.map_err(|e| {
e.into_diagnostic(&handler).emit();
})?;
e.visit_mut_with(&mut UnwrapParen);
let input = {
let mut e = e.clone();
e.visit_mut_with(&mut fixer(None));
dump(&e, true)
};
let expr_ctx = ExprCtx {
unresolved_ctxt: SyntaxContext::empty().apply_mark(Mark::new()),
is_unresolved_ref_safe: false,
in_strict: false,
remaining_depth: 2,
};
let real = {
let mut real = e.clone();
negate(expr_ctx, &mut real, in_bool_ctx, is_ret_val_ignored);
real.visit_mut_with(&mut fixer(None));
dump(&real, true)
};
{
warn!(
"Actual: {} ;Input = {}, Real = {}",
real.len() as isize - input.len() as isize,
input.len(),
real.len()
);
info!("Real: {}", real);
info!("Input: {}", input);
}
let actual = negate_cost(expr_ctx, &e, in_bool_ctx, is_ret_val_ignored);
assert_eq!(
actual, expected,
"Expected negation cost of {} to be {}, but got {}",
s, expected, actual,
);
Ok(())
})
.unwrap();
}
#[test]
fn negate_cost_1() {
assert_negate_cost(
"this[key] && !this.hasOwnProperty(key) || (this[key] = value)",
false,
true,
2,
);
}
#[test]
#[ignore]
fn negate_cost_2() {
assert_negate_cost(
"(!this[key] || this.hasOwnProperty(key)) && (this[key] = value)",
false,
true,
-2,
);
}
#[test]
fn negate_cost_3() {
assert_negate_cost(
"(pvt || (delete cache[id].data, isEmptyDataObject(cache[id]))) && (isNode ? \
jQuery.cleanData([
elem
], !0) : jQuery.support.deleteExpando || cache != cache.window ? delete cache[id] : \
cache[id] = null)",
true,
true,
4,
);
}
#[test]
#[ignore]
fn negate_cost_4() {
// "(!force && !this._isRebuildRequired()) && !self._buildList()",
assert_negate_cost(
"!(force || this._isRebuildRequired()) || self._buildList()",
true,
true,
2,
);
}
#[test]
fn negate_cost_5() {
assert_negate_cost(
"!(capacity && codeResult1 && (codeResult2 = codeResult1, !((list = config.blacklist) && \
list.some(function(item) {
return Object.keys(item).every(function(key) {
return item[key] === codeResult2[key];
});
}))) && (codeResult3 = codeResult1, \"function\" != typeof (filter = config.filter) || \
filter(codeResult3))) || (capacity--, result.codeResult = codeResult, capture && \
(canvas.width = imageSize.x, canvas.height = imageSize.y, image_debug.a.drawImage(data, \
imageSize, ctx), result.frame = canvas.toDataURL()), results.push(result))",
true,
true,
-1,
);
}
#[test]
fn negate_cost_5_1() {
assert_negate_cost(
"!(capacity && codeResult1 && (codeResult2 = codeResult1, !((list = config.blacklist) && \
list.some(function(item) {
return Object.keys(item).every(function(key) {
return item[key] === codeResult2[key];
});
}))) && (codeResult3 = codeResult1, \"function\" != typeof (filter = config.filter) || \
filter(codeResult3)))",
true,
false,
-1,
);
}
#[test]
fn negate_cost_5_2() {
assert_negate_cost(
"!(capacity && codeResult1 && (codeResult2 = codeResult1, !((list = config.blacklist) && \
list.some(function(item) {
return Object.keys(item).every(function(key) {
return item[key] === codeResult2[key];
});
}))))",
true,
false,
-1,
);
}
#[test]
fn negate_cost_5_3() {
assert_negate_cost(
"!(codeResult2 = codeResult1, !((list = config.blacklist) && list.some(function(item) {
return Object.keys(item).every(function(key) {
return item[key] === codeResult2[key];
});
})))",
true,
false,
-1,
);
}
#[test]
fn negate_cost_6() {
assert_negate_cost(
"
capacity && codeResult1 && (codeResult2 = codeResult1, !((list = config.blacklist) && \
list.some(function(item) {
return Object.keys(item).every(function(key) {
return item[key] === codeResult2[key];
});
}))) && (codeResult3 = codeResult1, \"function\" != typeof (filter = config.filter) || \
filter(codeResult3)) && (capacity--, result.codeResult = codeResult, capture && \
(canvas.width = imageSize.x, canvas.height = imageSize.y, image_debug.a.drawImage(data, \
imageSize, ctx), result.frame = canvas.toDataURL()), results.push(result))",
true,
true,
4,
);
}
#[test]
fn negate_cost_6_1() {
assert_negate_cost(
"
capacity && codeResult1 && (codeResult2 = codeResult1, !((list = config.blacklist) && \
list.some(function(item) {
return Object.keys(item).every(function(key) {
return item[key] === codeResult2[key];
});
}))) && (codeResult3 = codeResult1, \"function\" != typeof (filter = config.filter) || \
filter(codeResult3))",
true,
false,
4,
);
}
#[test]
fn negate_cost_6_2() {
assert_negate_cost(
"
!((list = config.blacklist) && list.some(function(item) {
return Object.keys(item).every(function(key) {
return item[key] === codeResult2[key];
});
}))",
true,
false,
-1,
);
}
#[test]
#[ignore]
fn next_31077_1() {
assert_negate_cost(
"((!a || !(a instanceof TextViewDesc1) || /\\n$/.test(a.node.text)) && ((result1.safari \
|| result1.chrome) && a && 'false' == a.dom.contentEditable && this.addHackNode('IMG'), \
this.addHackNode('BR')))",
true,
true,
0,
);
}
#[test]
#[ignore]
fn next_31077_2() {
assert_negate_cost(
"!((!a || !(a instanceof TextViewDesc1) || /\\n$/.test(a.node.text)) || ((result1.safari \
|| result1.chrome) && a && 'false' == a.dom.contentEditable && this.addHackNode('IMG'), \
this.addHackNode('BR')))",
true,
true,
-3,
);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/debug.rs | Rust | use swc_common::{sync::Lrc, SourceMap, SyntaxContext};
use swc_ecma_ast::*;
use swc_ecma_codegen::{text_writer::JsWriter, Emitter};
pub use swc_ecma_transforms_optimization::AssertValid;
use swc_ecma_utils::{drop_span, DropSpan};
use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith};
pub(crate) struct Debugger {}
impl VisitMut for Debugger {
noop_visit_mut_type!();
fn visit_mut_ident(&mut self, n: &mut Ident) {
if !cfg!(feature = "debug") {
return;
}
if n.ctxt == SyntaxContext::empty() {
return;
}
n.sym = format!("{}{:?}", n.sym, n.ctxt).into();
n.ctxt = SyntaxContext::empty();
}
}
pub(crate) fn dump<N>(node: &N, force: bool) -> String
where
N: swc_ecma_codegen::Node + Clone + VisitMutWith<DropSpan> + VisitMutWith<Debugger>,
{
if !force {
#[cfg(not(feature = "debug"))]
{
return String::new();
}
}
let mut node = node.clone();
node.visit_mut_with(&mut Debugger {});
node = drop_span(node);
let mut buf = Vec::new();
let cm = Lrc::new(SourceMap::default());
{
let mut emitter = Emitter {
cfg: Default::default(),
cm: cm.clone(),
comments: None,
wr: Box::new(JsWriter::new(cm, "\n", &mut buf, None)),
};
node.emit_with(&mut emitter).unwrap();
}
String::from_utf8(buf).unwrap()
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/eval.rs | Rust | use std::sync::Arc;
use parking_lot::Mutex;
use rustc_hash::FxHashMap;
use swc_atoms::atom;
use swc_common::{SyntaxContext, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_transforms_optimization::simplify::{expr_simplifier, ExprSimplifierConfig};
use swc_ecma_usage_analyzer::marks::Marks;
use swc_ecma_utils::{ExprCtx, ExprExt};
use swc_ecma_visit::VisitMutWith;
use crate::{
compress::{compressor, pure_optimizer, PureOptimizerConfig},
mode::Mode,
option::{CompressOptions, TopLevelOptions},
};
pub struct Evaluator {
expr_ctx: ExprCtx,
program: Program,
marks: Marks,
data: Eval,
/// We run minification only once.
done: bool,
}
impl Evaluator {
pub fn new(module: Module, marks: Marks) -> Self {
Evaluator {
expr_ctx: ExprCtx {
unresolved_ctxt: SyntaxContext::empty().apply_mark(marks.unresolved_mark),
is_unresolved_ref_safe: false,
in_strict: true,
remaining_depth: 3,
},
program: Program::Module(module),
marks,
data: Default::default(),
done: Default::default(),
}
}
}
#[derive(Default, Clone)]
struct Eval {
store: Arc<Mutex<EvalStore>>,
}
#[derive(Default)]
struct EvalStore {
cache: FxHashMap<Id, Box<Expr>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EvalResult {
Lit(Lit),
Undefined,
}
impl Mode for Eval {
fn store(&self, id: Id, value: &Expr) {
let mut w = self.store.lock();
w.cache.insert(id, Box::new(value.clone()));
}
fn preserve_vars(&self) -> bool {
true
}
fn should_be_very_correct(&self) -> bool {
false
}
fn force_str_for_tpl(&self) -> bool {
true
}
}
impl Evaluator {
#[tracing::instrument(name = "Evaluator::run", level = "debug", skip_all)]
fn run(&mut self) {
if !self.done {
self.done = true;
let marks = self.marks;
let data = self.data.clone();
//
self.program.mutate(&mut compressor(
marks,
&CompressOptions {
// We should not drop unused variables.
unused: false,
top_level: Some(TopLevelOptions { functions: true }),
..Default::default()
},
None,
&data,
));
}
}
pub fn eval(&mut self, e: &Expr) -> Option<EvalResult> {
match e {
Expr::Seq(s) => return self.eval(s.exprs.last()?),
Expr::Lit(
l @ Lit::Num(..)
| l @ Lit::Str(..)
| l @ Lit::BigInt(..)
| l @ Lit::Bool(..)
| l @ Lit::Null(..),
) => return Some(EvalResult::Lit(l.clone())),
Expr::Tpl(t) => {
return self.eval_tpl(t);
}
Expr::TaggedTpl(t) => {
// Handle `String.raw`
match &*t.tag {
Expr::Member(MemberExpr {
obj: tag_obj,
prop: MemberProp::Ident(prop),
..
}) if tag_obj.is_global_ref_to(self.expr_ctx, "String")
&& prop.sym == *"raw" =>
{
return self.eval_tpl(&t.tpl);
}
_ => {}
}
}
Expr::Cond(c) => {
let test = self.eval(&c.test)?;
if is_truthy(&test)? {
return self.eval(&c.cons);
} else {
return self.eval(&c.alt);
}
}
// TypeCastExpression, ExpressionStatement etc
Expr::TsTypeAssertion(e) => {
return self.eval(&e.expr);
}
Expr::TsConstAssertion(e) => {
return self.eval(&e.expr);
}
// "foo".length
Expr::Member(MemberExpr { obj, prop, .. })
if obj.is_lit() && prop.is_ident_with("length") => {}
Expr::Unary(UnaryExpr {
op: op!("void"), ..
}) => return Some(EvalResult::Undefined),
Expr::Unary(UnaryExpr {
op: op!("!"), arg, ..
}) => {
let arg = self.eval(arg)?;
if is_truthy(&arg)? {
return Some(EvalResult::Lit(Lit::Bool(Bool {
span: DUMMY_SP,
value: false,
})));
} else {
return Some(EvalResult::Lit(Lit::Bool(Bool {
span: DUMMY_SP,
value: true,
})));
}
}
_ => {}
}
Some(EvalResult::Lit(self.eval_as_expr(e)?.lit()?))
}
fn eval_as_expr(&mut self, e: &Expr) -> Option<Box<Expr>> {
match e {
Expr::Ident(i) => {
self.run();
let lock = self.data.store.lock();
let val = lock.cache.get(&i.to_id())?;
return Some(val.clone());
}
Expr::Member(MemberExpr {
span, obj, prop, ..
}) if !prop.is_computed() => {
let obj = self.eval_as_expr(obj)?;
let mut e: Expr = MemberExpr {
span: *span,
obj,
prop: prop.clone(),
}
.into();
e.visit_mut_with(&mut expr_simplifier(
self.marks.unresolved_mark,
ExprSimplifierConfig {},
));
return Some(Box::new(e));
}
_ => {}
}
None
}
pub fn eval_tpl(&mut self, q: &Tpl) -> Option<EvalResult> {
self.run();
let mut exprs = Vec::new();
for expr in &q.exprs {
let res = self.eval(expr)?;
exprs.push(match res {
EvalResult::Lit(v) => v.into(),
EvalResult::Undefined => Expr::undefined(DUMMY_SP),
});
}
let mut e: Box<Expr> = Tpl {
span: q.span,
exprs,
quasis: q.quasis.clone(),
}
.into();
{
e.visit_mut_with(&mut pure_optimizer(
&Default::default(),
self.marks,
PureOptimizerConfig {
enable_join_vars: false,
force_str_for_tpl: self.data.force_str_for_tpl(),
#[cfg(feature = "debug")]
debug_infinite_loop: false,
},
));
}
Some(EvalResult::Lit(e.lit()?))
}
}
fn is_truthy(lit: &EvalResult) -> Option<bool> {
match lit {
EvalResult::Lit(v) => match v {
Lit::Str(v) => Some(v.value != atom!("")),
Lit::Bool(v) => Some(v.value),
Lit::Null(_) => Some(false),
Lit::Num(v) => Some(v.value != 0.0 && v.value != -0.0),
_ => None,
},
EvalResult::Undefined => Some(false),
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/js.rs | Rust | //! NOT A PUBLIC API
use serde::{Deserialize, Serialize};
use swc_config::{config_types::BoolOrDataConfig, IsModule, SourceMapContent};
use crate::option::{
terser::{TerserCompressorOptions, TerserEcmaVersion},
MangleOptions,
};
/// Second argument of `minify`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct JsMinifyOptions {
#[serde(default)]
pub parse: JsMinifyParseOptions,
#[serde(default)]
pub compress: BoolOrDataConfig<TerserCompressorOptions>,
#[serde(default)]
pub mangle: BoolOrDataConfig<MangleOptions>,
#[serde(default, alias = "output")]
pub format: JsMinifyFormatOptions,
#[serde(default)]
pub ecma: TerserEcmaVersion,
#[serde(default, alias = "keep_classnames")]
pub keep_classnames: bool,
#[serde(default, alias = "keep_fnames")]
pub keep_fnames: bool,
#[serde(default = "default_module")]
pub module: IsModule,
#[serde(default)]
pub safari10: bool,
#[serde(default)]
pub toplevel: Option<bool>,
#[serde(default)]
pub source_map: BoolOrDataConfig<TerserSourceMapOption>,
#[serde(default)]
pub output_path: Option<String>,
#[serde(default = "true_by_default")]
pub inline_sources_content: bool,
#[serde(default = "true_by_default")]
pub emit_source_map_columns: bool,
}
fn true_by_default() -> bool {
true
}
/// `sourceMap` of `minify()`.`
///
/// `jsc.minify.sourceMap`
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct TerserSourceMapOption {
#[serde(default)]
pub filename: Option<String>,
#[serde(default)]
pub url: Option<String>,
#[serde(default)]
pub root: Option<String>,
#[serde(default)]
pub content: Option<SourceMapContent>,
}
/// Parser options for `minify()`, which should have the same API as terser.
///
/// `jsc.minify.parse` is ignored.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct JsMinifyParseOptions {
/// Not supported.
#[serde(default, alias = "bare_returns")]
pub bare_returns: bool,
/// Ignored, and always parsed.
#[serde(default = "true_by_default", alias = "html5_comments")]
pub html5_comments: bool,
/// Ignored, and always parsed.
#[serde(default = "true_by_default")]
pub shebang: bool,
/// Not supported.
#[serde(default)]
pub spidermonkey: bool,
}
/// `jsc.minify.format`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct JsMinifyFormatOptions {
/// Not implemented yet.
#[serde(default, alias = "ascii_only")]
pub ascii_only: bool,
/// Not implemented yet.
#[serde(default)]
pub beautify: bool,
/// Not implemented yet.
#[serde(default)]
pub braces: bool,
#[serde(default = "default_comments")]
pub comments: BoolOrDataConfig<JsMinifyCommentOption>,
/// Not implemented yet.
#[serde(default)]
pub ecma: usize,
/// Not implemented yet.
#[serde(default, alias = "indent_level")]
pub indent_level: Option<usize>,
/// Not implemented yet.
#[serde(default, alias = "indent_start")]
pub indent_start: bool,
#[serde(default = "true_by_default", alias = "inline_script")]
pub inline_script: bool,
/// Not implemented yet.
#[serde(default, alias = "keep_numbers")]
pub keep_numbers: bool,
/// Not implemented yet.
#[serde(default, alias = "keep_quoted_props")]
pub keep_quoted_props: bool,
/// Not implemented yet.
#[serde(default, alias = "max_line_len")]
pub max_line_len: usize,
/// Not implemented yet.
#[serde(default)]
pub preamble: String,
/// Not implemented yet.
#[serde(default, alias = "quote_keys")]
pub quote_keys: bool,
/// Not implemented yet.
#[serde(default, alias = "quote_style")]
pub quote_style: usize,
/// Not implemented yet.
#[serde(default, alias = "preserve_annotations")]
pub preserve_annotations: bool,
/// Not implemented yet.
#[serde(default)]
pub safari10: bool,
/// Not implemented yet.
#[serde(default)]
pub semicolons: bool,
/// Not implemented yet.
#[serde(default)]
pub shebang: bool,
/// Not implemented yet.
#[serde(default)]
pub webkit: bool,
/// Not implemented yet.
#[serde(default, alias = "warp_iife")]
pub wrap_iife: bool,
/// Not implemented yet.
#[serde(default, alias = "wrap_func_args")]
pub wrap_func_args: bool,
#[serde(default)]
pub emit_assert_for_import_attributes: bool,
}
impl Default for JsMinifyFormatOptions {
fn default() -> Self {
// Well, this should be a macro IMHO, but it's not so let's just use hacky way.
serde_json::from_str("{}").unwrap()
}
}
fn default_comments() -> BoolOrDataConfig<JsMinifyCommentOption> {
BoolOrDataConfig::from_obj(JsMinifyCommentOption::PreserveSomeComments)
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub enum JsMinifyCommentOption {
#[serde(rename = "some")]
#[default]
PreserveSomeComments,
#[serde(rename = "all")]
PreserveAllComments,
}
fn default_module() -> IsModule {
IsModule::Bool(false)
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/lib.rs | Rust | //! JavaScript minifier implemented in rust.
//!
//! # Assumptions
//!
//! Like other minification tools, swc minifier assumes some things about the
//! input code.
//!
//! - TDZ violation does not exist.
//!
//! In other words, TDZ violation will be ignored.
//!
//! - Acesssing top-level identifiers do not have side effects.
//!
//! If you declare a variable on `globalThis` using a getter with side-effects,
//! swc minifier will break it.
//!
//! # Debugging
//!
//! In debug build, if you set an environment variable `SWC_CHECK` to `1`, the
//! minifier will check the validity of the syntax using `node --check`
//!
//! # Cargo features
//!
//! ## `debug`
//!
//! If you enable this cargo feature and set the environment variable named
//! `SWC_RUN` to `1`, the minifier will validate the code using node before each
//! step.
#![deny(clippy::all)]
#![allow(clippy::blocks_in_conditions)]
#![allow(clippy::collapsible_else_if)]
#![allow(clippy::collapsible_if)]
#![allow(clippy::ptr_arg)]
#![allow(clippy::vec_box)]
#![allow(clippy::overly_complex_bool_expr)]
#![allow(clippy::mutable_key_type)]
#![allow(clippy::only_used_in_recursion)]
#![allow(unstable_name_collisions)]
#![allow(clippy::match_like_matches_macro)]
use once_cell::sync::Lazy;
use pass::mangle_names::mangle_names;
use swc_common::{comments::Comments, pass::Repeated, sync::Lrc, SourceMap, SyntaxContext};
use swc_ecma_ast::*;
use swc_ecma_transforms_optimization::debug_assert_valid;
use swc_ecma_usage_analyzer::marks::Marks;
use swc_ecma_utils::ExprCtx;
use swc_ecma_visit::VisitMutWith;
use swc_timer::timer;
pub use crate::pass::global_defs::globals_defs;
use crate::{
compress::{compressor, pure_optimizer, PureOptimizerConfig},
metadata::info_marker,
mode::{Minification, Mode},
option::{CompressOptions, ExtraOptions, MinifyOptions},
pass::{
global_defs, mangle_names::idents_to_preserve, mangle_props::mangle_properties,
merge_exports::merge_exports, postcompress::postcompress_optimizer,
precompress::precompress_optimizer,
},
// program_data::ModuleInfo,
timing::Timings,
util::base54::CharFreq,
};
#[macro_use]
mod macros;
mod compress;
mod debug;
pub mod eval;
#[doc(hidden)]
pub mod js;
mod metadata;
mod mode;
pub mod option;
mod pass;
mod program_data;
mod size_hint;
pub mod timing;
mod util;
pub mod marks {
pub use swc_ecma_usage_analyzer::marks::Marks;
}
const DISABLE_BUGGY_PASSES: bool = true;
pub(crate) static CPU_COUNT: Lazy<usize> = Lazy::new(num_cpus::get);
pub(crate) static HEAVY_TASK_PARALLELS: Lazy<usize> = Lazy::new(|| *CPU_COUNT * 8);
pub(crate) static LIGHT_TASK_PARALLELS: Lazy<usize> = Lazy::new(|| *CPU_COUNT * 100);
pub fn optimize(
mut n: Program,
_cm: Lrc<SourceMap>,
comments: Option<&dyn Comments>,
mut timings: Option<&mut Timings>,
options: &MinifyOptions,
extra: &ExtraOptions,
) -> Program {
let _timer = timer!("minify");
let mut marks = Marks::new();
marks.top_level_ctxt = SyntaxContext::empty().apply_mark(extra.top_level_mark);
marks.unresolved_mark = extra.unresolved_mark;
debug_assert_valid(&n);
if let Some(defs) = options.compress.as_ref().map(|c| &c.global_defs) {
let _timer = timer!("inline global defs");
// Apply global defs.
//
// As terser treats `CONFIG['VALUE']` and `CONFIG.VALUE` differently, we don't
// have to see if optimized code matches global definition and we can run
// this at startup.
if !defs.is_empty() {
let defs = defs.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
n.visit_mut_with(&mut global_defs::globals_defs(
defs,
extra.unresolved_mark,
extra.top_level_mark,
));
}
}
if let Some(_options) = &options.compress {
let _timer = timer!("precompress");
n.visit_mut_with(&mut precompress_optimizer(ExprCtx {
unresolved_ctxt: SyntaxContext::empty().apply_mark(marks.unresolved_mark),
is_unresolved_ref_safe: false,
in_strict: false,
remaining_depth: 6,
}));
debug_assert_valid(&n);
}
if options.compress.is_some() {
n.visit_mut_with(&mut info_marker(
options.compress.as_ref(),
comments,
marks,
// extra.unresolved_mark,
));
debug_assert_valid(&n);
}
if options.wrap {
// TODO: wrap_common_js
// toplevel = toplevel.wrap_commonjs(options.wrap);
}
if options.enclose {
// TODO: enclose
// toplevel = toplevel.wrap_enclose(options.enclose);
}
if let Some(ref mut t) = timings {
t.section("compress");
}
if let Some(options) = &options.compress {
if options.unused {
perform_dce(&mut n, options, extra);
debug_assert_valid(&n);
}
}
// We don't need validation.
if let Some(ref mut _t) = timings {
// TODO: store `rename`
}
// Noop.
// https://github.com/mishoo/UglifyJS2/issues/2794
if options.rename && DISABLE_BUGGY_PASSES {
// toplevel.figure_out_scope(options.mangle);
// TODO: Pass `options.mangle` to name expander.
// n.visit_mut_with(&mut name_expander());
}
if let Some(ref mut t) = timings {
t.section("compress");
}
if let Some(c) = &options.compress {
{
let _timer = timer!("compress ast");
n.mutate(&mut compressor(
marks,
c,
options.mangle.as_ref(),
&Minification,
))
}
// Again, we don't need to validate ast
let _timer = timer!("postcompress");
n.visit_mut_with(&mut postcompress_optimizer(c));
let mut pass = 0;
loop {
pass += 1;
let mut v = pure_optimizer(
c,
marks,
PureOptimizerConfig {
force_str_for_tpl: Minification.force_str_for_tpl(),
enable_join_vars: true,
#[cfg(feature = "debug")]
debug_infinite_loop: false,
},
);
n.visit_mut_with(&mut v);
if !v.changed() || c.passes <= pass {
break;
}
}
}
if let Some(ref mut _t) = timings {
// TODO: store `scope`
}
if options.mangle.is_some() {
// toplevel.figure_out_scope(options.mangle);
}
if let Some(ref mut t) = timings {
t.section("mangle");
}
if let Some(mangle) = &options.mangle {
let _timer = timer!("mangle names");
// TODO: base54.reset();
let preserved = idents_to_preserve(mangle, marks, &n);
let chars = CharFreq::compute(
&n,
&preserved,
SyntaxContext::empty().apply_mark(marks.unresolved_mark),
)
.compile();
mangle_names(
&mut n,
mangle,
preserved,
chars,
extra.top_level_mark,
extra.mangle_name_cache.clone(),
);
if let Some(property_mangle_options) = &mangle.props {
mangle_properties(&mut n, property_mangle_options.clone(), chars);
}
}
n.visit_mut_with(&mut merge_exports());
if let Some(ref mut t) = timings {
t.section("hygiene");
t.end_section();
}
n
}
fn perform_dce(m: &mut Program, options: &CompressOptions, extra: &ExtraOptions) {
let _timer = timer!("remove dead code");
let mut visitor = swc_ecma_transforms_optimization::simplify::dce::dce(
swc_ecma_transforms_optimization::simplify::dce::Config {
module_mark: None,
top_level: options.top_level(),
top_retain: options.top_retain.clone(),
preserve_imports_with_side_effects: true,
},
extra.unresolved_mark,
);
loop {
#[cfg(feature = "debug")]
let start = crate::debug::dump(&*m, false);
m.visit_mut_with(&mut visitor);
#[cfg(feature = "debug")]
if visitor.changed() {
let src = crate::debug::dump(&*m, false);
tracing::debug!(
"===== Before DCE =====\n{}\n===== After DCE =====\n{}",
start,
src
);
}
if !visitor.changed() {
break;
}
visitor.reset();
}
debug_assert_valid(&*m);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/macros.rs | Rust | /// Used when something is modified.
macro_rules! report_change {
($($tt:tt)+) => {{
#[cfg(feature = "debug")]
tracing::debug!(
kind = "change",
$($tt)*
);
}};
}
/// Used when a function decided to give up.
macro_rules! log_abort {
($($tt:tt)+) => {{
#[cfg(feature = "debug")]
{
tracing::trace!(
kind = "abort",
$($tt)*
);
}
}};
}
macro_rules! dump_change_detail {
($($tt:tt)+) => {{
#[cfg(feature = "debug")]
{
tracing::trace!(
kind = "detail",
$($tt)*
);
}
}};
}
macro_rules! trace_op {
($($tt:tt)+) => {{
#[cfg(feature = "debug")]
{
tracing::trace!(
$($tt)*
);
}
}};
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/metadata/mod.rs | Rust | use rustc_hash::FxHashSet;
use swc_common::{
comments::{Comment, CommentKind, Comments},
Span, Spanned,
};
use swc_ecma_ast::*;
use swc_ecma_usage_analyzer::marks::Marks;
use swc_ecma_utils::NodeIgnoringSpan;
use swc_ecma_visit::{
noop_visit_mut_type, noop_visit_type, Visit, VisitMut, VisitMutWith, VisitWith,
};
use crate::option::CompressOptions;
#[cfg(test)]
mod tests;
/// This pass analyzes the comment and convert it to a mark.
pub(crate) fn info_marker<'a>(
options: Option<&'a CompressOptions>,
comments: Option<&'a dyn Comments>,
marks: Marks,
// unresolved_mark: Mark,
) -> impl 'a + VisitMut {
let pure_funcs = options.map(|options| {
options
.pure_funcs
.iter()
.map(|f| NodeIgnoringSpan::borrowed(f.as_ref()))
.collect()
});
InfoMarker {
options,
comments,
marks,
pure_funcs,
// unresolved_mark,
state: Default::default(),
pure_callee: Default::default(),
}
}
#[derive(Default)]
struct State {
is_in_export: bool,
}
struct InfoMarker<'a> {
#[allow(dead_code)]
options: Option<&'a CompressOptions>,
pure_funcs: Option<FxHashSet<NodeIgnoringSpan<'a, Expr>>>,
pure_callee: FxHashSet<Id>,
comments: Option<&'a dyn Comments>,
marks: Marks,
// unresolved_mark: Mark,
state: State,
}
impl InfoMarker<'_> {
fn is_pure_callee(&self, callee: &Expr) -> bool {
match callee {
Expr::Ident(callee) => {
if self.pure_callee.contains(&callee.to_id()) {
return true;
}
}
Expr::Seq(callee) => {
if has_pure(self.comments, callee.span) {
return true;
}
}
_ => (),
}
if let Some(pure_fns) = &self.pure_funcs {
if let Expr::Ident(..) = callee {
// Check for pure_funcs
if Ident::within_ignored_ctxt(|| {
//
pure_fns.contains(&NodeIgnoringSpan::borrowed(callee))
}) {
return true;
}
}
}
has_pure(self.comments, callee.span())
}
}
impl VisitMut for InfoMarker<'_> {
noop_visit_mut_type!();
fn visit_mut_call_expr(&mut self, n: &mut CallExpr) {
n.visit_mut_children_with(self);
// TODO: remove after we figure out how to move comments properly
if has_noinline(self.comments, n.span)
|| match &n.callee {
Callee::Expr(e) => has_noinline(self.comments, e.span()),
_ => false,
}
{
n.ctxt = n.ctxt.apply_mark(self.marks.noinline);
}
// We check callee in some cases because we move comments
// See https://github.com/swc-project/swc/issues/7241
if match &n.callee {
Callee::Expr(e) => self.is_pure_callee(e),
_ => false,
} || has_pure(self.comments, n.span)
{
if !n.span.is_dummy_ignoring_cmt() {
n.ctxt = n.ctxt.apply_mark(self.marks.pure);
}
} else if let Some(pure_fns) = &self.pure_funcs {
if let Callee::Expr(e) = &n.callee {
// Check for pure_funcs
Ident::within_ignored_ctxt(|| {
if pure_fns.contains(&NodeIgnoringSpan::borrowed(e)) {
n.ctxt = n.ctxt.apply_mark(self.marks.pure);
};
})
}
}
}
fn visit_mut_export_default_decl(&mut self, e: &mut ExportDefaultDecl) {
self.state.is_in_export = true;
e.visit_mut_children_with(self);
self.state.is_in_export = false;
}
fn visit_mut_export_default_expr(&mut self, e: &mut ExportDefaultExpr) {
self.state.is_in_export = true;
e.visit_mut_children_with(self);
self.state.is_in_export = false;
}
fn visit_mut_fn_expr(&mut self, n: &mut FnExpr) {
n.visit_mut_children_with(self);
if !self.state.is_in_export
&& n.function
.params
.iter()
.any(|p| is_param_one_of(p, &["module", "__unused_webpack_module"]))
&& n.function.params.iter().any(|p| {
is_param_one_of(
p,
&[
"exports",
"__webpack_require__",
"__webpack_exports__",
"__unused_webpack_exports",
],
)
})
{
// if is_standalone(&mut n.function, self.unresolved_mark) {
// // self.state.is_bundle = true;
// // n.function.span =
// // n.function.span.apply_mark(self.marks.standalone);
// }
}
}
fn visit_mut_ident(&mut self, _: &mut Ident) {}
fn visit_mut_lit(&mut self, _: &mut Lit) {}
fn visit_mut_module(&mut self, n: &mut Module) {
n.visit_with(&mut InfoCollector {
comments: self.comments,
pure_callees: &mut self.pure_callee,
});
n.visit_mut_children_with(self);
}
fn visit_mut_new_expr(&mut self, n: &mut NewExpr) {
n.visit_mut_children_with(self);
if has_pure(self.comments, n.span) {
n.ctxt = n.ctxt.apply_mark(self.marks.pure);
}
}
fn visit_mut_script(&mut self, n: &mut Script) {
n.visit_with(&mut InfoCollector {
comments: self.comments,
pure_callees: &mut self.pure_callee,
});
n.visit_mut_children_with(self);
}
fn visit_mut_tagged_tpl(&mut self, n: &mut TaggedTpl) {
n.visit_mut_children_with(self);
if has_pure(self.comments, n.span) || self.is_pure_callee(&n.tag) {
if !n.span.is_dummy_ignoring_cmt() {
n.ctxt = n.ctxt.apply_mark(self.marks.pure);
}
}
}
fn visit_mut_var_decl(&mut self, n: &mut VarDecl) {
n.visit_mut_children_with(self);
if has_const_ann(self.comments, n.span) {
n.ctxt = n.ctxt.apply_mark(self.marks.const_ann);
}
}
}
fn is_param_one_of(p: &Param, allowed: &[&str]) -> bool {
match &p.pat {
Pat::Ident(i) => allowed.contains(&&*i.id.sym),
_ => false,
}
}
const NO_SIDE_EFFECTS_FLAG: &str = "NO_SIDE_EFFECTS";
struct InfoCollector<'a> {
comments: Option<&'a dyn Comments>,
pure_callees: &'a mut FxHashSet<Id>,
}
impl Visit for InfoCollector<'_> {
noop_visit_type!();
fn visit_export_decl(&mut self, f: &ExportDecl) {
f.visit_children_with(self);
if let Decl::Fn(f) = &f.decl {
if has_flag(self.comments, f.function.span, NO_SIDE_EFFECTS_FLAG) {
self.pure_callees.insert(f.ident.to_id());
}
}
}
fn visit_fn_decl(&mut self, f: &FnDecl) {
f.visit_children_with(self);
if has_flag(self.comments, f.function.span, NO_SIDE_EFFECTS_FLAG) {
self.pure_callees.insert(f.ident.to_id());
}
}
fn visit_fn_expr(&mut self, f: &FnExpr) {
f.visit_children_with(self);
if let Some(ident) = &f.ident {
if has_flag(self.comments, f.function.span, NO_SIDE_EFFECTS_FLAG) {
self.pure_callees.insert(ident.to_id());
}
}
}
fn visit_var_decl(&mut self, decl: &VarDecl) {
decl.visit_children_with(self);
for v in &decl.decls {
if let Pat::Ident(ident) = &v.name {
if let Some(init) = &v.init {
if has_flag(self.comments, decl.span, NO_SIDE_EFFECTS_FLAG)
|| has_flag(self.comments, v.span, NO_SIDE_EFFECTS_FLAG)
|| has_flag(self.comments, init.span(), NO_SIDE_EFFECTS_FLAG)
{
self.pure_callees.insert(ident.to_id());
}
}
}
}
}
}
/// Check for `/** @const */`.
pub(super) fn has_const_ann(comments: Option<&dyn Comments>, span: Span) -> bool {
find_comment(comments, span, |c| {
if c.kind == CommentKind::Block {
if !c.text.starts_with('*') {
return false;
}
let t = c.text[1..].trim();
//
if t.starts_with("@const") {
return true;
}
}
false
})
}
/// Check for `/*#__NOINLINE__*/`
pub(super) fn has_noinline(comments: Option<&dyn Comments>, span: Span) -> bool {
has_flag(comments, span, "NOINLINE")
}
/// Check for `/*#__PURE__*/`
pub(super) fn has_pure(comments: Option<&dyn Comments>, span: Span) -> bool {
span.is_pure() || has_flag(comments, span, "PURE")
}
fn find_comment<F>(comments: Option<&dyn Comments>, span: Span, mut op: F) -> bool
where
F: FnMut(&Comment) -> bool,
{
let mut found = false;
if let Some(comments) = comments {
let cs = comments.get_leading(span.lo);
if let Some(cs) = cs {
for c in &cs {
found |= op(c);
if found {
break;
}
}
}
}
found
}
fn has_flag(comments: Option<&dyn Comments>, span: Span, text: &'static str) -> bool {
if span.is_dummy_ignoring_cmt() {
return false;
}
comments.has_flag(span.lo, text)
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/metadata/tests.rs | Rust | // use swc_common::{input::SourceFileInput, FileName, Mark, Span, DUMMY_SP};
// use swc_ecma_ast::*;
// use swc_ecma_parser::{lexer::Lexer, Parser};
// use swc_ecma_transforms::resolver_with_mark;
// use swc_ecma_visit::{Node, Visit, VisitMutWith, VisitWith};
// use crate::marks::Marks;
// use super::info_marker;
// fn assert_standalone(src: &str, expected: usize) {
// testing::run_test(false, |cm, _handler| {
// let marks = Marks::new();
// let top_level_mark = Mark::fresh(Mark::root());
// let fm = cm.new_source_file(FileName::Anon, src.to_string());
// let lexer = Lexer::new(
// Default::default(),
// EsVersion::latest(),
// SourceFileInput::from(&*fm),
// None,
// );
// let mut parser = Parser::new_from(lexer);
// let mut m = parser.parse_module().expect("failed to parse");
// m.visit_mut_with(&mut resolver_with_mark(top_level_mark));
// m.visit_mut_with(&mut info_marker(None, marks, top_level_mark));
// eprintln!("Expected: {} modules in bundle", expected);
// let actual = {
// let mut counter = MarkCounter {
// mark: marks.standalone,
// count: 0,
// };
// m.visit_with( &mut counter);
// counter.count
// };
// eprintln!("Actual: {} modules in bundle", actual);
// assert_eq!(expected, actual);
// if expected != 0 {
// assert!(
// m.span.has_mark(marks.bundle_of_standalones),
// "Expected module to be marked as a bundle"
// );
// } else {
// assert!(
// !m.span.has_mark(marks.bundle_of_standalones),
// "Expected module to be not marked as a bundle"
// );
// }
// Ok(())
// })
// .unwrap();
// }
// struct MarkCounter {
// mark: Mark,
// count: usize,
// }
// impl Visit for MarkCounter {
// fn visit_span(&mut self, span: &Span) {
// if span.has_mark(self.mark) {
// self.count += 1;
// }
// }
// }
// #[test]
// fn standalone_base() {
// assert_standalone("function foo() {}", 0);
// }
// #[test]
// fn standalone_no_usage() {
// assert_standalone(
// "function foo() {
// declare(function (module, exports) {
// }, function (module, exports) {
// });
// }",
// 2,
// );
// }
// #[test]
// fn usage_of_var_1() {
// assert_standalone(
// "function foo() {
// var bar = 2;
// declare(function (module, exports) {
// bar = 1;
// }, function (module, exports) {
// });
// }",
// 1,
// );
// }
// #[test]
// fn usage_of_class_1() {
// assert_standalone(
// "function foo() {
// class Foo {
// }
// declare(function (module, exports) {
// const bar = new Foo();
// }, function (module, exports) {
// });
// }",
// 1,
// );
// }
// #[test]
// fn usage_of_fn_1() {
// assert_standalone(
// "function foo() {
// function bar() {
// }
// declare(function (module, exports) {
// const baz = new bar();
// }, function (module, exports) {
// });
// }",
// 1,
// );
// }
// #[test]
// fn usage_of_var_2() {
// assert_standalone(
// "var C = 1;
// var obj = {
// bar: function (module, exports) {
// return C + C;
// },
// };
// console.log(obj.bar());
// ",
// 0,
// );
// }
// #[test]
// fn export_default_fn_1() {
// assert_standalone("export default function f(module, exports) {}", 0);
// }
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/mode.rs | Rust | use swc_ecma_ast::*;
pub(crate) trait Mode: Send + Sync {
fn store(&self, id: Id, value: &Expr);
fn preserve_vars(&self) -> bool;
fn should_be_very_correct(&self) -> bool;
/// If this returns true, template literals with `\n` or `\r` will be
/// converted to [Lit::Str].
fn force_str_for_tpl(&self) -> bool;
}
pub struct Minification;
impl Mode for Minification {
fn store(&self, _: Id, _: &Expr) {}
fn preserve_vars(&self) -> bool {
false
}
fn should_be_very_correct(&self) -> bool {
true
}
fn force_str_for_tpl(&self) -> bool {
false
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/option/mod.rs | Rust | #![cfg_attr(not(feature = "extra-serde"), allow(unused))]
use std::sync::Arc;
use parking_lot::RwLock;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use swc_atoms::Atom;
use swc_common::Mark;
use swc_config::{merge::Merge, CachedRegex};
use swc_ecma_ast::{EsVersion, Expr, Id};
/// Implement default using serde.
macro_rules! impl_default {
($T:ty) => {
impl Default for $T {
fn default() -> Self {
serde_json::from_value(serde_json::Value::Object(Default::default())).unwrap()
}
}
};
}
pub mod terser;
/// This is not serializable.
pub struct ExtraOptions {
/// It should be the [Mark] used for `resolver`.
pub unresolved_mark: Mark,
/// It should be the [Mark] used for `resolver`.
pub top_level_mark: Mark,
pub mangle_name_cache: Option<Arc<dyn MangleCache>>,
}
#[derive(Debug, Default, Clone)]
#[cfg_attr(feature = "extra-serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "extra-serde", serde(rename_all = "camelCase"))]
#[cfg_attr(feature = "extra-serde", serde(deny_unknown_fields))]
pub struct MinifyOptions {
#[cfg_attr(feature = "extra-serde", serde(default))]
pub rename: bool,
#[cfg_attr(feature = "extra-serde", serde(default))]
pub compress: Option<CompressOptions>,
#[cfg_attr(feature = "extra-serde", serde(default))]
pub mangle: Option<MangleOptions>,
#[cfg_attr(feature = "extra-serde", serde(default))]
pub wrap: bool,
#[cfg_attr(feature = "extra-serde", serde(default))]
pub enclose: bool,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields)]
pub struct TopLevelOptions {
pub functions: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[serde(deny_unknown_fields)]
pub struct MangleOptions {
#[serde(default, alias = "properties")]
pub props: Option<ManglePropertiesOptions>,
#[serde(default, alias = "toplevel")]
pub top_level: Option<bool>,
#[serde(default, alias = "keep_classnames")]
pub keep_class_names: bool,
#[serde(default, alias = "keep_fnames")]
pub keep_fn_names: bool,
#[serde(default, alias = "keep_private_props")]
pub keep_private_props: bool,
#[serde(default, alias = "ie8")]
pub ie8: bool,
#[deprecated = "This field is no longer required to work around bugs in Safari 10."]
#[serde(default, alias = "safari10")]
pub safari10: bool,
#[serde(default, alias = "reserved")]
pub reserved: Vec<Atom>,
/// mangle names visible in scopes where eval or with are used
#[serde(default)]
pub eval: bool,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, Merge)]
#[serde(rename_all = "camelCase")]
pub struct ManglePropertiesOptions {
#[serde(default, alias = "reserved")]
pub reserved: Vec<Atom>,
#[serde(default, alias = "undeclared")]
pub undeclared: Option<bool>,
#[serde(default)]
pub regex: Option<CachedRegex>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(untagged)]
pub enum PureGetterOption {
Bool(bool),
#[serde(rename = "strict")]
Strict,
Str(Vec<Atom>),
}
impl Default for PureGetterOption {
fn default() -> Self {
Self::Strict
}
}
/// https://terser.org/docs/api-reference.html#compress-options
#[derive(Debug, Clone)]
#[cfg_attr(feature = "extra-serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "extra-serde", serde(rename_all = "camelCase"))]
#[cfg_attr(feature = "extra-serde", serde(deny_unknown_fields))]
pub struct CompressOptions {
#[cfg_attr(feature = "extra-serde", serde(default))]
#[cfg_attr(feature = "extra-serde", serde(alias = "arguments"))]
pub arguments: bool,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
pub arrows: bool,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "booleans"))]
pub bools: bool,
#[cfg_attr(feature = "extra-serde", serde(default))]
#[cfg_attr(feature = "extra-serde", serde(alias = "booleans_as_integers"))]
pub bools_as_ints: bool,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "collapse_vars"))]
pub collapse_vars: bool,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "comparisons"))]
pub comparisons: bool,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "computed_props"))]
pub computed_props: bool,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "conditionals"))]
pub conditionals: bool,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "dead_code"))]
pub dead_code: bool,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "directives"))]
pub directives: bool,
#[cfg_attr(feature = "extra-serde", serde(default))]
#[cfg_attr(feature = "extra-serde", serde(alias = "drop_console"))]
pub drop_console: bool,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "drop_debugger"))]
pub drop_debugger: bool,
#[cfg_attr(feature = "extra-serde", serde(default = "default_ecma"))]
pub ecma: EsVersion,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "evaluate"))]
pub evaluate: bool,
/// Should we simplify expressions?
#[cfg_attr(feature = "extra-serde", serde(default))]
#[cfg_attr(feature = "extra-serde", serde(alias = "expression"))]
pub expr: bool,
/// All expressions should have dummy span. Use [swc_ecma_utils::drop_span]
/// to remove spans.
#[cfg_attr(feature = "extra-serde", serde(skip))]
#[cfg_attr(feature = "extra-serde", serde(alias = "global_defs"))]
pub global_defs: FxHashMap<Box<Expr>, Box<Expr>>,
#[cfg_attr(feature = "extra-serde", serde(default))]
#[cfg_attr(feature = "extra-serde", serde(alias = "hoist_funs"))]
pub hoist_fns: bool,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "hoist_props"))]
pub hoist_props: bool,
#[cfg_attr(feature = "extra-serde", serde(default))]
#[cfg_attr(feature = "extra-serde", serde(alias = "hoist_vars"))]
pub hoist_vars: bool,
/// No effect.
#[cfg_attr(feature = "extra-serde", serde(default))]
#[cfg_attr(feature = "extra-serde", serde(alias = "ie8"))]
pub ie8: bool,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "if_return"))]
pub if_return: bool,
///
/// - `0`: disabled inlining
/// - `1`: inline simple functions
/// - `2`: inline functions with arguments
/// - `3`: inline functions with arguments and variables
#[cfg_attr(feature = "extra-serde", serde(default = "three_by_default"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "inline"))]
pub inline: u8,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "join_vars"))]
pub join_vars: bool,
#[cfg_attr(feature = "extra-serde", serde(default))]
#[cfg_attr(feature = "extra-serde", serde(alias = "keep_classnames"))]
pub keep_classnames: bool,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "keep_fargs"))]
pub keep_fargs: bool,
#[cfg_attr(feature = "extra-serde", serde(default))]
#[cfg_attr(feature = "extra-serde", serde(alias = "keep_fnames"))]
pub keep_fnames: bool,
#[cfg_attr(feature = "extra-serde", serde(default))]
#[cfg_attr(feature = "extra-serde", serde(alias = "keep_infinity"))]
pub keep_infinity: bool,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "loops"))]
pub loops: bool,
#[cfg_attr(feature = "extra-serde", serde(default))]
pub module: bool,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "negate_iife"))]
pub negate_iife: bool,
/// If this value is zero, the minifier will repeat work until the ast node
/// is settled.
#[cfg_attr(feature = "extra-serde", serde(default = "default_passes"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "passes"))]
pub passes: usize,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "properties"))]
pub props: bool,
#[cfg_attr(feature = "extra-serde", serde(default))]
#[cfg_attr(feature = "extra-serde", serde(alias = "pure_getters"))]
pub pure_getters: PureGetterOption,
#[cfg_attr(feature = "extra-serde", serde(default))]
#[cfg_attr(feature = "extra-serde", serde(alias = "pure_funcs"))]
pub pure_funcs: Vec<Box<Expr>>,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "reduce_funcs"))]
pub reduce_fns: bool,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "reduce_vars"))]
pub reduce_vars: bool,
#[cfg_attr(feature = "extra-serde", serde(default = "three_by_default"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "sequences"))]
pub sequences: u8,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "side_effects"))]
pub side_effects: bool,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "switches"))]
pub switches: bool,
/// Top level symbols to retain.
#[cfg_attr(feature = "extra-serde", serde(default))]
#[cfg_attr(feature = "extra-serde", serde(alias = "top_retain"))]
pub top_retain: Vec<Atom>,
#[cfg_attr(feature = "extra-serde", serde(default))]
#[cfg_attr(feature = "extra-serde", serde(alias = "toplevel"))]
pub top_level: Option<TopLevelOptions>,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
#[cfg_attr(feature = "extra-serde", serde(alias = "typeofs"))]
pub typeofs: bool,
#[cfg_attr(feature = "extra-serde", serde(default))]
#[cfg_attr(feature = "extra-serde", serde(rename = "unsafe"))]
pub unsafe_passes: bool,
#[cfg_attr(feature = "extra-serde", serde(default))]
pub unsafe_arrows: bool,
#[cfg_attr(feature = "extra-serde", serde(default))]
pub unsafe_comps: bool,
#[cfg_attr(feature = "extra-serde", serde(default))]
#[cfg_attr(feature = "extra-serde", serde(alias = "unsafe_Function"))]
pub unsafe_function: bool,
#[cfg_attr(feature = "extra-serde", serde(default))]
pub unsafe_math: bool,
#[cfg_attr(feature = "extra-serde", serde(default))]
pub unsafe_symbols: bool,
#[cfg_attr(feature = "extra-serde", serde(default))]
pub unsafe_methods: bool,
#[cfg_attr(feature = "extra-serde", serde(default))]
pub unsafe_proto: bool,
#[cfg_attr(feature = "extra-serde", serde(default))]
pub unsafe_regexp: bool,
#[cfg_attr(feature = "extra-serde", serde(default))]
pub unsafe_undefined: bool,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
pub unused: bool,
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
pub const_to_let: bool,
/// If you modified globals, set this to false.
///
/// Defaults to true.
#[cfg_attr(feature = "extra-serde", serde(default = "true_by_default"))]
pub pristine_globals: bool,
}
impl CompressOptions {
pub(crate) fn sequences(&self) -> bool {
self.sequences != 0
}
/// Returns `true` if any of toplevel optimizer is enabled.
pub(crate) fn top_level(&self) -> bool {
if !self.top_retain.is_empty() {
return true;
}
self.top_level.map(|v| v.functions).unwrap_or(false) || self.module
}
}
const fn true_by_default() -> bool {
true
}
const fn default_passes() -> usize {
2
}
const fn three_by_default() -> u8 {
3
}
const fn default_ecma() -> EsVersion {
EsVersion::Es5
}
impl_default!(MangleOptions);
impl Default for CompressOptions {
fn default() -> Self {
Self {
arguments: false,
arrows: true,
bools: true,
bools_as_ints: false,
collapse_vars: true,
comparisons: true,
computed_props: true,
conditionals: true,
dead_code: true,
directives: true,
drop_console: false,
drop_debugger: true,
ecma: default_ecma(),
evaluate: true,
expr: false,
global_defs: Default::default(),
hoist_fns: false,
hoist_props: true,
hoist_vars: false,
ie8: false,
if_return: true,
inline: 3,
join_vars: true,
keep_classnames: false,
keep_fargs: true,
keep_fnames: false,
keep_infinity: false,
loops: true,
module: false,
negate_iife: true,
passes: default_passes(),
props: true,
pure_getters: Default::default(),
pure_funcs: Default::default(),
reduce_fns: true,
reduce_vars: false,
sequences: 3,
side_effects: true,
switches: true,
top_retain: Default::default(),
top_level: Default::default(),
typeofs: true,
unsafe_passes: false,
unsafe_arrows: false,
unsafe_comps: false,
unsafe_function: false,
unsafe_math: false,
unsafe_methods: false,
unsafe_proto: false,
unsafe_regexp: false,
unsafe_symbols: false,
unsafe_undefined: false,
unused: true,
const_to_let: true,
pristine_globals: true,
}
}
}
pub trait MangleCache: Send + Sync {
fn vars_cache(&self, op: &mut dyn FnMut(&FxHashMap<Id, Atom>));
fn props_cache(&self, op: &mut dyn FnMut(&FxHashMap<Atom, Atom>));
fn update_vars_cache(&self, new_data: &FxHashMap<Id, Atom>);
fn update_props_cache(&self, new_data: &FxHashMap<Atom, Atom>);
}
#[derive(Debug, Default)]
pub struct SimpleMangleCache {
pub vars: RwLock<FxHashMap<Id, Atom>>,
pub props: RwLock<FxHashMap<Atom, Atom>>,
}
impl MangleCache for SimpleMangleCache {
fn vars_cache(&self, op: &mut dyn FnMut(&FxHashMap<Id, Atom>)) {
let vars = self.vars.read();
op(&vars);
}
fn props_cache(&self, op: &mut dyn FnMut(&FxHashMap<Atom, Atom>)) {
let props = self.props.read();
op(&props);
}
fn update_vars_cache(&self, new_data: &FxHashMap<Id, Atom>) {
let mut vars = self.vars.write();
vars.extend(new_data.iter().map(|(k, v)| (k.clone(), v.clone())));
}
fn update_props_cache(&self, new_data: &FxHashMap<Atom, Atom>) {
let mut props = self.props.write();
props.extend(new_data.iter().map(|(k, v)| (k.clone(), v.clone())));
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/option/terser.rs | Rust | //! Compatibility for terser config.
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use swc_atoms::Atom;
use swc_common::{sync::Lrc, FileName, SourceMap, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_parser::parse_file_as_expr;
use swc_ecma_utils::drop_span;
use super::{default_passes, true_by_default, CompressOptions, TopLevelOptions};
use crate::option::PureGetterOption;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(untagged)]
pub enum TerserEcmaVersion {
Num(usize),
Str(String),
}
impl Default for TerserEcmaVersion {
fn default() -> Self {
Self::Num(5)
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(deny_unknown_fields)]
#[serde(untagged)]
pub enum TerserPureGetterOption {
Bool(bool),
#[serde(rename = "strict")]
#[default]
Strict,
Str(String),
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(untagged)]
pub enum TerserInlineOption {
Bool(bool),
Num(u8),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(untagged)]
pub enum TerserTopLevelOptions {
Bool(bool),
Str(String),
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(untagged)]
pub enum TerserSequenceOptions {
Bool(bool),
Num(u8),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(untagged)]
pub enum TerserTopRetainOption {
Str(String),
Seq(Vec<Atom>),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TerserCompressorOptions {
#[serde(default)]
pub arguments: bool,
#[serde(default)]
pub arrows: Option<bool>,
#[serde(default)]
pub booleans: Option<bool>,
#[serde(default)]
pub booleans_as_integers: bool,
#[serde(default)]
pub collapse_vars: Option<bool>,
#[serde(default)]
pub comparisons: Option<bool>,
#[serde(default)]
pub computed_props: Option<bool>,
#[serde(default)]
pub conditionals: Option<bool>,
#[serde(default)]
pub dead_code: Option<bool>,
#[serde(default = "true_by_default")]
pub defaults: bool,
#[serde(default)]
pub directives: Option<bool>,
#[serde(default)]
pub drop_console: bool,
#[serde(default)]
pub drop_debugger: Option<bool>,
#[serde(default)]
pub ecma: TerserEcmaVersion,
#[serde(default)]
pub evaluate: Option<bool>,
#[serde(default)]
pub expression: bool,
#[serde(default)]
pub global_defs: FxHashMap<Atom, Value>,
#[serde(default)]
pub hoist_funs: bool,
#[serde(default)]
pub hoist_props: Option<bool>,
#[serde(default)]
pub hoist_vars: bool,
#[serde(default)]
pub ie8: bool,
#[serde(default)]
pub if_return: Option<bool>,
#[serde(default)]
pub inline: Option<TerserInlineOption>,
#[serde(default)]
pub join_vars: Option<bool>,
#[serde(default)]
pub keep_classnames: bool,
#[serde(default = "true_by_default")]
pub keep_fargs: bool,
#[serde(default)]
pub keep_fnames: bool,
#[serde(default)]
pub keep_infinity: bool,
#[serde(default)]
pub loops: Option<bool>,
// module : false,
#[serde(default)]
pub negate_iife: Option<bool>,
#[serde(default = "default_passes")]
pub passes: usize,
#[serde(default)]
pub properties: Option<bool>,
#[serde(default)]
pub pure_getters: TerserPureGetterOption,
#[serde(default)]
pub pure_funcs: Vec<String>,
#[serde(default)]
pub reduce_funcs: Option<bool>,
#[serde(default)]
pub reduce_vars: Option<bool>,
#[serde(default)]
pub sequences: Option<TerserSequenceOptions>,
#[serde(default)]
pub side_effects: Option<bool>,
#[serde(default)]
pub switches: Option<bool>,
#[serde(default)]
pub top_retain: Option<TerserTopRetainOption>,
#[serde(default)]
pub toplevel: Option<TerserTopLevelOptions>,
#[serde(default)]
pub typeofs: Option<bool>,
#[serde(default)]
#[serde(rename = "unsafe")]
pub unsafe_passes: bool,
#[serde(default)]
pub unsafe_arrows: bool,
#[serde(default)]
pub unsafe_comps: bool,
#[serde(default)]
#[serde(rename = "unsafe_Function")]
pub unsafe_function: bool,
#[serde(default)]
pub unsafe_math: bool,
#[serde(default)]
pub unsafe_symbols: bool,
#[serde(default)]
pub unsafe_methods: bool,
#[serde(default)]
pub unsafe_proto: bool,
#[serde(default)]
pub unsafe_regexp: bool,
#[serde(default)]
pub unsafe_undefined: bool,
#[serde(default)]
pub unused: Option<bool>,
#[serde(default)]
pub module: bool,
#[serde(default)]
pub const_to_let: Option<bool>,
#[serde(default)]
pub pristine_globals: Option<bool>,
}
impl_default!(TerserCompressorOptions);
impl TerserCompressorOptions {
pub fn into_config(self, cm: Lrc<SourceMap>) -> CompressOptions {
CompressOptions {
arguments: self.arguments,
arrows: self.arrows.unwrap_or(self.defaults),
bools: self.booleans.unwrap_or(self.defaults),
bools_as_ints: self.booleans_as_integers,
collapse_vars: self.collapse_vars.unwrap_or(self.defaults),
comparisons: self.comparisons.unwrap_or(self.defaults),
computed_props: self.computed_props.unwrap_or(self.defaults),
conditionals: self.conditionals.unwrap_or(self.defaults),
dead_code: self.dead_code.unwrap_or(self.defaults),
directives: self.directives.unwrap_or(self.defaults),
drop_console: self.drop_console,
drop_debugger: self.drop_debugger.unwrap_or(self.defaults),
ecma: self.ecma.into(),
evaluate: self.evaluate.unwrap_or(self.defaults),
expr: self.expression,
global_defs: self
.global_defs
.into_iter()
.map(|(k, v)| {
let parse = |input: String| {
let fm = cm.new_source_file(FileName::Anon.into(), input);
parse_file_as_expr(
&fm,
Default::default(),
Default::default(),
None,
&mut Vec::new(),
)
.map(drop_span)
.unwrap_or_else(|err| {
panic!(
"failed to parse `global_defs.{}` of minifier options: {:?}",
k, err
)
})
};
let key = parse(if let Some(k) = k.strip_prefix('@') {
k.to_string()
} else {
k.to_string()
});
(
key,
if k.starts_with('@') {
parse(
v.as_str()
.unwrap_or_else(|| {
panic!(
"Value of `global_defs.{}` must be a string literal: ",
k
)
})
.into(),
)
} else {
value_to_expr(v)
},
)
})
.collect(),
hoist_fns: self.hoist_funs,
hoist_props: self.hoist_props.unwrap_or(self.defaults),
hoist_vars: self.hoist_vars,
ie8: self.ie8,
if_return: self.if_return.unwrap_or(self.defaults),
inline: self
.inline
.map(|v| match v {
TerserInlineOption::Bool(v) => {
if v {
3
} else {
0
}
}
TerserInlineOption::Num(n) => n,
})
.unwrap_or(if self.defaults { 3 } else { 0 }),
join_vars: self.join_vars.unwrap_or(self.defaults),
keep_classnames: self.keep_classnames,
keep_fargs: self.keep_fargs,
keep_fnames: self.keep_fnames,
keep_infinity: self.keep_infinity,
loops: self.loops.unwrap_or(self.defaults),
module: self.module,
negate_iife: self.negate_iife.unwrap_or(self.defaults),
passes: self.passes,
props: self.properties.unwrap_or(self.defaults),
pure_getters: match self.pure_getters {
TerserPureGetterOption::Bool(v) => PureGetterOption::Bool(v),
TerserPureGetterOption::Strict => PureGetterOption::Strict,
TerserPureGetterOption::Str(v) => {
PureGetterOption::Str(v.split(',').map(From::from).collect())
}
},
reduce_fns: self.reduce_funcs.unwrap_or(self.defaults),
reduce_vars: self.reduce_vars.unwrap_or(self.defaults),
sequences: self
.sequences
.map(|v| match v {
TerserSequenceOptions::Bool(v) => {
if v {
3
} else {
0
}
}
TerserSequenceOptions::Num(v) => v,
})
.unwrap_or(if self.defaults { 3 } else { 0 }),
side_effects: self.side_effects.unwrap_or(self.defaults),
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),
unsafe_passes: self.unsafe_passes,
unsafe_arrows: self.unsafe_arrows,
unsafe_comps: self.unsafe_comps,
unsafe_function: self.unsafe_function,
unsafe_math: self.unsafe_math,
unsafe_symbols: self.unsafe_symbols,
unsafe_methods: self.unsafe_methods,
unsafe_proto: self.unsafe_proto,
unsafe_regexp: self.unsafe_regexp,
unsafe_undefined: self.unsafe_undefined,
unused: self.unused.unwrap_or(self.defaults),
const_to_let: self.const_to_let.unwrap_or(self.defaults),
pristine_globals: self.pristine_globals.unwrap_or(self.defaults),
pure_funcs: self
.pure_funcs
.into_iter()
.map(|input| {
let fm = cm.new_source_file(FileName::Anon.into(), input);
parse_file_as_expr(
&fm,
Default::default(),
Default::default(),
None,
&mut Vec::new(),
)
.map(drop_span)
.unwrap_or_else(|err| {
panic!(
"failed to parse `pure_funcs` of minifier options: {:?}",
err
)
})
})
.collect(),
}
}
}
impl From<TerserTopLevelOptions> for TopLevelOptions {
fn from(c: TerserTopLevelOptions) -> Self {
match c {
TerserTopLevelOptions::Bool(v) => TopLevelOptions { functions: v },
TerserTopLevelOptions::Str(..) => {
// TODO
TopLevelOptions { functions: false }
}
}
}
}
impl From<TerserEcmaVersion> for EsVersion {
fn from(v: TerserEcmaVersion) -> Self {
match v {
TerserEcmaVersion::Num(v) => match v {
3 => EsVersion::Es3,
5 => EsVersion::Es5,
6 | 2015 => EsVersion::Es2015,
2016 => EsVersion::Es2016,
2017 => EsVersion::Es2017,
2018 => EsVersion::Es2018,
2019 => EsVersion::Es2019,
2020 => EsVersion::Es2020,
2021 => EsVersion::Es2021,
2022 => EsVersion::Es2022,
_ => {
panic!("`{}` is not a valid ecmascript version", v)
}
},
TerserEcmaVersion::Str(v) => {
TerserEcmaVersion::Num(v.parse().expect("failed to parse version of ecmascript"))
.into()
}
}
}
}
impl From<TerserTopRetainOption> for Vec<Atom> {
fn from(v: TerserTopRetainOption) -> Self {
match v {
TerserTopRetainOption::Str(s) => s
.split(',')
.filter(|s| s.trim() != "")
.map(|v| v.into())
.collect(),
TerserTopRetainOption::Seq(v) => v,
}
}
}
fn value_to_expr(v: Value) -> Box<Expr> {
match v {
Value::Null => Lit::Null(Null { span: DUMMY_SP }).into(),
Value::Bool(value) => Lit::Bool(Bool {
span: DUMMY_SP,
value,
})
.into(),
Value::Number(v) => {
trace_op!("Creating a numeric literal from value");
Lit::Num(Number {
span: DUMMY_SP,
value: v.as_f64().unwrap(),
raw: None,
})
.into()
}
Value::String(v) => {
let value: Atom = v.into();
Lit::Str(Str {
span: DUMMY_SP,
raw: None,
value,
})
.into()
}
Value::Array(arr) => {
let elems = arr
.into_iter()
.map(value_to_expr)
.map(|expr| Some(ExprOrSpread { spread: None, expr }))
.collect();
ArrayLit {
span: DUMMY_SP,
elems,
}
.into()
}
Value::Object(obj) => {
let props = obj
.into_iter()
.map(|(k, v)| (k, value_to_expr(v)))
.map(|(key, value)| KeyValueProp {
key: PropName::Str(Str {
span: DUMMY_SP,
raw: None,
value: key.into(),
}),
value,
})
.map(Prop::KeyValue)
.map(Box::new)
.map(PropOrSpread::Prop)
.collect();
ObjectLit {
span: DUMMY_SP,
props,
}
.into()
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/pass/global_defs.rs | Rust | use std::borrow::Cow;
use swc_common::{pass::CompilerPass, EqIgnoreSpan, Mark, SyntaxContext};
use swc_ecma_ast::*;
use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith};
pub fn globals_defs(
defs: Vec<(Box<Expr>, Box<Expr>)>,
unresolved_mark: Mark,
top_level_mark: Mark,
) -> impl VisitMut {
GlobalDefs {
defs,
unresolved_ctxt: SyntaxContext::empty().apply_mark(unresolved_mark),
top_level_ctxt: SyntaxContext::empty().apply_mark(top_level_mark),
..Default::default()
}
}
#[derive(Default)]
struct GlobalDefs {
defs: Vec<(Box<Expr>, Box<Expr>)>,
unresolved_ctxt: SyntaxContext,
top_level_ctxt: SyntaxContext,
in_lhs_of_assign: bool,
}
impl CompilerPass for GlobalDefs {
fn name(&self) -> Cow<'static, str> {
Cow::Borrowed("global-defs")
}
}
/// We use [VisitMut] instead of [swc_ecma_visit::Fold] because it's faster.
impl VisitMut for GlobalDefs {
noop_visit_mut_type!();
fn visit_mut_assign_expr(&mut self, n: &mut AssignExpr) {
let old = self.in_lhs_of_assign;
self.in_lhs_of_assign = true;
n.left.visit_mut_with(self);
self.in_lhs_of_assign = false;
n.right.visit_mut_with(self);
self.in_lhs_of_assign = old;
}
fn visit_mut_expr(&mut self, n: &mut Expr) {
if self.in_lhs_of_assign {
return;
}
match n {
Expr::Ident(i) => {
if i.ctxt != self.unresolved_ctxt && i.ctxt != self.top_level_ctxt {
return;
}
}
Expr::Member(MemberExpr { obj, .. }) => {
if let Expr::Ident(i) = &**obj {
if i.ctxt != self.unresolved_ctxt && i.ctxt != self.top_level_ctxt {
return;
}
}
}
_ => {}
}
if let Some((_, new)) = self
.defs
.iter()
.find(|(pred, _)| Ident::within_ignored_ctxt(|| should_replace(pred, n)))
{
*n = *new.clone();
return;
}
n.visit_mut_children_with(self);
}
fn visit_mut_update_expr(&mut self, e: &mut UpdateExpr) {
match &mut *e.arg {
Expr::Ident(..) => {}
Expr::Member(MemberExpr { prop, .. }) if !prop.is_computed() => {
// TODO: Check for `obj`
}
_ => {
e.arg.visit_mut_with(self);
}
}
}
}
/// This is used to detect optional chaining expressions like `a?.b.c` without
/// allocation.
fn should_replace(pred: &Expr, node: &Expr) -> bool {
if pred.eq_ignore_span(node) {
return true;
}
fn match_node(node: &Expr) -> Option<(&Expr, &MemberProp)> {
match node {
Expr::Member(MemberExpr {
obj: node_obj,
prop: nodes,
..
}) => Some((node_obj, nodes)),
Expr::OptChain(OptChainExpr { base, .. }) => {
let base = base.as_member()?;
Some((&base.obj, &base.prop))
}
_ => None,
}
}
match (pred, match_node(node)) {
// super?. is invalid
(
Expr::Member(MemberExpr {
obj: pred_obj,
prop: pred,
..
}),
Some((node_obj, nodes)),
) if !(pred.is_computed() || nodes.is_computed()) => {
if !pred.eq_ignore_span(nodes) {
return false;
}
return should_replace(pred_obj, node_obj);
}
_ => {}
}
false
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/pass/hygiene/vars.rs | Rust | use std::cell::RefCell;
use fxhash::{FxHashMap, FxHashSet};
use swc_atoms::Atom;
use swc_common::{SyntaxContext, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_visit::{noop_visit_type, Node, Visit, VisitWith};
#[derive(Default)]
pub(super) struct All {
pub scopes: FxHashMap<SyntaxContext, VarHygieneData>,
}
pub(super) fn analyze<N>(node: &N) -> All
where
N: for<'aa> VisitWith<VarAnalyzer<'aa>>,
{
let mut data = All::default();
let mut v = VarAnalyzer {
all: &mut data,
cur: Default::default(),
};
node.visit_with(&mut v);
data
}
#[derive(Debug, Default)]
pub(super) struct VarHygieneData {
pub decls: FxHashMap<Atom, FxHashSet<SyntaxContext>>,
}
#[derive(Default)]
struct Scope<'a> {
parent: Option<&'a Scope<'a>>,
data: RefCell<VarHygieneData>,
}
impl<'a> Scope<'a> {
pub fn new(parent: Option<&'a Scope<'a>>) -> Self {
Scope {
parent,
data: Default::default(),
}
}
/// Add usage or declaration of a variable
fn add(&mut self, i: &Ident) {
let mut cur = Some(&*self);
while let Some(scope) = cur {
let mut w = scope.data.borrow_mut();
w.decls.entry(i.sym.clone()).or_default().insert(i.ctxt);
cur = scope.parent;
}
}
}
pub struct VarAnalyzer<'a> {
all: &'a mut All,
cur: Scope<'a>,
}
macro_rules! scoped {
($v:expr, $n:expr) => {
let data = {
let child = Scope::new(Some(&$v.cur));
let mut v = VarAnalyzer {
all: &mut $v.all,
cur: child,
};
$n.visit_children_with(&mut v);
v.cur.data.into_inner()
};
let old = $v.all.scopes.insert($n.ctxt, data);
debug_assert!(old.is_none(), "{:?}", $n.ctxt);
};
}
impl Visit for VarAnalyzer<'_> {
noop_visit_type!();
fn visit_arrow_expr(&mut self, n: &ArrowExpr) {
scoped!(self, n);
}
fn visit_block_stmt(&mut self, n: &BlockStmt) {
scoped!(self, n);
}
fn visit_function(&mut self, n: &Function) {
scoped!(self, n);
}
fn visit_ident(&mut self, i: &Ident) {
trace!("hygiene/vars: Found {}", i);
self.cur.add(i);
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/pass/mangle_names/mod.rs | Rust | use std::{borrow::Cow, sync::Arc};
use rustc_hash::{FxHashMap, FxHashSet};
use swc_atoms::Atom;
use swc_common::Mark;
use swc_ecma_ast::*;
use swc_ecma_transforms_base::rename::{renamer, RenameMap, Renamer};
use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith};
pub(crate) use self::preserver::idents_to_preserve;
use crate::{
option::{MangleCache, MangleOptions},
util::base54::Base54Chars,
};
mod preserver;
mod private_name;
pub(crate) fn mangle_names(
program: &mut Program,
options: &MangleOptions,
preserved: FxHashSet<Id>,
chars: Base54Chars,
top_level_mark: Mark,
mangle_name_cache: Option<Arc<dyn MangleCache>>,
) {
program.visit_mut_with(&mut LabelMangler {
chars,
cache: Default::default(),
n: Default::default(),
});
program.visit_mut_with(&mut self::private_name::private_name_mangler(
options.keep_private_props,
chars,
));
let mut cache = None;
if let Some(mangle_cache) = &mangle_name_cache {
let mut c = RenameMap::default();
mangle_cache.vars_cache(&mut |v| c.extend(v.iter().map(|(k, v)| (k.clone(), v.clone()))));
cache = Some(c);
}
program.visit_mut_with(&mut renamer(
swc_ecma_transforms_base::hygiene::Config {
keep_class_names: options.keep_class_names,
top_level_mark,
ignore_eval: options.eval,
preserved_symbols: options.reserved.iter().cloned().collect(),
},
ManglingRenamer {
chars,
preserved,
cache,
mangle_name_cache,
},
));
}
struct ManglingRenamer {
chars: Base54Chars,
preserved: FxHashSet<Id>,
cache: Option<RenameMap>,
mangle_name_cache: Option<Arc<dyn MangleCache>>,
}
impl Renamer for ManglingRenamer {
const MANGLE: bool = true;
const RESET_N: bool = false;
fn preserved_ids_for_module(&mut self, _: &Module) -> FxHashSet<Id> {
self.preserved.clone()
}
fn preserved_ids_for_script(&mut self, _: &Script) -> FxHashSet<Id> {
self.preserved.clone()
}
fn new_name_for(&self, _: &Id, n: &mut usize) -> Atom {
self.chars.encode(n, true)
}
fn get_cached(&self) -> Option<Cow<RenameMap>> {
self.cache.as_ref().map(Cow::Borrowed)
}
fn store_cache(&mut self, update: &RenameMap) {
if let Some(cacher) = &self.mangle_name_cache {
cacher.update_vars_cache(update);
}
}
}
struct LabelMangler {
chars: Base54Chars,
cache: FxHashMap<Atom, Atom>,
n: usize,
}
impl LabelMangler {
fn mangle(&mut self, label: &mut Ident) {
let v = self
.cache
.entry(label.sym.clone())
.or_insert_with(|| self.chars.encode(&mut self.n, true))
.clone();
label.sym = v;
}
}
impl VisitMut for LabelMangler {
noop_visit_mut_type!();
fn visit_mut_labeled_stmt(&mut self, s: &mut LabeledStmt) {
self.mangle(&mut s.label);
s.visit_mut_children_with(self);
}
fn visit_mut_continue_stmt(&mut self, s: &mut ContinueStmt) {
if let Some(label) = &mut s.label {
self.mangle(label);
}
}
fn visit_mut_break_stmt(&mut self, s: &mut BreakStmt) {
if let Some(label) = &mut s.label {
self.mangle(label);
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/pass/mangle_names/preserver.rs | Rust | use rustc_hash::FxHashSet;
use swc_ecma_ast::*;
use swc_ecma_usage_analyzer::marks::Marks;
use swc_ecma_utils::find_pat_ids;
use swc_ecma_visit::{noop_visit_type, Visit, VisitWith};
use crate::option::MangleOptions;
/// Returns `(preserved, unresolved)`
pub(crate) fn idents_to_preserve<N>(options: &MangleOptions, marks: Marks, n: &N) -> FxHashSet<Id>
where
N: for<'a> VisitWith<Preserver<'a>>,
{
let mut v = Preserver {
options,
preserved: Default::default(),
should_preserve: false,
in_top_level: false,
};
n.visit_with(&mut v);
let top_level_mark = marks.top_level_ctxt.outer();
// Force rename synthesized names
// See https://github.com/swc-project/swc/issues/9468
v.preserved.retain(|id| {
options.reserved.contains(&id.0) || id.1.outer().is_descendant_of(top_level_mark)
});
v.preserved
}
pub(crate) struct Preserver<'a> {
options: &'a MangleOptions,
preserved: FxHashSet<Id>,
should_preserve: bool,
in_top_level: bool,
}
impl Preserver<'_> {
fn is_reserved(&self, ident: &Ident) -> bool {
self.options.reserved.contains(&ident.sym)
}
}
impl Visit for Preserver<'_> {
noop_visit_type!();
fn visit_block_stmt(&mut self, n: &BlockStmt) {
let old_top_level = self.in_top_level;
for n in n.stmts.iter() {
self.in_top_level = false;
n.visit_with(self);
}
self.in_top_level = old_top_level;
}
fn visit_catch_clause(&mut self, n: &CatchClause) {
let old = self.should_preserve;
if self.options.ie8 && !self.options.top_level.unwrap_or_default() {
self.should_preserve = true;
n.param.visit_with(self);
}
self.should_preserve = old;
n.body.visit_with(self);
}
fn visit_class_decl(&mut self, n: &ClassDecl) {
n.visit_children_with(self);
if (self.in_top_level && !self.options.top_level.unwrap_or_default())
|| self.options.keep_class_names
|| self.is_reserved(&n.ident)
{
self.preserved.insert(n.ident.to_id());
}
}
fn visit_class_expr(&mut self, n: &ClassExpr) {
n.visit_children_with(self);
if self.options.keep_class_names {
if let Some(i) = &n.ident {
self.preserved.insert(i.to_id());
}
}
}
fn visit_export_decl(&mut self, n: &ExportDecl) {
n.visit_children_with(self);
match &n.decl {
Decl::Class(c) => {
self.preserved.insert(c.ident.to_id());
}
Decl::Fn(f) => {
self.preserved.insert(f.ident.to_id());
}
Decl::Var(v) => {
let ids: Vec<Id> = find_pat_ids(&v.decls);
self.preserved.extend(ids);
}
_ => {}
}
}
fn visit_expr(&mut self, n: &Expr) {
n.visit_children_with(self);
if let Expr::Ident(i) = n {
if self.should_preserve || self.is_reserved(i) {
self.preserved.insert(i.to_id());
}
}
}
fn visit_fn_decl(&mut self, n: &FnDecl) {
n.visit_children_with(self);
if (self.in_top_level && !self.options.top_level.unwrap_or_default())
|| self.is_reserved(&n.ident)
|| self.options.keep_fn_names
{
self.preserved.insert(n.ident.to_id());
}
}
fn visit_fn_expr(&mut self, n: &FnExpr) {
n.visit_children_with(self);
if self.options.keep_fn_names {
if let Some(i) = &n.ident {
self.preserved.insert(i.to_id());
}
}
}
fn visit_ident(&mut self, _: &Ident) {}
fn visit_module_items(&mut self, n: &[ModuleItem]) {
for n in n {
self.in_top_level = true;
n.visit_with(self);
}
}
fn visit_pat(&mut self, n: &Pat) {
n.visit_children_with(self);
if let Pat::Ident(i) = n {
if self.should_preserve || self.is_reserved(&i.id) {
self.preserved.insert(i.to_id());
}
}
}
fn visit_script(&mut self, n: &Script) {
for n in n.body.iter() {
self.in_top_level = true;
n.visit_with(self);
}
}
fn visit_var_declarator(&mut self, n: &VarDeclarator) {
n.visit_children_with(self);
if self.in_top_level && !self.options.top_level.unwrap_or_default() {
let old = self.should_preserve;
self.should_preserve = true;
n.name.visit_with(self);
self.should_preserve = old;
return;
}
if self.options.keep_fn_names {
match n.init.as_deref() {
Some(Expr::Fn(..)) | Some(Expr::Arrow(..)) => {
let old = self.should_preserve;
self.should_preserve = true;
n.name.visit_with(self);
self.should_preserve = old;
}
_ => {}
}
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/pass/mangle_names/private_name.rs | Rust | use rustc_hash::FxHashMap;
use swc_atoms::Atom;
use swc_ecma_ast::*;
use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith};
use super::Base54Chars;
pub(crate) fn private_name_mangler(keep_private_props: bool, chars: Base54Chars) -> impl VisitMut {
PrivateNameMangler {
keep_private_props,
private_n: Default::default(),
renamed_private: Default::default(),
chars,
}
}
struct PrivateNameMangler {
chars: Base54Chars,
keep_private_props: bool,
private_n: usize,
renamed_private: FxHashMap<Atom, Atom>,
}
impl PrivateNameMangler {
fn rename_private(&mut self, private_name: &mut PrivateName) {
let new_sym = if let Some(cached) = self.renamed_private.get(&private_name.name) {
cached.clone()
} else {
let sym = self.chars.encode(&mut self.private_n, true);
self.renamed_private
.insert(private_name.name.clone(), sym.clone());
sym
};
private_name.name = new_sym;
}
}
impl VisitMut for PrivateNameMangler {
noop_visit_mut_type!();
fn visit_mut_member_expr(&mut self, n: &mut MemberExpr) {
n.obj.visit_mut_with(self);
match &mut n.prop {
MemberProp::Computed(c) => c.visit_mut_with(self),
MemberProp::PrivateName(p) => p.visit_mut_with(self),
MemberProp::Ident(_) => (),
}
}
fn visit_mut_private_name(&mut self, private_name: &mut PrivateName) {
if !self.keep_private_props {
self.rename_private(private_name);
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/pass/mangle_props.rs | Rust | use std::collections::HashSet;
use once_cell::sync::Lazy;
use rustc_hash::{FxHashMap, FxHashSet};
use swc_atoms::Atom;
use swc_ecma_ast::{
CallExpr, Callee, Expr, IdentName, KeyValueProp, Lit, MemberExpr, MemberProp, Program, Prop,
PropName, Str, SuperProp, SuperPropExpr,
};
use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith};
use crate::{
option::ManglePropertiesOptions,
program_data::{analyze, ProgramData},
util::base54::Base54Chars,
};
pub static JS_ENVIRONMENT_PROPS: Lazy<FxHashSet<Atom>> = Lazy::new(|| {
let domprops: Vec<Atom> = serde_json::from_str(include_str!("../lists/domprops.json"))
.expect("failed to parse domprops.json for property mangler");
let jsprops: Vec<Atom> = serde_json::from_str(include_str!("../lists/jsprops.json"))
.expect("Failed to parse jsprops.json for property mangler");
let mut word_set: FxHashSet<Atom> = HashSet::default();
for name in domprops.iter().chain(jsprops.iter()) {
word_set.insert(name.clone());
}
word_set
});
struct ManglePropertiesState {
chars: Base54Chars,
options: ManglePropertiesOptions,
names_to_mangle: FxHashSet<Atom>,
unmangleable: FxHashSet<Atom>,
// Cache of already mangled names
cache: FxHashMap<Atom, Atom>,
// Numbers to pass to base54()
n: usize,
}
impl ManglePropertiesState {
fn add(&mut self, name: &Atom) {
if self.can_mangle(name) {
self.names_to_mangle.insert(name.clone());
}
if !self.should_mangle(name) {
self.unmangleable.insert(name.clone());
}
}
fn can_mangle(&self, name: &Atom) -> bool {
!(self.unmangleable.contains(name) || self.is_reserved(name))
}
fn matches_regex_option(&self, name: &Atom) -> bool {
if let Some(regex) = &self.options.regex {
regex.is_match(name)
} else {
true
}
}
fn should_mangle(&self, name: &Atom) -> bool {
if !self.matches_regex_option(name) || self.is_reserved(name) {
false
} else {
self.cache.contains_key(name) || self.names_to_mangle.contains(name)
}
}
fn is_reserved(&self, name: &Atom) -> bool {
JS_ENVIRONMENT_PROPS.contains(name) || self.options.reserved.contains(name)
}
fn gen_name(&mut self, name: &Atom) -> Option<Atom> {
if self.should_mangle(name) {
if let Some(cached) = self.cache.get(name) {
Some(cached.clone())
} else {
let mangled_name = self.chars.encode(&mut self.n, true);
self.cache.insert(name.clone(), mangled_name.clone());
Some(mangled_name)
}
} else {
None
}
}
}
pub(crate) fn mangle_properties(
m: &mut Program,
options: ManglePropertiesOptions,
chars: Base54Chars,
) {
let mut state = ManglePropertiesState {
options,
chars,
names_to_mangle: Default::default(),
unmangleable: Default::default(),
cache: Default::default(),
n: 0,
};
let data = analyze(&*m, None);
m.visit_mut_with(&mut PropertyCollector {
state: &mut state,
data,
});
m.visit_mut_with(&mut Mangler { state: &mut state });
}
// Step 1 -- collect candidates to mangle
pub struct PropertyCollector<'a> {
data: ProgramData,
state: &'a mut ManglePropertiesState,
}
impl VisitMut for PropertyCollector<'_> {
fn visit_mut_call_expr(&mut self, call: &mut CallExpr) {
call.visit_mut_children_with(self);
if let Some(prop_name) = get_object_define_property_name_arg(call) {
self.state.add(&prop_name.value);
}
}
fn visit_mut_member_expr(&mut self, member_expr: &mut MemberExpr) {
member_expr.visit_mut_children_with(self);
let is_root_declared = is_root_of_member_expr_declared(member_expr, &self.data);
if is_root_declared {
if let MemberProp::Ident(ident) = &mut member_expr.prop {
self.state.add(&ident.sym);
}
}
}
fn visit_mut_prop(&mut self, prop: &mut Prop) {
prop.visit_mut_children_with(self);
if let Prop::Shorthand(ident) = prop {
self.state.add(&ident.sym);
}
}
fn visit_mut_prop_name(&mut self, name: &mut PropName) {
name.visit_mut_children_with(self);
match name {
PropName::Ident(ident) => {
self.state.add(&ident.sym);
}
PropName::Str(s) => {
self.state.add(&s.value);
}
_ => {}
};
}
}
fn is_root_of_member_expr_declared(member_expr: &MemberExpr, data: &ProgramData) -> bool {
match &*member_expr.obj {
Expr::Member(member_expr) => is_root_of_member_expr_declared(member_expr, data),
Expr::Ident(expr) => data
.vars
.get(&expr.to_id())
.map(|var| var.declared)
.unwrap_or(false),
_ => false,
}
}
fn is_object_property_call(call: &CallExpr) -> bool {
// Find Object.defineProperty
if let Callee::Expr(callee) = &call.callee {
match &**callee {
Expr::Member(MemberExpr {
obj,
prop: MemberProp::Ident(IdentName { sym, .. }),
..
}) if *sym == *"defineProperty" => {
if obj.is_ident_ref_to("Object") {
return true;
}
}
_ => {}
}
};
false
}
fn get_object_define_property_name_arg(call: &mut CallExpr) -> Option<&mut Str> {
if is_object_property_call(call) {
let second_arg: &mut Expr = call.args.get_mut(1).map(|arg| &mut arg.expr)?;
if let Expr::Lit(Lit::Str(s)) = second_arg {
Some(s)
} else {
None
}
} else {
None
}
}
// Step 2 -- mangle those properties
struct Mangler<'a> {
state: &'a mut ManglePropertiesState,
}
impl Mangler<'_> {
fn mangle_ident(&mut self, ident: &mut IdentName) {
if let Some(mangled) = self.state.gen_name(&ident.sym) {
ident.sym = mangled;
}
}
fn mangle_str(&mut self, string: &mut Str) {
if let Some(mangled) = self.state.gen_name(&string.value) {
string.value = mangled;
string.raw = None;
}
}
}
impl VisitMut for Mangler<'_> {
noop_visit_mut_type!();
fn visit_mut_call_expr(&mut self, call: &mut CallExpr) {
call.visit_mut_children_with(self);
if let Some(prop_name_str) = get_object_define_property_name_arg(call) {
self.mangle_str(prop_name_str);
}
}
fn visit_mut_member_expr(&mut self, member_expr: &mut MemberExpr) {
member_expr.visit_mut_children_with(self);
if let MemberProp::Ident(ident) = &mut member_expr.prop {
self.mangle_ident(ident);
}
}
fn visit_mut_prop(&mut self, prop: &mut Prop) {
prop.visit_mut_children_with(self);
if let Prop::Shorthand(ident) = prop {
let mut new_ident = IdentName::from(ident.clone());
self.mangle_ident(&mut new_ident);
*prop = Prop::KeyValue(KeyValueProp {
key: PropName::Ident(new_ident),
value: ident.clone().into(),
});
}
}
fn visit_mut_prop_name(&mut self, name: &mut PropName) {
name.visit_mut_children_with(self);
match name {
PropName::Ident(ident) => {
self.mangle_ident(ident);
}
PropName::Str(string) => {
self.mangle_str(string);
}
_ => {}
}
}
fn visit_mut_super_prop_expr(&mut self, super_expr: &mut SuperPropExpr) {
super_expr.visit_mut_children_with(self);
if let SuperProp::Ident(ident) = &mut super_expr.prop {
self.mangle_ident(ident);
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/pass/merge_exports.rs | Rust | use swc_common::{util::take::Take, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith};
use crate::maybe_par;
///
/// - merge exports
pub(crate) fn merge_exports() -> impl VisitMut {
Merger::default()
}
#[derive(Default)]
struct Merger {
specifiers: Vec<ExportSpecifier>,
}
impl VisitMut for Merger {
noop_visit_mut_type!();
fn visit_mut_module_items(&mut self, stmts: &mut Vec<ModuleItem>) {
let was_module = maybe_par!(
stmts
.iter()
.any(|s| matches!(s, ModuleItem::ModuleDecl(..))),
*crate::LIGHT_TASK_PARALLELS
);
// Fast-path
if !was_module {
return;
}
stmts.visit_mut_children_with(self);
// Merge exports
stmts.retain(|s| {
!matches!(
s,
ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(NamedExport { src: None, .. }))
)
});
if !self.specifiers.is_empty() {
stmts.push(
NamedExport {
src: None,
specifiers: self.specifiers.take(),
span: DUMMY_SP,
type_only: Default::default(),
with: Default::default(),
}
.into(),
);
}
// export {}, to preserve module semantics
if was_module && stmts.iter().all(|s| matches!(s, ModuleItem::Stmt(..))) {
stmts.push(
NamedExport {
src: None,
specifiers: Default::default(),
span: DUMMY_SP,
type_only: Default::default(),
with: Default::default(),
}
.into(),
);
}
}
fn visit_mut_named_export(&mut self, e: &mut NamedExport) {
if e.src.is_some() {
return;
}
self.specifiers.append(&mut e.specifiers);
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/pass/mod.rs | Rust | pub mod global_defs;
pub mod mangle_names;
pub mod mangle_props;
pub mod merge_exports;
pub mod postcompress;
pub mod precompress;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/pass/postcompress.rs | Rust | use swc_common::util::take::Take;
use swc_ecma_ast::*;
use swc_ecma_transforms_base::perf::{Parallel, ParallelExt};
use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith};
use crate::{maybe_par, option::CompressOptions, LIGHT_TASK_PARALLELS};
pub fn postcompress_optimizer(options: &CompressOptions) -> impl '_ + VisitMut {
PostcompressOptimizer {
options,
ctx: Default::default(),
}
}
struct PostcompressOptimizer<'a> {
options: &'a CompressOptions,
ctx: Ctx,
}
#[derive(Default, Clone, Copy)]
struct Ctx {
is_module: bool,
is_top_level: bool,
}
impl Parallel for PostcompressOptimizer<'_> {
fn create(&self) -> Self {
Self {
options: self.options,
ctx: self.ctx,
}
}
fn merge(&mut self, _: Self) {}
}
impl VisitMut for PostcompressOptimizer<'_> {
noop_visit_mut_type!();
fn visit_mut_export_decl(&mut self, export: &mut ExportDecl) {
match &mut export.decl {
Decl::Var(decl) => {
// Don't change constness of exported variables.
decl.visit_mut_children_with(self);
}
_ => {
export.decl.visit_mut_with(self);
}
}
}
fn visit_mut_module_decl(&mut self, m: &mut ModuleDecl) {
if let ModuleDecl::ExportDefaultExpr(e) = m {
match &mut *e.expr {
Expr::Fn(f) => {
if f.ident.is_some() {
if self.options.top_level() {
*m = ExportDefaultDecl {
span: e.span,
decl: DefaultDecl::Fn(f.take()),
}
.into()
}
} else {
*m = ExportDefaultDecl {
span: e.span,
decl: DefaultDecl::Fn(f.take()),
}
.into()
}
}
Expr::Class(c) => {
if c.ident.is_some() {
if self.options.top_level() {
*m = ExportDefaultDecl {
span: e.span,
decl: DefaultDecl::Class(c.take()),
}
.into()
}
} else {
*m = ExportDefaultDecl {
span: e.span,
decl: DefaultDecl::Class(c.take()),
}
.into()
}
}
_ => (),
}
}
m.visit_mut_children_with(self)
}
fn visit_mut_module_items(&mut self, nodes: &mut Vec<ModuleItem>) {
self.ctx.is_module = maybe_par!(
nodes
.iter()
.any(|s| matches!(s, ModuleItem::ModuleDecl(..))),
*crate::LIGHT_TASK_PARALLELS
);
self.ctx.is_top_level = true;
self.maybe_par(*crate::LIGHT_TASK_PARALLELS, nodes, |v, n| {
n.visit_mut_with(v);
});
}
fn visit_mut_stmts(&mut self, nodes: &mut Vec<Stmt>) {
let old = self.ctx;
self.ctx.is_top_level = false;
self.maybe_par(*crate::LIGHT_TASK_PARALLELS, nodes, |v, n| {
n.visit_mut_with(v);
});
self.ctx = old;
}
fn visit_mut_var_decl(&mut self, v: &mut VarDecl) {
v.visit_mut_children_with(self);
if self.options.const_to_let {
if self.ctx.is_module || !self.ctx.is_top_level {
// We don't change constness of top-level variables in a script
if let VarDeclKind::Const = v.kind {
v.kind = VarDeclKind::Let;
}
}
}
}
fn visit_mut_exprs(&mut self, n: &mut Vec<Box<Expr>>) {
self.maybe_par(*LIGHT_TASK_PARALLELS, n, |v, n| {
n.visit_mut_with(v);
});
}
fn visit_mut_opt_vec_expr_or_spreads(&mut self, n: &mut Vec<Option<ExprOrSpread>>) {
self.maybe_par(*LIGHT_TASK_PARALLELS, n, |v, n| {
n.visit_mut_with(v);
});
}
fn visit_mut_expr_or_spreads(&mut self, n: &mut Vec<ExprOrSpread>) {
self.maybe_par(*LIGHT_TASK_PARALLELS, n, |v, n| {
n.visit_mut_with(v);
});
}
fn visit_mut_var_declarators(&mut self, n: &mut Vec<VarDeclarator>) {
self.maybe_par(*LIGHT_TASK_PARALLELS, n, |v, n| {
n.visit_mut_with(v);
});
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/pass/precompress.rs | Rust | use std::vec::Vec;
use swc_common::util::take::Take;
use swc_ecma_ast::*;
use swc_ecma_transforms_base::perf::{Parallel, ParallelExt};
use swc_ecma_utils::{ExprCtx, ExprExt, Value::Known};
use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith};
use crate::HEAVY_TASK_PARALLELS;
/// Optimizer invoked before invoking compressor.
///
/// - Remove parens.
///
/// TODO: remove completely after #8333
pub(crate) fn precompress_optimizer<'a>(expr_ctx: ExprCtx) -> impl 'a + VisitMut {
PrecompressOptimizer { expr_ctx }
}
#[derive(Debug)]
pub(crate) struct PrecompressOptimizer {
expr_ctx: ExprCtx,
}
impl PrecompressOptimizer {
/// Drops RHS from `null && foo`
fn optimize_bin_expr(&mut self, n: &mut Expr) {
let Expr::Bin(b) = n else {
return;
};
if b.op == op!("&&") && b.left.as_pure_bool(self.expr_ctx) == Known(false) {
*n = *b.left.take();
return;
}
if b.op == op!("||") && b.left.as_pure_bool(self.expr_ctx) == Known(true) {
*n = *b.left.take();
}
}
}
impl Parallel for PrecompressOptimizer {
fn create(&self) -> Self {
Self { ..*self }
}
fn merge(&mut self, _: Self) {}
}
impl VisitMut for PrecompressOptimizer {
noop_visit_mut_type!();
fn visit_mut_expr(&mut self, n: &mut Expr) {
n.visit_mut_children_with(self);
self.optimize_bin_expr(n);
}
fn visit_mut_stmts(&mut self, n: &mut Vec<Stmt>) {
self.maybe_par(*HEAVY_TASK_PARALLELS, n, |v, n| {
n.visit_mut_with(v);
});
}
fn visit_mut_module_items(&mut self, n: &mut Vec<ModuleItem>) {
self.maybe_par(*HEAVY_TASK_PARALLELS, n, |v, n| {
n.visit_mut_with(v);
});
}
fn visit_mut_exprs(&mut self, n: &mut Vec<Box<Expr>>) {
self.maybe_par(*HEAVY_TASK_PARALLELS, n, |v, n| {
n.visit_mut_with(v);
});
}
fn visit_mut_opt_vec_expr_or_spreads(&mut self, n: &mut Vec<Option<ExprOrSpread>>) {
self.maybe_par(*HEAVY_TASK_PARALLELS, n, |v, n| {
n.visit_mut_with(v);
});
}
fn visit_mut_expr_or_spreads(&mut self, n: &mut Vec<ExprOrSpread>) {
self.maybe_par(*HEAVY_TASK_PARALLELS, n, |v, n| {
n.visit_mut_with(v);
});
}
fn visit_mut_var_declarators(&mut self, n: &mut Vec<VarDeclarator>) {
self.maybe_par(*HEAVY_TASK_PARALLELS, n, |v, n| {
n.visit_mut_with(v);
});
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/program_data.rs | Rust | use std::collections::hash_map::Entry;
use indexmap::IndexSet;
use rustc_hash::{FxBuildHasher, FxHashMap};
use swc_atoms::Atom;
use swc_common::SyntaxContext;
use swc_ecma_ast::*;
use swc_ecma_usage_analyzer::{
alias::{Access, AccessKind},
analyzer::{
analyze_with_storage,
storage::{ScopeDataLike, Storage, VarDataLike},
Ctx, ScopeKind, UsageAnalyzer,
},
marks::Marks,
util::is_global_var_with_pure_property_access,
};
use swc_ecma_utils::{Merge, Type, Value};
use swc_ecma_visit::VisitWith;
pub(crate) fn analyze<N>(n: &N, marks: Option<Marks>) -> ProgramData
where
N: VisitWith<UsageAnalyzer<ProgramData>>,
{
analyze_with_storage::<ProgramData, _>(n, marks)
}
/// Analyzed info of a whole program we are working on.
#[derive(Debug, Default)]
pub(crate) struct ProgramData {
pub(crate) vars: FxHashMap<Id, Box<VarUsageInfo>>,
pub(crate) top: ScopeData,
pub(crate) scopes: FxHashMap<SyntaxContext, ScopeData>,
initialized_vars: IndexSet<Id, FxBuildHasher>,
}
#[derive(Debug, Default, Clone)]
pub(crate) struct ScopeData {
pub(crate) has_with_stmt: bool,
pub(crate) has_eval_call: bool,
pub(crate) used_arguments: bool,
}
#[derive(Debug, Clone)]
pub(crate) struct VarUsageInfo {
pub(crate) inline_prevented: bool,
/// The number of direct reference to this identifier.
pub(crate) ref_count: u32,
/// `false` if it's only used.
pub(crate) declared: bool,
pub(crate) declared_count: u32,
/// `true` if the enclosing function defines this variable as a parameter.
pub(crate) declared_as_fn_param: bool,
pub(crate) declared_as_fn_decl: bool,
pub(crate) declared_as_fn_expr: bool,
pub(crate) declared_as_for_init: bool,
/// The number of assign and initialization to this identifier.
pub(crate) assign_count: u32,
/// The number of direct and indirect reference to this identifier.
/// ## Things to note
///
/// - Update is counted as usage, but assign is not
pub(crate) usage_count: u32,
/// The variable itself is assigned after reference.
pub(crate) reassigned: bool,
pub(crate) has_property_access: bool,
pub(crate) property_mutation_count: u32,
pub(crate) exported: bool,
/// True if used **above** the declaration or in init. (Not eval order).
pub(crate) used_above_decl: bool,
/// `true` if it's declared by function parameters or variables declared in
/// a closest function and used only within it and not used by child
/// functions.
pub(crate) is_fn_local: bool,
used_in_non_child_fn: bool,
/// `true` if all its assign happens in the same function scope it's defined
pub(crate) assigned_fn_local: bool,
pub(crate) executed_multiple_time: bool,
pub(crate) used_in_cond: bool,
pub(crate) var_kind: Option<VarDeclKind>,
pub(crate) var_initialized: bool,
pub(crate) merged_var_type: Option<Value<Type>>,
pub(crate) declared_as_catch_param: bool,
pub(crate) no_side_effect_for_member_access: bool,
pub(crate) callee_count: u32,
/// `a` in `foo(a)` or `foo({ a })`.
pub(crate) used_as_ref: bool,
pub(crate) used_as_arg: bool,
pub(crate) indexed_with_dynamic_key: bool,
pub(crate) pure_fn: bool,
/// Is the variable declared in top level?
pub(crate) is_top_level: bool,
/// `infects_to`. This should be renamed, but it will be done with another
/// PR. (because it's hard to review)
infects_to: Vec<Access>,
/// Only **string** properties.
pub(crate) accessed_props: FxHashMap<Atom, u32>,
pub(crate) used_recursively: bool,
}
impl Default for VarUsageInfo {
fn default() -> Self {
Self {
inline_prevented: Default::default(),
ref_count: Default::default(),
declared: Default::default(),
declared_count: Default::default(),
declared_as_fn_param: Default::default(),
declared_as_fn_decl: Default::default(),
declared_as_fn_expr: Default::default(),
declared_as_for_init: Default::default(),
assign_count: Default::default(),
usage_count: Default::default(),
reassigned: Default::default(),
has_property_access: Default::default(),
property_mutation_count: Default::default(),
exported: Default::default(),
used_above_decl: Default::default(),
is_fn_local: true,
executed_multiple_time: Default::default(),
used_in_cond: Default::default(),
var_kind: Default::default(),
var_initialized: Default::default(),
merged_var_type: Default::default(),
declared_as_catch_param: Default::default(),
no_side_effect_for_member_access: Default::default(),
callee_count: Default::default(),
used_as_arg: Default::default(),
indexed_with_dynamic_key: Default::default(),
pure_fn: Default::default(),
infects_to: Default::default(),
used_in_non_child_fn: Default::default(),
accessed_props: Default::default(),
used_recursively: Default::default(),
is_top_level: Default::default(),
assigned_fn_local: true,
used_as_ref: false,
}
}
}
impl VarUsageInfo {
pub(crate) fn is_infected(&self) -> bool {
!self.infects_to.is_empty()
}
/// The variable itself or a property of it is modified.
pub(crate) fn mutated(&self) -> bool {
self.assign_count > 1 || self.property_mutation_count > 0
}
pub(crate) fn can_inline_fn_once(&self) -> bool {
(self.callee_count > 0
|| !self.executed_multiple_time && (self.is_fn_local || !self.used_in_non_child_fn))
&& !(self.used_recursively
&& self.has_property_access
&& self.property_mutation_count != 0)
}
fn initialized(&self) -> bool {
self.var_initialized || self.declared_as_fn_param || self.declared_as_catch_param
}
}
impl Storage for ProgramData {
type ScopeData = ScopeData;
type VarData = VarUsageInfo;
fn scope(&mut self, ctxt: swc_common::SyntaxContext) -> &mut Self::ScopeData {
self.scopes.entry(ctxt).or_default()
}
fn top_scope(&mut self) -> &mut Self::ScopeData {
&mut self.top
}
fn var_or_default(&mut self, id: Id) -> &mut Self::VarData {
self.vars.entry(id).or_default()
}
fn merge(&mut self, kind: ScopeKind, child: Self) {
self.scopes.reserve(child.scopes.len());
for (ctxt, scope) in child.scopes {
let to = self.scopes.entry(ctxt).or_default();
self.top.merge(scope.clone(), true);
to.merge(scope, false);
}
self.vars.reserve(child.vars.len());
for (id, mut var_info) in child.vars {
// trace!("merge({:?},{}{:?})", kind, id.0, id.1);
let inited = self.initialized_vars.contains(&id);
match self.vars.entry(id.clone()) {
Entry::Occupied(mut e) => {
e.get_mut().inline_prevented |= var_info.inline_prevented;
let var_assigned = var_info.assign_count > 0
|| (var_info.var_initialized && !e.get().var_initialized);
if var_info.assign_count > 0 {
if e.get().initialized() {
e.get_mut().reassigned = true
}
}
if var_info.var_initialized {
// If it is inited in some other child scope and also inited in current
// scope
if e.get().var_initialized || e.get().ref_count > 0 {
e.get_mut().reassigned = true;
} else {
// If it is referred outside child scope, it will
// be marked as var_initialized false
e.get_mut().var_initialized = true;
}
} else {
// If it is inited in some other child scope, but referenced in
// current child scope
if !inited && e.get().var_initialized && var_info.ref_count > 0 {
e.get_mut().var_initialized = false;
e.get_mut().reassigned = true
}
}
e.get_mut().merged_var_type.merge(var_info.merged_var_type);
e.get_mut().ref_count += var_info.ref_count;
e.get_mut().reassigned |= var_info.reassigned;
e.get_mut().has_property_access |= var_info.has_property_access;
e.get_mut().property_mutation_count |= var_info.property_mutation_count;
e.get_mut().exported |= var_info.exported;
e.get_mut().declared |= var_info.declared;
e.get_mut().declared_count += var_info.declared_count;
e.get_mut().declared_as_fn_param |= var_info.declared_as_fn_param;
e.get_mut().declared_as_fn_decl |= var_info.declared_as_fn_decl;
e.get_mut().declared_as_fn_expr |= var_info.declared_as_fn_expr;
e.get_mut().declared_as_catch_param |= var_info.declared_as_catch_param;
// If a var is registered at a parent scope, it means that it's delcared before
// usages.
//
// e.get_mut().used_above_decl |= var_info.used_above_decl;
e.get_mut().executed_multiple_time |= var_info.executed_multiple_time;
e.get_mut().used_in_cond |= var_info.used_in_cond;
e.get_mut().assign_count += var_info.assign_count;
e.get_mut().usage_count += var_info.usage_count;
e.get_mut().infects_to.extend(var_info.infects_to);
e.get_mut().no_side_effect_for_member_access =
e.get_mut().no_side_effect_for_member_access
&& var_info.no_side_effect_for_member_access;
e.get_mut().callee_count += var_info.callee_count;
e.get_mut().used_as_arg |= var_info.used_as_arg;
e.get_mut().used_as_ref |= var_info.used_as_ref;
e.get_mut().indexed_with_dynamic_key |= var_info.indexed_with_dynamic_key;
e.get_mut().pure_fn |= var_info.pure_fn;
e.get_mut().used_recursively |= var_info.used_recursively;
e.get_mut().is_fn_local &= var_info.is_fn_local;
e.get_mut().used_in_non_child_fn |= var_info.used_in_non_child_fn;
e.get_mut().assigned_fn_local &= var_info.assigned_fn_local;
for (k, v) in var_info.accessed_props {
*e.get_mut().accessed_props.entry(k).or_default() += v;
}
match kind {
ScopeKind::Fn => {
e.get_mut().is_fn_local = false;
if !var_info.used_recursively {
e.get_mut().used_in_non_child_fn = true
}
if var_assigned {
e.get_mut().assigned_fn_local = false
}
}
ScopeKind::Block => {
if e.get().used_in_non_child_fn {
e.get_mut().is_fn_local = false;
e.get_mut().used_in_non_child_fn = true;
}
}
}
}
Entry::Vacant(e) => {
match kind {
ScopeKind::Fn => {
if !var_info.used_recursively {
var_info.used_in_non_child_fn = true
}
}
ScopeKind::Block => {}
}
e.insert(var_info);
}
}
}
}
fn report_usage(&mut self, ctx: Ctx, i: Id) {
let inited = self.initialized_vars.contains(&i);
let e = self.vars.entry(i.clone()).or_insert_with(|| {
Box::new(VarUsageInfo {
used_above_decl: true,
..Default::default()
})
});
e.used_as_ref |= ctx.is_id_ref;
e.ref_count += 1;
e.usage_count += 1;
// If it is inited in some child scope, but referenced in current scope
if !inited && e.var_initialized {
e.reassigned = true;
e.var_initialized = false;
}
e.inline_prevented |= ctx.inline_prevented;
e.executed_multiple_time |= ctx.executed_multiple_time;
e.used_in_cond |= ctx.in_cond;
}
fn report_assign(&mut self, ctx: Ctx, i: Id, is_op: bool, ty: Value<Type>) {
let e = self.vars.entry(i.clone()).or_default();
let inited = self.initialized_vars.contains(&i);
if e.assign_count > 0 || e.initialized() {
e.reassigned = true
}
e.merged_var_type.merge(Some(ty));
e.assign_count += 1;
if !is_op {
self.initialized_vars.insert(i.clone());
if e.ref_count == 1 && e.var_kind != Some(VarDeclKind::Const) && !inited {
e.var_initialized = true;
} else {
e.reassigned = true;
}
if e.ref_count == 1 && e.used_above_decl {
e.used_above_decl = false;
}
e.usage_count = e.usage_count.saturating_sub(1);
}
let mut to_visit: IndexSet<Id, FxBuildHasher> =
IndexSet::from_iter(e.infects_to.iter().cloned().map(|i| i.0));
let mut idx = 0;
while idx < to_visit.len() {
let curr = &to_visit[idx];
if let Some(usage) = self.vars.get_mut(curr) {
usage.inline_prevented |= ctx.inline_prevented;
usage.executed_multiple_time |= ctx.executed_multiple_time;
usage.used_in_cond |= ctx.in_cond;
if is_op {
usage.usage_count += 1;
}
to_visit.extend(usage.infects_to.iter().cloned().map(|i| i.0))
}
idx += 1;
}
}
fn declare_decl(
&mut self,
ctx: Ctx,
i: &Ident,
init_type: Option<Value<Type>>,
kind: Option<VarDeclKind>,
) -> &mut VarUsageInfo {
// if cfg!(feature = "debug") {
// debug!(has_init = has_init, "declare_decl(`{}`)", i);
// }
let v = self.vars.entry(i.to_id()).or_default();
v.is_top_level |= ctx.is_top_level;
// assigned or declared before this declaration
if init_type.is_some() {
if v.declared || v.var_initialized || v.assign_count > 0 {
#[cfg(feature = "debug")]
{
tracing::trace!("declare_decl(`{}`): Already declared", i);
}
v.reassigned = true;
}
v.assign_count += 1;
}
// This is not delcared yet, so this is the first declaration.
if !v.declared {
v.var_kind = kind;
v.no_side_effect_for_member_access = ctx.in_decl_with_no_side_effect_for_member_access;
}
if v.used_in_non_child_fn {
v.is_fn_local = false;
}
v.var_initialized |= init_type.is_some();
if ctx.in_pat_of_param {
v.merged_var_type = Some(Value::Unknown);
} else {
v.merged_var_type.merge(init_type);
}
v.declared_count += 1;
v.declared = true;
// not a VarDecl, thus always inited
if init_type.is_some() || kind.is_none() {
self.initialized_vars.insert(i.to_id());
}
v.declared_as_catch_param |= ctx.in_catch_param;
v
}
fn get_initialized_cnt(&self) -> usize {
self.initialized_vars.len()
}
fn truncate_initialized_cnt(&mut self, len: usize) {
self.initialized_vars.truncate(len)
}
fn mark_property_mutation(&mut self, id: Id) {
let e = self.vars.entry(id).or_default();
e.property_mutation_count += 1;
let to_mark_mutate = e
.infects_to
.iter()
.filter(|(_, kind)| *kind == AccessKind::Reference)
.map(|(id, _)| id.clone())
.collect::<Vec<_>>();
for other in to_mark_mutate {
let other = self.vars.entry(other).or_default();
other.property_mutation_count += 1;
}
}
}
impl ScopeDataLike for ScopeData {
fn add_declared_symbol(&mut self, _: &Ident) {}
fn merge(&mut self, other: Self, _: bool) {
self.has_with_stmt |= other.has_with_stmt;
self.has_eval_call |= other.has_eval_call;
self.used_arguments |= other.used_arguments;
}
fn mark_used_arguments(&mut self) {
self.used_arguments = true;
}
fn mark_eval_called(&mut self) {
self.has_eval_call = true;
}
fn mark_with_stmt(&mut self) {
self.has_with_stmt = true;
}
}
impl VarDataLike for VarUsageInfo {
fn mark_declared_as_fn_param(&mut self) {
self.declared_as_fn_param = true;
}
fn mark_declared_as_fn_decl(&mut self) {
self.declared_as_fn_decl = true;
}
fn mark_declared_as_fn_expr(&mut self) {
self.declared_as_fn_expr = true;
}
fn mark_declared_as_for_init(&mut self) {
self.declared_as_for_init = true;
}
fn mark_has_property_access(&mut self) {
self.has_property_access = true;
}
fn mark_used_as_callee(&mut self) {
self.callee_count += 1;
}
fn mark_used_as_arg(&mut self) {
self.used_as_ref = true;
self.used_as_arg = true
}
fn mark_indexed_with_dynamic_key(&mut self) {
self.indexed_with_dynamic_key = true;
}
fn add_accessed_property(&mut self, name: swc_atoms::Atom) {
*self.accessed_props.entry(name).or_default() += 1;
}
fn mark_used_as_ref(&mut self) {
self.used_as_ref = true;
}
fn add_infects_to(&mut self, other: Access) {
self.infects_to.push(other);
}
fn prevent_inline(&mut self) {
self.inline_prevented = true;
}
fn mark_as_exported(&mut self) {
self.exported = true;
}
fn mark_initialized_with_safe_value(&mut self) {
self.no_side_effect_for_member_access = true;
}
fn mark_as_pure_fn(&mut self) {
self.pure_fn = true;
}
fn mark_used_above_decl(&mut self) {
self.used_above_decl = true;
}
fn mark_used_recursively(&mut self) {
self.used_recursively = true;
}
}
impl ProgramData {
/// This should be used only for conditionals pass.
pub(crate) fn contains_unresolved(&self, e: &Expr) -> bool {
match e {
Expr::Ident(i) => self.ident_is_unresolved(i),
Expr::Member(MemberExpr { obj, prop, .. }) => {
if self.contains_unresolved(obj) {
return true;
}
if let MemberProp::Computed(prop) = prop {
if self.contains_unresolved(&prop.expr) {
return true;
}
}
false
}
Expr::Bin(BinExpr { left, right, .. }) => {
self.contains_unresolved(left) || self.contains_unresolved(right)
}
Expr::Unary(UnaryExpr { arg, .. }) => self.contains_unresolved(arg),
Expr::Update(UpdateExpr { arg, .. }) => self.contains_unresolved(arg),
Expr::Seq(SeqExpr { exprs, .. }) => exprs.iter().any(|e| self.contains_unresolved(e)),
Expr::Assign(AssignExpr { left, right, .. }) => {
// TODO
(match left {
AssignTarget::Simple(left) => {
self.simple_assign_target_contains_unresolved(left)
}
AssignTarget::Pat(_) => false,
}) || self.contains_unresolved(right)
}
Expr::Cond(CondExpr {
test, cons, alt, ..
}) => {
self.contains_unresolved(test)
|| self.contains_unresolved(cons)
|| self.contains_unresolved(alt)
}
Expr::New(NewExpr { args, .. }) => args.iter().flatten().any(|arg| match arg.spread {
Some(..) => self.contains_unresolved(&arg.expr),
None => false,
}),
Expr::Yield(YieldExpr { arg, .. }) => {
matches!(arg, Some(arg) if self.contains_unresolved(arg))
}
Expr::Tpl(Tpl { exprs, .. }) => exprs.iter().any(|e| self.contains_unresolved(e)),
Expr::Paren(ParenExpr { expr, .. }) => self.contains_unresolved(expr),
Expr::Await(AwaitExpr { arg, .. }) => self.contains_unresolved(arg),
Expr::Array(ArrayLit { elems, .. }) => elems.iter().any(|elem| match elem {
Some(elem) => self.contains_unresolved(&elem.expr),
None => false,
}),
Expr::Call(CallExpr {
callee: Callee::Expr(callee),
args,
..
}) => {
if self.contains_unresolved(callee) {
return true;
}
if args.iter().any(|arg| self.contains_unresolved(&arg.expr)) {
return true;
}
false
}
Expr::OptChain(o) => self.opt_chain_expr_contains_unresolved(o),
_ => false,
}
}
pub(crate) fn ident_is_unresolved(&self, i: &Ident) -> bool {
// We treat `window` and `global` as resolved
if is_global_var_with_pure_property_access(&i.sym)
|| matches!(&*i.sym, "arguments" | "window" | "global")
{
return false;
}
if let Some(v) = self.vars.get(&i.to_id()) {
return !v.declared;
}
true
}
fn opt_chain_expr_contains_unresolved(&self, o: &OptChainExpr) -> bool {
match &*o.base {
OptChainBase::Member(me) => self.member_expr_contains_unresolved(me),
OptChainBase::Call(OptCall { callee, args, .. }) => {
if self.contains_unresolved(callee) {
return true;
}
if args.iter().any(|arg| self.contains_unresolved(&arg.expr)) {
return true;
}
false
}
}
}
fn member_expr_contains_unresolved(&self, n: &MemberExpr) -> bool {
if self.contains_unresolved(&n.obj) {
return true;
}
if let MemberProp::Computed(prop) = &n.prop {
if self.contains_unresolved(&prop.expr) {
return true;
}
}
false
}
fn simple_assign_target_contains_unresolved(&self, n: &SimpleAssignTarget) -> bool {
match n {
SimpleAssignTarget::Ident(i) => self.ident_is_unresolved(&i.id),
SimpleAssignTarget::Member(me) => self.member_expr_contains_unresolved(me),
SimpleAssignTarget::SuperProp(n) => {
if let SuperProp::Computed(prop) = &n.prop {
if self.contains_unresolved(&prop.expr) {
return true;
}
}
false
}
SimpleAssignTarget::Paren(n) => self.contains_unresolved(&n.expr),
SimpleAssignTarget::OptChain(n) => self.opt_chain_expr_contains_unresolved(n),
SimpleAssignTarget::TsAs(..)
| SimpleAssignTarget::TsSatisfies(..)
| SimpleAssignTarget::TsNonNull(..)
| SimpleAssignTarget::TsTypeAssertion(..)
| SimpleAssignTarget::TsInstantiation(..) => false,
SimpleAssignTarget::Invalid(..) => true,
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/size_hint.rs | Rust | #[derive(Debug, Default, Clone, Copy)]
pub struct SizeHint {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/timing.rs | Rust | use std::{
io::{self, Write},
time::{Duration, Instant},
};
use crate::util::now;
/// TOOD: Add timings.
#[derive(Default, Debug)]
pub struct Timings {
current_section: Option<(String, Instant)>,
entries: Vec<(String, Duration)>,
}
impl Timings {
pub fn new() -> Timings {
Default::default()
}
pub fn section(&mut self, name: &str) {
self.end_section();
self.current_section = now().map(|now| (String::from(name), now));
}
pub fn end_section(&mut self) {
if let Some((prev_name, prev_start)) = &self.current_section {
self.entries.push((
prev_name.clone(),
Instant::now().duration_since(*prev_start),
));
}
}
pub fn log(&mut self) {
self.end_section();
let entries_printout: Vec<u8> = self
.entries
.iter()
.flat_map(|(name, duration)| {
let sec_duration = duration.as_micros() / 1_000_000;
format!("- {}: {:.6}s\n", name, sec_duration).into_bytes()
})
.collect();
io::stderr()
.write_all(&entries_printout)
.expect("Could not write timings");
*self = Timings::new();
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/util/base54.rs | Rust | use std::{cmp::Reverse, io, ops::AddAssign};
use arrayvec::ArrayVec;
use rustc_hash::FxHashSet;
use swc_atoms::Atom;
use swc_common::{
sync::Lrc, BytePos, FileLines, FileName, Loc, SourceMapper, Span, SpanLinesError, SyntaxContext,
};
use swc_ecma_ast::*;
use swc_ecma_codegen::{text_writer::WriteJs, Emitter};
use swc_ecma_utils::parallel::{cpu_count, Parallel, ParallelExt};
use swc_ecma_visit::{noop_visit_type, visit_obj_and_computed, Visit, VisitWith};
#[derive(Clone, Copy)]
pub(crate) struct CharFreq([i32; 64]);
#[derive(Clone, Copy)]
pub(crate) struct Base54Chars {
chars: [u8; 64],
}
impl Default for CharFreq {
fn default() -> Self {
CharFreq([0; 64])
}
}
struct DummySourceMap;
impl SourceMapper for DummySourceMap {
fn lookup_char_pos(&self, _: BytePos) -> Loc {
unreachable!()
}
fn span_to_lines(&self, _: Span) -> Result<FileLines, Box<SpanLinesError>> {
unreachable!()
}
fn span_to_string(&self, _: Span) -> String {
String::new()
}
fn span_to_filename(&self, _: Span) -> Lrc<FileName> {
FileName::Anon.into()
}
fn merge_spans(&self, _: Span, _: Span) -> Option<Span> {
None
}
fn call_span_if_macro(&self, sp: Span) -> Span {
sp
}
fn doctest_offset_line(&self, line: usize) -> usize {
line
}
fn span_to_snippet(&self, _: Span) -> Result<String, Box<swc_common::SpanSnippetError>> {
Ok(String::new())
}
}
impl SourceMapperExt for DummySourceMap {
fn get_code_map(&self) -> &dyn SourceMapper {
self
}
}
impl CharFreq {
#[inline(always)]
fn write(&mut self, data: &str) -> io::Result<()> {
self.scan(data, 1);
Ok(())
}
}
impl WriteJs for CharFreq {
#[inline(always)]
fn increase_indent(&mut self) -> io::Result<()> {
Ok(())
}
#[inline(always)]
fn decrease_indent(&mut self) -> io::Result<()> {
Ok(())
}
#[inline(always)]
fn write_semi(&mut self, _: Option<Span>) -> io::Result<()> {
Ok(())
}
#[inline(always)]
fn write_space(&mut self) -> io::Result<()> {
Ok(())
}
#[inline(always)]
fn write_keyword(&mut self, _: Option<Span>, s: &'static str) -> io::Result<()> {
self.write(s)?;
Ok(())
}
#[inline(always)]
fn write_operator(&mut self, _: Option<Span>, s: &str) -> io::Result<()> {
self.write(s)?;
Ok(())
}
#[inline(always)]
fn write_param(&mut self, s: &str) -> io::Result<()> {
self.write(s)?;
Ok(())
}
#[inline(always)]
fn write_property(&mut self, s: &str) -> io::Result<()> {
self.write(s)?;
Ok(())
}
#[inline(always)]
fn write_line(&mut self) -> io::Result<()> {
Ok(())
}
#[inline(always)]
fn write_lit(&mut self, _: Span, s: &str) -> io::Result<()> {
self.write(s)?;
Ok(())
}
#[inline(always)]
fn write_comment(&mut self, s: &str) -> io::Result<()> {
self.write(s)?;
Ok(())
}
#[inline(always)]
fn write_str_lit(&mut self, _: Span, s: &str) -> io::Result<()> {
self.write(s)?;
Ok(())
}
#[inline(always)]
fn write_str(&mut self, s: &str) -> io::Result<()> {
self.write(s)?;
Ok(())
}
#[inline(always)]
fn write_symbol(&mut self, _: Span, s: &str) -> io::Result<()> {
self.write(s)?;
Ok(())
}
#[inline(always)]
fn write_punct(&mut self, _: Option<Span>, s: &'static str) -> io::Result<()> {
self.write(s)?;
Ok(())
}
#[inline(always)]
fn care_about_srcmap(&self) -> bool {
false
}
#[inline(always)]
fn add_srcmap(&mut self, _: BytePos) -> io::Result<()> {
Ok(())
}
#[inline(always)]
fn commit_pending_semi(&mut self) -> io::Result<()> {
Ok(())
}
#[inline(always)]
fn can_ignore_invalid_unicodes(&mut self) -> bool {
true
}
}
impl CharFreq {
pub fn scan(&mut self, s: &str, delta: i32) {
if delta == 0 {
return;
}
// #[cfg(feature = "debug")]
// {
// let considered = s
// .chars()
// .filter(|&c| Ident::is_valid_continue(c))
// .collect::<String>();
// if !considered.is_empty() {
// tracing::debug!("Scanning: `{}` with delta {}", considered, delta);
// }
// }
for &c in s.as_bytes() {
match c {
b'a'..=b'z' => {
self.0[c as usize - 'a' as usize] += delta;
}
b'A'..=b'Z' => {
self.0[c as usize - 'A' as usize + 26] += delta;
}
b'0'..=b'9' => {
self.0[c as usize - '0' as usize + 52] += delta;
}
b'$' => {
self.0[62] += delta;
}
b'_' => {
self.0[63] += delta;
}
_ => {}
}
}
}
pub fn compute(p: &Program, preserved: &FxHashSet<Id>, unresolved_ctxt: SyntaxContext) -> Self {
let (mut a, b) = swc_parallel::join(
|| {
let cm = Lrc::new(DummySourceMap);
let mut freq = Self::default();
{
let mut emitter = Emitter {
cfg: swc_ecma_codegen::Config::default()
.with_target(EsVersion::latest())
.with_minify(true),
cm,
comments: None,
wr: &mut freq,
};
emitter.emit_program(p).unwrap();
}
freq
},
|| {
let mut visitor = CharFreqAnalyzer {
freq: Default::default(),
preserved,
unresolved_ctxt,
};
// Subtract
p.visit_with(&mut visitor);
visitor.freq
},
);
a += b;
a
}
pub fn compile(self) -> Base54Chars {
static BASE54_DEFAULT_CHARS: &[u8; 64] =
b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$_";
let mut arr = BASE54_DEFAULT_CHARS
.iter()
.copied()
.enumerate()
.map(|(idx, c)| (self.0[idx], c))
.collect::<Vec<_>>();
arr.sort_by_key(|&(freq, _)| Reverse(freq));
let mut digits = Vec::with_capacity(10);
let mut alpha = Vec::with_capacity(54);
let mut all = Vec::with_capacity(64);
for (_, c) in arr {
if c.is_ascii_digit() {
digits.push(c);
} else {
alpha.push(c);
}
}
all.extend_from_slice(&alpha);
all.extend_from_slice(&digits);
#[cfg(feature = "debug")]
tracing::info!("Chars: {}", String::from_utf8_lossy(&all));
Base54Chars {
chars: all.try_into().unwrap(),
}
}
}
struct CharFreqAnalyzer<'a> {
freq: CharFreq,
preserved: &'a FxHashSet<Id>,
unresolved_ctxt: SyntaxContext,
}
impl Parallel for CharFreqAnalyzer<'_> {
fn create(&self) -> Self {
Self {
freq: Default::default(),
..*self
}
}
fn merge(&mut self, other: Self) {
self.freq += other.freq;
}
}
impl Visit for CharFreqAnalyzer<'_> {
noop_visit_type!();
visit_obj_and_computed!();
fn visit_class_members(&mut self, members: &[ClassMember]) {
self.maybe_par(cpu_count() * 8, members, |v, member| {
member.visit_with(v);
});
}
fn visit_expr_or_spreads(&mut self, n: &[ExprOrSpread]) {
self.maybe_par(cpu_count() * 8, n, |v, n| {
n.visit_with(v);
});
}
fn visit_exprs(&mut self, exprs: &[Box<Expr>]) {
self.maybe_par(cpu_count() * 8, exprs, |v, expr| {
expr.visit_with(v);
});
}
fn visit_ident(&mut self, i: &Ident) {
if i.ctxt == self.unresolved_ctxt && i.sym != "arguments" {
return;
}
// It's not mangled
if self.preserved.contains(&i.to_id()) {
return;
}
self.freq.scan(&i.sym, -1);
}
/// This is preserved anyway
fn visit_module_export_name(&mut self, _: &ModuleExportName) {}
fn visit_module_items(&mut self, items: &[ModuleItem]) {
self.maybe_par(cpu_count() * 8, items, |v, item| {
item.visit_with(v);
});
}
fn visit_opt_vec_expr_or_spreads(&mut self, n: &[Option<ExprOrSpread>]) {
self.maybe_par(cpu_count() * 8, n, |v, n| {
n.visit_with(v);
});
}
fn visit_prop_name(&mut self, n: &PropName) {
match n {
PropName::Ident(_) => {}
PropName::Str(_) => {}
PropName::Num(_) => {}
PropName::Computed(e) => e.visit_with(self),
PropName::BigInt(_) => {}
}
}
fn visit_prop_or_spreads(&mut self, n: &[PropOrSpread]) {
self.maybe_par(cpu_count() * 8, n, |v, n| {
n.visit_with(v);
});
}
fn visit_stmts(&mut self, stmts: &[Stmt]) {
self.maybe_par(cpu_count() * 8, stmts, |v, stmt| {
stmt.visit_with(v);
});
}
}
impl AddAssign for CharFreq {
fn add_assign(&mut self, rhs: Self) {
for i in 0..64 {
self.0[i] += rhs.0[i];
}
}
}
impl Base54Chars {
/// givin a number, return a base54 encoded string
/// `usize -> [a-zA-Z$_][a-zA-Z$_0-9]*`
pub(crate) fn encode(&self, init: &mut usize, skip_reserved: bool) -> Atom {
let mut n = *init;
*init += 1;
let mut base = 54;
while n >= base {
n -= base;
base <<= 6;
}
// Not sure if this is ideal, but it's safe
let mut ret: ArrayVec<_, 14> = ArrayVec::new();
base /= 54;
let mut c = self.chars[n / base];
ret.push(c);
while base > 1 {
n %= base;
base >>= 6;
c = self.chars[n / base];
ret.push(c);
}
let s = unsafe {
// Safety: We are only using ascii characters
// Safety: The stack memory for ret is alive while creating Atom
Atom::from(std::str::from_utf8_unchecked(&ret))
};
if skip_reserved
&& (s.is_reserved()
|| s.is_reserved_in_strict_bind()
|| s.is_reserved_in_strict_mode(true))
{
return self.encode(init, skip_reserved);
}
s
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/util/mod.rs | Rust | #![allow(dead_code)]
use std::time::Instant;
use rustc_hash::FxHashSet;
use swc_atoms::Atom;
use swc_common::{util::take::Take, Span, Spanned, DUMMY_SP};
use swc_ecma_ast::*;
use swc_ecma_transforms_base::{fixer::fixer, hygiene::hygiene};
use swc_ecma_utils::{stack_size::maybe_grow_default, DropSpan, ModuleItemLike, StmtLike, Value};
use swc_ecma_visit::{noop_visit_type, visit_mut_pass, visit_obj_and_computed, Visit, VisitWith};
pub(crate) mod base54;
pub(crate) mod size;
pub(crate) mod sort;
pub(crate) fn make_number(span: Span, value: f64) -> Expr {
trace_op!("Creating a numeric literal");
Lit::Num(Number {
span,
value,
raw: None,
})
.into()
}
pub trait ModuleItemExt:
StmtLike + ModuleItemLike + From<Stmt> + Spanned + std::fmt::Debug
{
fn as_module_decl(&self) -> Result<&ModuleDecl, &Stmt>;
fn from_module_item(item: ModuleItem) -> Self;
fn into_module_item(self) -> ModuleItem {
match self.into_module_decl() {
Ok(v) => v.into(),
Err(v) => v.into(),
}
}
fn into_module_decl(self) -> Result<ModuleDecl, Stmt>;
}
impl ModuleItemExt for Stmt {
fn as_module_decl(&self) -> Result<&ModuleDecl, &Stmt> {
Err(self)
}
fn from_module_item(item: ModuleItem) -> Self {
item.expect_stmt()
}
fn into_module_decl(self) -> Result<ModuleDecl, Stmt> {
Err(self)
}
}
impl ModuleItemExt for ModuleItem {
fn as_module_decl(&self) -> Result<&ModuleDecl, &Stmt> {
match self {
ModuleItem::ModuleDecl(v) => Ok(v),
ModuleItem::Stmt(v) => Err(v),
}
}
fn from_module_item(item: ModuleItem) -> Self {
item
}
fn into_module_decl(self) -> Result<ModuleDecl, Stmt> {
match self {
ModuleItem::ModuleDecl(v) => Ok(v),
ModuleItem::Stmt(v) => Err(v),
}
}
}
///
/// - `!0` for true
/// - `!1` for false
pub(crate) fn make_bool(span: Span, value: bool) -> Expr {
trace_op!("Creating a boolean literal");
UnaryExpr {
span,
op: op!("!"),
arg: Lit::Num(Number {
span: DUMMY_SP,
value: if value { 0.0 } else { 1.0 },
raw: None,
})
.into(),
}
.into()
}
/// Additional methods for optimizing expressions.
pub(crate) trait ExprOptExt: Sized {
fn as_expr(&self) -> &Expr;
fn as_mut(&mut self) -> &mut Expr;
fn first_expr_mut(&mut self) -> &mut Expr {
let expr = self.as_mut();
match expr {
Expr::Seq(seq) => seq
.exprs
.first_mut()
.expect("Sequence expressions should have at least one element")
.first_expr_mut(),
expr => expr,
}
}
/// This returns itself for normal expressions and returns last expressions
/// for sequence expressions.
fn value_mut(&mut self) -> &mut Expr {
let expr = self.as_mut();
match expr {
Expr::Seq(seq) => seq
.exprs
.last_mut()
.expect("Sequence expressions should have at least one element")
.value_mut(),
expr => expr,
}
}
fn force_seq(&mut self) -> &mut SeqExpr {
let expr = self.as_mut();
match expr {
Expr::Seq(seq) => seq,
_ => {
let inner = expr.take();
*expr = SeqExpr {
span: DUMMY_SP,
exprs: vec![Box::new(inner)],
}
.into();
expr.force_seq()
}
}
}
fn prepend_exprs(&mut self, mut exprs: Vec<Box<Expr>>) {
if exprs.is_empty() {
return;
}
let to = self.as_mut();
match to {
Expr::Seq(to) => {
exprs.append(&mut to.exprs);
to.exprs = exprs;
}
_ => {
let v = to.take();
exprs.push(Box::new(v));
*to = SeqExpr {
span: DUMMY_SP,
exprs,
}
.into();
}
}
}
}
impl ExprOptExt for Box<Expr> {
fn as_expr(&self) -> &Expr {
self
}
fn as_mut(&mut self) -> &mut Expr {
self
}
}
impl ExprOptExt for Expr {
fn as_expr(&self) -> &Expr {
self
}
fn as_mut(&mut self) -> &mut Expr {
self
}
}
pub(crate) fn contains_leaping_continue_with_label<N>(n: &N, label: Atom) -> bool
where
N: VisitWith<LeapFinder>,
{
let mut v = LeapFinder {
target_label: Some(label),
..Default::default()
};
n.visit_with(&mut v);
v.found_continue_with_label
}
#[allow(unused)]
pub(crate) fn contains_leaping_yield<N>(n: &N) -> bool
where
N: VisitWith<LeapFinder>,
{
let mut v = LeapFinder::default();
n.visit_with(&mut v);
v.found_yield
}
#[derive(Default)]
pub(crate) struct LeapFinder {
found_await: bool,
found_yield: bool,
found_continue_with_label: bool,
target_label: Option<Atom>,
}
impl Visit for LeapFinder {
noop_visit_type!();
fn visit_await_expr(&mut self, n: &AwaitExpr) {
n.visit_children_with(self);
self.found_await = true;
}
fn visit_arrow_expr(&mut self, _: &ArrowExpr) {}
fn visit_class_method(&mut self, _: &ClassMethod) {}
fn visit_constructor(&mut self, _: &Constructor) {}
fn visit_continue_stmt(&mut self, n: &ContinueStmt) {
n.visit_children_with(self);
if let Some(label) = &n.label {
self.found_continue_with_label |= self
.target_label
.as_ref()
.map_or(false, |l| *l == label.sym);
}
}
fn visit_function(&mut self, _: &Function) {}
fn visit_getter_prop(&mut self, _: &GetterProp) {}
fn visit_setter_prop(&mut self, _: &SetterProp) {}
fn visit_yield_expr(&mut self, n: &YieldExpr) {
n.visit_children_with(self);
self.found_yield = true;
}
}
/// This method returns true only if `T` is `var`. (Not `const` or `let`)
pub(crate) fn is_hoisted_var_decl_without_init<T>(t: &T) -> bool
where
T: StmtLike,
{
let var = match t.as_stmt() {
Some(Stmt::Decl(Decl::Var(v)))
if matches!(
&**v,
VarDecl {
kind: VarDeclKind::Var,
..
}
) =>
{
v
}
_ => return false,
};
var.decls.iter().all(|decl| decl.init.is_none())
}
pub(crate) trait IsModuleItem {
fn is_module_item() -> bool;
}
impl IsModuleItem for Stmt {
fn is_module_item() -> bool {
false
}
}
impl IsModuleItem for ModuleItem {
fn is_module_item() -> bool {
true
}
}
pub trait ValueExt<T>: Into<Value<T>> {
fn opt(self) -> Option<T> {
match self.into() {
Value::Known(v) => Some(v),
_ => None,
}
}
}
impl<T> ValueExt<T> for Value<T> {}
pub struct DeepThisExprVisitor {
found: bool,
}
impl Visit for DeepThisExprVisitor {
noop_visit_type!();
fn visit_this_expr(&mut self, _: &ThisExpr) {
self.found = true;
}
}
pub fn deeply_contains_this_expr<N>(body: &N) -> bool
where
N: VisitWith<DeepThisExprVisitor>,
{
let mut visitor = DeepThisExprVisitor { found: false };
body.visit_with(&mut visitor);
visitor.found
}
#[derive(Default)]
pub(crate) struct IdentUsageCollector {
ids: FxHashSet<Id>,
ignore_nested: bool,
}
impl Visit for IdentUsageCollector {
noop_visit_type!();
visit_obj_and_computed!();
fn visit_block_stmt_or_expr(&mut self, n: &BlockStmtOrExpr) {
if self.ignore_nested {
return;
}
n.visit_children_with(self);
}
fn visit_constructor(&mut self, n: &Constructor) {
if self.ignore_nested {
return;
}
n.visit_children_with(self);
}
fn visit_function(&mut self, n: &Function) {
if self.ignore_nested {
return;
}
n.visit_children_with(self);
}
fn visit_getter_prop(&mut self, n: &GetterProp) {
if self.ignore_nested {
return;
}
n.visit_children_with(self);
}
fn visit_setter_prop(&mut self, n: &SetterProp) {
if self.ignore_nested {
return;
}
n.visit_children_with(self);
}
fn visit_ident(&mut self, n: &Ident) {
self.ids.insert(n.to_id());
}
fn visit_prop_name(&mut self, n: &PropName) {
if let PropName::Computed(..) = n {
n.visit_children_with(self);
}
}
}
#[derive(Default)]
pub(crate) struct CapturedIdCollector {
ids: FxHashSet<Id>,
is_nested: bool,
}
impl Visit for CapturedIdCollector {
noop_visit_type!();
visit_obj_and_computed!();
fn visit_block_stmt_or_expr(&mut self, n: &BlockStmtOrExpr) {
let old = self.is_nested;
self.is_nested = true;
n.visit_children_with(self);
self.is_nested = old;
}
fn visit_constructor(&mut self, n: &Constructor) {
let old = self.is_nested;
self.is_nested = true;
n.visit_children_with(self);
self.is_nested = old;
}
fn visit_function(&mut self, n: &Function) {
let old = self.is_nested;
self.is_nested = true;
n.visit_children_with(self);
self.is_nested = old;
}
fn visit_ident(&mut self, n: &Ident) {
if self.is_nested {
self.ids.insert(n.to_id());
}
}
fn visit_prop_name(&mut self, n: &PropName) {
if let PropName::Computed(..) = n {
n.visit_children_with(self);
}
}
}
pub(crate) fn idents_captured_by<N>(n: &N) -> FxHashSet<Id>
where
N: VisitWith<CapturedIdCollector>,
{
let mut v = CapturedIdCollector {
is_nested: false,
..Default::default()
};
n.visit_with(&mut v);
v.ids
}
pub(crate) fn idents_used_by<N>(n: &N) -> FxHashSet<Id>
where
N: VisitWith<IdentUsageCollector>,
{
let mut v = IdentUsageCollector {
ignore_nested: false,
..Default::default()
};
n.visit_with(&mut v);
v.ids
}
pub(crate) fn idents_used_by_ignoring_nested<N>(n: &N) -> FxHashSet<Id>
where
N: VisitWith<IdentUsageCollector>,
{
let mut v = IdentUsageCollector {
ignore_nested: true,
..Default::default()
};
n.visit_with(&mut v);
v.ids
}
pub fn now() -> Option<Instant> {
#[cfg(target_arch = "wasm32")]
{
None
}
#[cfg(not(target_arch = "wasm32"))]
{
Some(Instant::now())
}
}
pub(crate) fn contains_eval<N>(node: &N, include_with: bool) -> bool
where
N: VisitWith<EvalFinder>,
{
let mut v = EvalFinder {
found: false,
include_with,
};
node.visit_with(&mut v);
v.found
}
pub(crate) struct EvalFinder {
found: bool,
include_with: bool,
}
impl Visit for EvalFinder {
noop_visit_type!();
visit_obj_and_computed!();
fn visit_expr(&mut self, n: &Expr) {
maybe_grow_default(|| n.visit_children_with(self));
}
fn visit_ident(&mut self, i: &Ident) {
if i.sym == "eval" {
self.found = true;
}
}
fn visit_with_stmt(&mut self, s: &WithStmt) {
if self.include_with {
self.found = true;
} else {
s.visit_children_with(self);
}
}
}
#[allow(unused)]
pub(crate) fn dump_program(p: &Program) -> String {
#[cfg(feature = "debug")]
{
force_dump_program(p)
}
#[cfg(not(feature = "debug"))]
{
String::new()
}
}
pub(crate) fn force_dump_program(p: &Program) -> String {
let _noop_sub = tracing::subscriber::set_default(tracing::subscriber::NoSubscriber::default());
crate::debug::dump(
&p.clone()
.apply(fixer(None))
.apply(hygiene())
.apply(visit_mut_pass(DropSpan {})),
true,
)
}
#[cfg(feature = "concurrent")]
#[macro_export(local_inner_macros)]
#[allow(clippy::crate_in_macro_def)]
macro_rules! maybe_par {
($prefix:ident.$name:ident.iter().$operator:ident($($rest:expr)*), $threshold:expr) => {
if $prefix.$name.len() >= $threshold {
use rayon::prelude::*;
$prefix.$name.par_iter().$operator($($rest)*)
} else {
$prefix.$name.iter().$operator($($rest)*)
}
};
($prefix:ident.$name:ident.into_iter().$operator:ident($($rest:expr)*), $threshold:expr) => {
if $prefix.$name.len() >= $threshold {
use rayon::prelude::*;
$prefix.$name.into_par_iter().$operator($($rest)*)
} else {
$prefix.$name.into_iter().$operator($($rest)*)
}
};
($name:ident.iter().$operator:ident($($rest:expr)*), $threshold:expr) => {
if $name.len() >= $threshold {
use rayon::prelude::*;
$name.par_iter().$operator($($rest)*)
} else {
$name.iter().$operator($($rest)*)
}
};
($name:ident.into_iter().$operator:ident($($rest:expr)*), $threshold:expr) => {
if $name.len() >= $threshold {
use rayon::prelude::*;
$name.into_par_iter().$operator($($rest)*)
} else {
$name.into_iter().$operator($($rest)*)
}
};
($name:ident.iter_mut().$operator:ident($($rest:expr)*), $threshold:expr) => {
if $name.len() >= $threshold {
use rayon::prelude::*;
$name.par_iter_mut().$operator($($rest)*)
} else {
$name.iter_mut().$operator($($rest)*)
}
};
($name:ident.iter().$operator:ident($($rest:expr)*).$operator2:ident($($rest2:expr)*), $threshold:expr) => {
if $name.len() >= $threshold {
use rayon::prelude::*;
$name.par_iter().$operator($($rest)*).$operator2($($rest2)*)
} else {
$name.iter().$operator($($rest)*).$operator2($($rest2)*)
}
};
($name:ident.into_iter().$operator:ident($($rest:expr)*).$operator2:ident($($rest2:expr)*), $threshold:expr) => {
if $name.len() >= $threshold {
use rayon::prelude::*;
$name.into_par_iter().$operator($($rest)*).$operator2($($rest2)*)
} else {
$name.into_iter().$operator($($rest)*).$operator2($($rest2)*)
}
};
($name:ident.iter_mut().$operator:ident($($rest:expr)*).$operator2:ident($($rest2:expr)*), $threshold:expr) => {
if $name.len() >= $threshold {
use rayon::prelude::*;
$name.par_iter_mut().$operator($($rest)*).$operator2($($rest2)*)
} else {
$name.iter_mut().$operator($($rest)*).$operator2($($rest2)*)
}
};
($name:ident.iter().$operator:ident($($rest:expr)*).$operator2:ident::<$t:ty>($($rest2:expr)*), $threshold:expr) => {
if $name.len() >= $threshold {
use rayon::prelude::*;
$name.par_iter().$operator($($rest)*).$operator2::<$t>($($rest2)*)
} else {
$name.iter().$operator($($rest)*).$operator2::<$t>($($rest2)*)
}
};
($name:ident.iter().$operator:ident($($rest:expr)*).$operator2:ident($($rest2:expr)*).$operator3:ident($($rest3:expr)*), $threshold:expr) => {
if $name.len() >= $threshold {
use rayon::prelude::*;
$name.par_iter().$operator($($rest)*).$operator2($($rest2)*).$operator3($($rest3)*)
} else {
$name.iter().$operator($($rest)*).$operator2($($rest2)*).$operator3($($rest3)*)
}
};
}
#[cfg(not(feature = "concurrent"))]
#[macro_export(local_inner_macros)]
#[allow(clippy::crate_in_macro_def)]
macro_rules! maybe_par {
($prefix:ident.$name:ident.iter().$operator:ident($($rest:expr)*), $threshold:expr) => {
$prefix.$name.iter().$operator($($rest)*)
};
($prefix:ident.$name:ident.into_iter().$operator:ident($($rest:expr)*), $threshold:expr) => {
$prefix.$name.into_iter().$operator($($rest)*)
};
($name:ident.iter().$operator:ident($($rest:expr)*), $threshold:expr) => {
$name.iter().$operator($($rest)*)
};
($name:ident.into_iter().$operator:ident($($rest:expr)*), $threshold:expr) => {
$name.into_iter().$operator($($rest)*)
};
($name:ident.iter_mut().$operator:ident($($rest:expr)*), $threshold:expr) => {
$name.iter_mut().$operator($($rest)*)
};
($name:ident.iter().$operator:ident($($rest:expr)*).$operator2:ident($($rest2:expr)*), $threshold:expr) => {
$name.iter().$operator($($rest)*).$operator2($($rest2)*)
};
($name:ident.into_iter().$operator:ident($($rest:expr)*).$operator2:ident($($rest2:expr)*), $threshold:expr) => {
$name.into_iter().$operator($($rest)*).$operator2($($rest2)*)
};
($name:ident.iter_mut().$operator:ident($($rest:expr)*).$operator2:ident($($rest2:expr)*), $threshold:expr) => {
$name.iter_mut().$operator($($rest)*).$operator2($($rest2)*)
};
($name:ident.iter().$operator:ident($($rest:expr)*).$operator2:ident::<$t:ty>($($rest2:expr)*), $threshold:expr) => {
$name.iter().$operator($($rest)*).$operator2::<$t>($($rest2)*)
};
($name:ident.iter().$operator:ident($($rest:expr)*).$operator2:ident($($rest2:expr)*).$operator3:ident($($rest3:expr)*), $threshold:expr) => {
$name.iter().$operator($($rest)*).$operator2($($rest2)*).$operator3($($rest3)*)
};
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/util/size.rs | Rust | use num_bigint::{BigInt as BigIntValue, Sign};
use swc_common::SyntaxContext;
use swc_ecma_ast::*;
/// Give a rough size for everything
pub trait Size {
fn size(&self) -> usize;
}
impl Size for Lit {
fn size(&self) -> usize {
match self {
Lit::Str(s) => s.value.len() + 2,
// would be !0 or !1
Lit::Bool(_) => 2,
Lit::Null(_) => 4,
Lit::Num(num) => num.value.size(),
Lit::BigInt(i) => i.value.size(),
Lit::Regex(r) => r.exp.len(),
Lit::JSXText(s) => s.value.len(),
}
}
}
impl Size for UnaryOp {
fn size(&self) -> usize {
use UnaryOp::*;
match self {
Minus | Plus | Bang | Tilde => 1,
TypeOf => 7,
Void => 5,
Delete => 7,
}
}
}
impl Size for UpdateOp {
fn size(&self) -> usize {
2
}
}
impl Size for BinaryOp {
fn size(&self) -> usize {
use BinaryOp::*;
match self {
Lt | Gt | Add | Sub | Mul | Div | Mod | BitOr | BitXor | BitAnd | EqEq | NotEq
| LtEq | GtEq | LShift | RShift | LogicalOr | LogicalAnd | Exp | NullishCoalescing
| EqEqEq | NotEqEq | ZeroFillRShift => self.as_str().len(),
In => 4,
InstanceOf => 12,
}
}
}
impl Size for AssignOp {
fn size(&self) -> usize {
self.as_str().len()
}
}
impl Size for PrivateName {
fn size(&self) -> usize {
// priv name can be mangled
2
}
}
// TODO: optimize
impl Size for f64 {
fn size(&self) -> usize {
if self.fract() == 0.0 {
self.log10().ceil() as usize + 1
} else {
self.to_string().len()
}
}
}
#[allow(clippy::bool_to_int_with_if)]
impl Size for BigIntValue {
fn size(&self) -> usize {
let sign = if let Sign::Minus = self.sign() { 1 } else { 0 };
// bits is bascially log2
// use this until https://github.com/rust-num/num-bigint/issues/57
let value = ((self.bits() as f64) / 10.0_f64.log2()).ceil() as usize + 1;
sign + value + 1 // n
}
}
/// Give a rough size for everything
pub trait SizeWithCtxt {
fn size(&self, unresolved: SyntaxContext) -> usize;
}
const TODO: usize = 10000;
impl SizeWithCtxt for Expr {
fn size(&self, unresolved: SyntaxContext) -> usize {
match self {
Expr::Lit(lit) => lit.size(),
Expr::Ident(id) => id.size(unresolved),
Expr::Bin(BinExpr {
op, left, right, ..
}) => op.size() + left.size(unresolved) + right.size(unresolved),
Expr::Unary(UnaryExpr { arg, op, .. }) => op.size() + arg.size(unresolved),
Expr::Call(CallExpr { callee, args, .. }) => {
callee.size(unresolved) + args.size(unresolved) + 2
}
Expr::New(NewExpr { callee, args, .. }) => {
args.as_ref().map_or(0, |args| args.size(unresolved) + 2)
+ 4
+ callee.size(unresolved)
}
Expr::Member(m) => m.obj.size(unresolved) + m.prop.size(unresolved),
Expr::SuperProp(s) => 6 + s.prop.size(unresolved),
Expr::Update(e) => e.arg.size(unresolved) + e.op.size(),
Expr::Assign(AssignExpr {
op, left, right, ..
}) => left.size(unresolved) + op.size() + right.size(unresolved),
Expr::Seq(e) => {
e.exprs
.iter()
.map(|v| v.size(unresolved) + 1)
.sum::<usize>()
- 1
}
Expr::This(_) => 4,
Expr::Array(a) => 2 + a.elems.size(unresolved),
Expr::Object(o) => 2 + o.props.size(unresolved),
Expr::Yield(YieldExpr { arg, delegate, .. }) => {
6 + *delegate as usize + arg.as_ref().map_or(0, |a| a.size(unresolved))
}
Expr::Await(a) => 6 + a.arg.size(unresolved),
Expr::Cond(CondExpr {
test, cons, alt, ..
}) => test.size(unresolved) + 1 + cons.size(unresolved) + 1 + alt.size(unresolved),
Expr::Tpl(t) => t.size(unresolved),
Expr::TaggedTpl(t) => t.tag.size(unresolved) + t.tpl.size(unresolved),
Expr::Arrow(ArrowExpr {
params,
body,
is_async,
..
}) => match &**body {
BlockStmtOrExpr::BlockStmt(_) => TODO,
BlockStmtOrExpr::Expr(e) => {
let p = match ¶ms[..] {
[] => 2,
[Pat::Ident(_)] => 1,
_ => 2 + params.size(unresolved),
};
let a = if *is_async {
5 + usize::from(params.len() != 1)
} else {
0
};
p + a + 2 + e.size(unresolved)
}
},
Expr::Fn(_) => TODO,
Expr::Class(_) => TODO,
Expr::MetaProp(m) => match m.kind {
MetaPropKind::NewTarget => 10,
MetaPropKind::ImportMeta => 11,
},
Expr::PrivateName(p) => p.size(),
Expr::OptChain(p) => match &*p.base {
OptChainBase::Member(m) => 1 + m.obj.size(unresolved) + m.prop.size(unresolved),
OptChainBase::Call(c) => {
1 + c.callee.size(unresolved) + c.args.size(unresolved) + 2
}
},
Expr::Paren(p) => 2 + p.expr.size(unresolved),
Expr::Invalid(_) => 0,
Expr::JSXMember(_) => TODO,
Expr::JSXNamespacedName(_) => TODO,
Expr::JSXEmpty(_) => TODO,
Expr::JSXElement(_) => TODO,
Expr::JSXFragment(_) => TODO,
Expr::TsTypeAssertion(_) => TODO,
Expr::TsConstAssertion(_) => TODO,
Expr::TsNonNull(_) => TODO,
Expr::TsAs(_) => TODO,
Expr::TsInstantiation(_) => TODO,
Expr::TsSatisfies(_) => TODO,
}
}
}
impl SizeWithCtxt for Ident {
fn size(&self, unresolved: SyntaxContext) -> usize {
if self.ctxt == unresolved {
self.sym.len()
} else {
1
}
}
}
impl SizeWithCtxt for Callee {
fn size(&self, unresolved: SyntaxContext) -> usize {
match self {
Callee::Super(_) => 5,
Callee::Import(_) => 6,
Callee::Expr(e) => e.size(unresolved),
}
}
}
impl SizeWithCtxt for ExprOrSpread {
fn size(&self, unresolved: SyntaxContext) -> usize {
let mut c = 0;
if self.spread.is_some() {
c += 3;
}
c += self.expr.size(unresolved);
c
}
}
impl SizeWithCtxt for MemberProp {
fn size(&self, unresolved: SyntaxContext) -> usize {
match self {
MemberProp::Ident(id) => 1 + id.sym.len(),
MemberProp::PrivateName(priv_name) => 1 + priv_name.size(),
MemberProp::Computed(c) => 2 + c.expr.size(unresolved),
}
}
}
impl SizeWithCtxt for SuperProp {
fn size(&self, unresolved: SyntaxContext) -> usize {
match self {
SuperProp::Ident(id) => 1 + id.sym.len(),
SuperProp::Computed(c) => 2 + c.expr.size(unresolved),
}
}
}
impl SizeWithCtxt for Pat {
fn size(&self, unresolved: SyntaxContext) -> usize {
match self {
Pat::Ident(id) => id.size(unresolved),
Pat::Array(a) => 2 + a.elems.size(unresolved),
Pat::Rest(r) => 3 + r.arg.size(unresolved),
Pat::Object(o) => 2 + o.props.size(unresolved),
Pat::Assign(a) => a.left.size(unresolved) + 1 + a.right.size(unresolved),
Pat::Invalid(_) => 0,
Pat::Expr(e) => e.size(unresolved),
}
}
}
impl SizeWithCtxt for AssignTarget {
fn size(&self, unresolved: SyntaxContext) -> usize {
match self {
AssignTarget::Simple(e) => e.size(unresolved),
AssignTarget::Pat(p) => p.size(unresolved),
}
}
}
impl SizeWithCtxt for SimpleAssignTarget {
fn size(&self, unresolved: SyntaxContext) -> usize {
match self {
SimpleAssignTarget::Ident(e) => {
if e.ctxt == unresolved {
e.sym.len()
} else {
1
}
}
SimpleAssignTarget::Member(e) => e.obj.size(unresolved) + e.prop.size(unresolved),
SimpleAssignTarget::SuperProp(e) => 6 + e.prop.size(unresolved),
SimpleAssignTarget::Paren(e) => 2 + e.expr.size(unresolved),
SimpleAssignTarget::OptChain(e) => match &*e.base {
OptChainBase::Member(m) => 1 + m.obj.size(unresolved) + m.prop.size(unresolved),
OptChainBase::Call(c) => {
1 + c.callee.size(unresolved) + c.args.size(unresolved) + 2
}
},
SimpleAssignTarget::TsAs(_)
| SimpleAssignTarget::TsSatisfies(_)
| SimpleAssignTarget::TsNonNull(_)
| SimpleAssignTarget::TsTypeAssertion(_)
| SimpleAssignTarget::TsInstantiation(_)
| SimpleAssignTarget::Invalid(_) => TODO,
}
}
}
impl SizeWithCtxt for AssignTargetPat {
fn size(&self, unresolved: SyntaxContext) -> usize {
match self {
AssignTargetPat::Array(a) => 2 + a.elems.size(unresolved),
AssignTargetPat::Object(o) => 2 + o.props.size(unresolved),
AssignTargetPat::Invalid(_) => unreachable!(),
}
}
}
impl SizeWithCtxt for PropName {
fn size(&self, unresolved: SyntaxContext) -> usize {
match self {
PropName::Ident(id) => id.sym.len(),
PropName::Str(s) => s.value.len(),
PropName::Num(n) => n.value.size(),
PropName::Computed(c) => 2 + c.expr.size(unresolved),
PropName::BigInt(n) => n.value.size(),
}
}
}
impl SizeWithCtxt for ObjectPatProp {
fn size(&self, unresolved: SyntaxContext) -> usize {
match self {
ObjectPatProp::KeyValue(k) => k.key.size(unresolved) + 1 + k.value.size(unresolved),
ObjectPatProp::Assign(a) => {
a.key.sym.len() + a.value.as_ref().map_or(0, |v| v.size(unresolved) + 1)
}
ObjectPatProp::Rest(r) => 3 + r.arg.size(unresolved),
}
}
}
impl SizeWithCtxt for PropOrSpread {
fn size(&self, unresolved: SyntaxContext) -> usize {
match self {
PropOrSpread::Spread(s) => 3 + s.expr.size(unresolved),
PropOrSpread::Prop(p) => match &**p {
Prop::Shorthand(s) => s.sym.len(),
Prop::KeyValue(KeyValueProp { key, value }) => {
key.size(unresolved) + 1 + value.size(unresolved)
}
// where is Prop::Assign valid?
Prop::Assign(_) => TODO,
Prop::Getter(_) => TODO,
Prop::Setter(_) => TODO,
Prop::Method(_) => TODO,
},
}
}
}
impl SizeWithCtxt for Tpl {
fn size(&self, unresolved: SyntaxContext) -> usize {
let Self { exprs, quasis, .. } = self;
let expr_len: usize = exprs.iter().map(|e| e.size(unresolved) + 3).sum();
let str_len: usize = quasis.iter().map(|q| q.raw.len()).sum();
2 + expr_len + str_len
}
}
impl<T: SizeWithCtxt> SizeWithCtxt for Vec<T> {
fn size(&self, unresolved: SyntaxContext) -> usize {
let mut c = 0;
for item in self.iter() {
c += item.size(unresolved) + 1; // comma
}
if !self.is_empty() {
c -= 1;
}
c
}
}
impl<T: SizeWithCtxt> SizeWithCtxt for Vec<Option<T>> {
fn size(&self, unresolved: SyntaxContext) -> usize {
let mut c = 0;
for item in self.iter() {
c += 1; // comma
if let Some(item) = item {
c += item.size(unresolved); // extra comma
}
}
c -= match self.last() {
// if empty or last is none, no need to remove dangling comma
None | Some(None) => 0,
_ => 1,
};
c
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/src/util/sort.rs | Rust | use std::cmp::Ordering;
pub(crate) fn is_sorted_by<I, T, F>(mut items: I, mut compare: F) -> bool
where
I: Iterator<Item = T>,
T: Copy,
F: FnMut(&T, &T) -> Option<Ordering>,
{
let last = match items.next() {
Some(e) => e,
None => return true,
};
items
.try_fold(last, |last, curr| {
if let Some(Ordering::Greater) | None = compare(&last, &curr) {
return Err(());
}
Ok(curr)
})
.is_ok()
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/benches-full/d3.js | JavaScript | !// https://d3js.org v6.3.1 Copyright 2020 Mike Bostock
function(global, factory) {
'object' == typeof exports && 'undefined' != typeof module ? factory(exports) : 'function' == typeof define && define.amd ? define([
'exports'
], factory) : factory((global = 'undefined' != typeof globalThis ? globalThis : global || self).d3 = global.d3 || {});
}(this, function(exports1) {
'use strict';
function ascending(a, b) {
return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}
function bisector(f) {
let delta = f, compare = f;
function left(a, x, lo, hi) {
for(null == lo && (lo = 0), null == hi && (hi = a.length); lo < hi;){
const mid = lo + hi >>> 1;
0 > compare(a[mid], x) ? lo = mid + 1 : hi = mid;
}
return lo;
}
return 1 === f.length && (delta = (d, x)=>f(d) - x, compare = (d, x)=>ascending(f(d), x)), {
left,
center: function(a, x, lo, hi) {
null == lo && (lo = 0), null == hi && (hi = a.length);
const i = left(a, x, lo, hi - 1);
return i > lo && delta(a[i - 1], x) > -delta(a[i], x) ? i - 1 : i;
},
right: function(a, x, lo, hi) {
for(null == lo && (lo = 0), null == hi && (hi = a.length); lo < hi;){
const mid = lo + hi >>> 1;
compare(a[mid], x) > 0 ? hi = mid : lo = mid + 1;
}
return lo;
}
};
}
function number(x) {
return null === x ? NaN : +x;
}
const ascendingBisect = bisector(ascending), bisectRight = ascendingBisect.right, bisectLeft = ascendingBisect.left, bisectCenter = bisector(number).center;
function count(values, valueof) {
let count = 0;
if (void 0 === valueof) for (let value of values)null != value && (value *= 1) >= value && ++count;
else {
let index = -1;
for (let value of values)null != (value = valueof(value, ++index, values)) && (value *= 1) >= value && ++count;
}
return count;
}
function length(array) {
return 0 | array.length;
}
function empty(length) {
return !(length > 0);
}
function arrayify(values) {
return "object" != typeof values || "length" in values ? values : Array.from(values);
}
function variance(values, valueof) {
let delta, count = 0, mean = 0, sum = 0;
if (void 0 === valueof) for (let value of values)null != value && (value *= 1) >= value && (delta = value - mean, mean += delta / ++count, sum += delta * (value - mean));
else {
let index = -1;
for (let value of values)null != (value = valueof(value, ++index, values)) && (value *= 1) >= value && (delta = value - mean, mean += delta / ++count, sum += delta * (value - mean));
}
if (count > 1) return sum / (count - 1);
}
function deviation(values, valueof) {
const v = variance(values, valueof);
return v ? Math.sqrt(v) : v;
}
function extent(values, valueof) {
let min, max;
if (void 0 === valueof) for (const value of values)null != value && (void 0 === min ? value >= value && (min = max = value) : (min > value && (min = value), max < value && (max = value)));
else {
let index = -1;
for (let value of values)null != (value = valueof(value, ++index, values)) && (void 0 === min ? value >= value && (min = max = value) : (min > value && (min = value), max < value && (max = value)));
}
return [
min,
max
];
}
// https://github.com/python/cpython/blob/a74eea238f5baba15797e2e8b570d153bc8690a7/Modules/mathmodule.c#L1423
class Adder {
constructor(){
this._partials = new Float64Array(32), this._n = 0;
}
add(x) {
const p = this._partials;
let i = 0;
for(let j = 0; j < this._n && j < 32; j++){
const y = p[j], hi = x + y, lo = Math.abs(x) < Math.abs(y) ? x - (hi - y) : y - (hi - x);
lo && (p[i++] = lo), x = hi;
}
return p[i] = x, this._n = i + 1, this;
}
valueOf() {
const p = this._partials;
let n = this._n, x, y, lo, hi = 0;
if (n > 0) {
for(hi = p[--n]; n > 0 && (hi = (x = hi) + (y = p[--n]), !(lo = y - (hi - x))););
n > 0 && (lo < 0 && p[n - 1] < 0 || lo > 0 && p[n - 1] > 0) && (x = hi + (y = 2 * lo), y == x - hi && (hi = x));
}
return hi;
}
}
function identity(x) {
return x;
}
function unique(values) {
if (1 !== values.length) throw Error("duplicate key");
return values[0];
}
function nest(values, map, reduce, keys) {
return function regroup(values, i) {
if (i >= keys.length) return reduce(values);
const groups = new Map(), keyof = keys[i++];
let index = -1;
for (const value of values){
const key = keyof(value, ++index, values), group = groups.get(key);
group ? group.push(value) : groups.set(key, [
value
]);
}
for (const [key, values] of groups)groups.set(key, regroup(values, i));
return map(groups);
}(values, 0);
}
var slice = Array.prototype.slice;
function constant(x) {
return function() {
return x;
};
}
var e10 = Math.sqrt(50), e5 = Math.sqrt(10), e2 = Math.sqrt(2);
function ticks(start, stop, count) {
var reverse, n, ticks, step, i = -1;
if (count *= 1, (start *= 1) == (stop *= 1) && count > 0) return [
start
];
if ((reverse = stop < start) && (n = start, start = stop, stop = n), 0 === (step = tickIncrement(start, stop, count)) || !isFinite(step)) return [];
if (step > 0) for(start = Math.ceil(start / step), ticks = Array(n = Math.ceil((stop = Math.floor(stop / step)) - start + 1)); ++i < n;)ticks[i] = (start + i) * step;
else for(start = Math.ceil(start * (step = -step)), ticks = Array(n = Math.ceil((stop = Math.floor(stop * step)) - start + 1)); ++i < n;)ticks[i] = (start + i) / step;
return reverse && ticks.reverse(), ticks;
}
function tickIncrement(start, stop, count) {
var step = (stop - start) / Math.max(0, count), power = Math.floor(Math.log(step) / Math.LN10), error = step / Math.pow(10, power);
return power >= 0 ? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power) : -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1);
}
function tickStep(start, stop, count) {
var step0 = Math.abs(stop - start) / Math.max(0, count), step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)), error = step0 / step1;
return error >= e10 ? step1 *= 10 : error >= e5 ? step1 *= 5 : error >= e2 && (step1 *= 2), stop < start ? -step1 : step1;
}
function nice(start, stop, count) {
let prestep;
for(;;){
const step = tickIncrement(start, stop, count);
if (step === prestep || 0 === step || !isFinite(step)) return [
start,
stop
];
step > 0 ? (start = Math.floor(start / step) * step, stop = Math.ceil(stop / step) * step) : step < 0 && (start = Math.ceil(start * step) / step, stop = Math.floor(stop * step) / step), prestep = step;
}
}
function thresholdSturges(values) {
return Math.ceil(Math.log(count(values)) / Math.LN2) + 1;
}
function bin() {
var value = identity, domain = extent, threshold = thresholdSturges;
function histogram(data) {
Array.isArray(data) || (data = Array.from(data));
var i, x, n = data.length, values = Array(n);
for(i = 0; i < n; ++i)values[i] = value(data[i], i, data);
var xz = domain(values), x0 = xz[0], x1 = xz[1], tz = threshold(values, x0, x1);
// Convert number of thresholds into uniform thresholds, and nice the
// default domain accordingly.
if (!Array.isArray(tz)) {
const max = x1, tn = +tz;
// If the last threshold is coincident with the domain’s upper bound, the
// last bin will be zero-width. If the default domain is used, and this
// last threshold is coincident with the maximum input value, we can
// extend the niced upper bound by one tick to ensure uniform bin widths;
// otherwise, we simply remove the last threshold. Note that we don’t
// coerce values or the domain to numbers, and thus must be careful to
// compare order (>=) rather than strict equality (===)!
if (domain === extent && ([x0, x1] = nice(x0, x1, tn)), (tz = ticks(x0, x1, tn))[tz.length - 1] >= x1) {
if (max >= x1 && domain === extent) {
const step = tickIncrement(x0, x1, tn);
isFinite(step) && (step > 0 ? x1 = (Math.floor(x1 / step) + 1) * step : step < 0 && (x1 = -((Math.ceil(-(x1 * step)) + 1) / step)));
} else tz.pop();
}
}
for(// Remove any thresholds outside the domain.
var m = tz.length; tz[0] <= x0;)tz.shift(), --m;
for(; tz[m - 1] > x1;)tz.pop(), --m;
var bin, bins = Array(m + 1);
// Initialize bins.
for(i = 0; i <= m; ++i)(bin = bins[i] = []).x0 = i > 0 ? tz[i - 1] : x0, bin.x1 = i < m ? tz[i] : x1;
// Assign data to bins by value, ignoring any outside the domain.
for(i = 0; i < n; ++i)x0 <= (x = values[i]) && x <= x1 && bins[bisectRight(tz, x, 0, m)].push(data[i]);
return bins;
}
return histogram.value = function(_) {
return arguments.length ? (value = "function" == typeof _ ? _ : constant(_), histogram) : value;
}, histogram.domain = function(_) {
return arguments.length ? (domain = "function" == typeof _ ? _ : constant([
_[0],
_[1]
]), histogram) : domain;
}, histogram.thresholds = function(_) {
return arguments.length ? (threshold = "function" == typeof _ ? _ : Array.isArray(_) ? constant(slice.call(_)) : constant(_), histogram) : threshold;
}, histogram;
}
function max(values, valueof) {
let max;
if (void 0 === valueof) for (const value of values)null != value && (max < value || void 0 === max && value >= value) && (max = value);
else {
let index = -1;
for (let value of values)null != (value = valueof(value, ++index, values)) && (max < value || void 0 === max && value >= value) && (max = value);
}
return max;
}
function min(values, valueof) {
let min;
if (void 0 === valueof) for (const value of values)null != value && (min > value || void 0 === min && value >= value) && (min = value);
else {
let index = -1;
for (let value of values)null != (value = valueof(value, ++index, values)) && (min > value || void 0 === min && value >= value) && (min = value);
}
return min;
}
// Based on https://github.com/mourner/quickselect
// ISC license, Copyright 2018 Vladimir Agafonkin.
function quickselect(array, k, left = 0, right = array.length - 1, compare = ascending) {
for(; right > left;){
if (right - left > 600) {
const n = right - left + 1, m = k - left + 1, z = Math.log(n), s = 0.5 * Math.exp(2 * z / 3), sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1), newLeft = Math.max(left, Math.floor(k - m * s / n + sd)), newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
quickselect(array, k, newLeft, newRight, compare);
}
const t = array[k];
let i = left, j = right;
for(swap(array, left, k), compare(array[right], t) > 0 && swap(array, left, right); i < j;){
for(swap(array, i, j), ++i, --j; 0 > compare(array[i], t);)++i;
for(; compare(array[j], t) > 0;)--j;
}
0 === compare(array[left], t) ? swap(array, left, j) : swap(array, ++j, right), j <= k && (left = j + 1), k <= j && (right = j - 1);
}
return array;
}
function swap(array, i, j) {
const t = array[i];
array[i] = array[j], array[j] = t;
}
function quantile(values, p, valueof) {
if (n = (values = Float64Array.from(function*(values, valueof) {
if (void 0 === valueof) for (let value of values)null != value && (value *= 1) >= value && (yield value);
else {
let index = -1;
for (let value of values)null != (value = valueof(value, ++index, values)) && (value *= 1) >= value && (yield value);
}
}(values, valueof))).length) {
if ((p *= 1) <= 0 || n < 2) return min(values);
if (p >= 1) return max(values);
var n, i = (n - 1) * p, i0 = Math.floor(i), value0 = max(quickselect(values, i0).subarray(0, i0 + 1));
return value0 + (min(values.subarray(i0 + 1)) - value0) * (i - i0);
}
}
function quantileSorted(values, p, valueof = number) {
if (n = values.length) {
if ((p *= 1) <= 0 || n < 2) return +valueof(values[0], 0, values);
if (p >= 1) return +valueof(values[n - 1], n - 1, values);
var n, i = (n - 1) * p, i0 = Math.floor(i), value0 = +valueof(values[i0], i0, values);
return value0 + (+valueof(values[i0 + 1], i0 + 1, values) - value0) * (i - i0);
}
}
function maxIndex(values, valueof) {
let max;
let maxIndex = -1, index = -1;
if (void 0 === valueof) for (const value of values)++index, null != value && (max < value || void 0 === max && value >= value) && (max = value, maxIndex = index);
else for (let value of values)null != (value = valueof(value, ++index, values)) && (max < value || void 0 === max && value >= value) && (max = value, maxIndex = index);
return maxIndex;
}
function merge(arrays) {
return Array.from(function*(arrays) {
for (const array of arrays)yield* array;
}(arrays));
}
function minIndex(values, valueof) {
let min;
let minIndex = -1, index = -1;
if (void 0 === valueof) for (const value of values)++index, null != value && (min > value || void 0 === min && value >= value) && (min = value, minIndex = index);
else for (let value of values)null != (value = valueof(value, ++index, values)) && (min > value || void 0 === min && value >= value) && (min = value, minIndex = index);
return minIndex;
}
function pair(a, b) {
return [
a,
b
];
}
function permute(source, keys) {
return Array.from(keys, (key)=>source[key]);
}
function sequence(start, stop, step) {
start *= 1, stop *= 1, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;
for(var i = -1, n = 0 | Math.max(0, Math.ceil((stop - start) / step)), range = Array(n); ++i < n;)range[i] = start + i * step;
return range;
}
function leastIndex(values, compare = ascending) {
let minValue;
if (1 === compare.length) return minIndex(values, compare);
let min = -1, index = -1;
for (const value of values)++index, (min < 0 ? 0 === compare(value, value) : 0 > compare(value, minValue)) && (minValue = value, min = index);
return min;
}
var shuffle = shuffler(Math.random);
function shuffler(random) {
return function(array, i0 = 0, i1 = array.length) {
let m = i1 - (i0 *= 1);
for(; m;){
const i = random() * m-- | 0, t = array[m + i0];
array[m + i0] = array[i + i0], array[i + i0] = t;
}
return array;
};
}
function transpose(matrix) {
if (!(n = matrix.length)) return [];
for(var i = -1, m = min(matrix, length$1), transpose = Array(m); ++i < m;)for(var n, j = -1, row = transpose[i] = Array(n); ++j < n;)row[j] = matrix[j][i];
return transpose;
}
function length$1(d) {
return d.length;
}
function set(values) {
return values instanceof Set ? values : new Set(values);
}
function superset(values, other) {
const iterator = values[Symbol.iterator](), set = new Set();
for (const o of other){
let value, done;
if (!set.has(o)) for(; { value, done } = iterator.next();){
if (done) return !1;
if (set.add(value), Object.is(o, value)) break;
}
}
return !0;
}
var slice$1 = Array.prototype.slice;
function identity$1(x) {
return x;
}
function translateX(x) {
return "translate(" + (x + 0.5) + ",0)";
}
function translateY(y) {
return "translate(0," + (y + 0.5) + ")";
}
function entering() {
return !this.__axis;
}
function axis(orient, scale) {
var tickArguments = [], tickValues = null, tickFormat = null, tickSizeInner = 6, tickSizeOuter = 6, tickPadding = 3, k = 1 === orient || 4 === orient ? -1 : 1, x = 4 === orient || 2 === orient ? "x" : "y", transform = 1 === orient || 3 === orient ? translateX : translateY;
function axis(context) {
var values = null == tickValues ? scale.ticks ? scale.ticks.apply(scale, tickArguments) : scale.domain() : tickValues, format = null == tickFormat ? scale.tickFormat ? scale.tickFormat.apply(scale, tickArguments) : identity$1 : tickFormat, spacing = Math.max(tickSizeInner, 0) + tickPadding, range = scale.range(), range0 = +range[0] + 0.5, range1 = +range[range.length - 1] + 0.5, position = (scale.bandwidth ? function(scale) {
var offset = Math.max(0, scale.bandwidth() - 1) / 2; // Adjust for 0.5px offset.
return scale.round() && (offset = Math.round(offset)), function(d) {
return +scale(d) + offset;
};
} : function(scale) {
return (d)=>+scale(d);
})(scale.copy()), selection = context.selection ? context.selection() : context, path = selection.selectAll(".domain").data([
null
]), tick = selection.selectAll(".tick").data(values, scale).order(), tickExit = tick.exit(), tickEnter = tick.enter().append("g").attr("class", "tick"), line = tick.select("line"), text = tick.select("text");
path = path.merge(path.enter().insert("path", ".tick").attr("class", "domain").attr("stroke", "currentColor")), tick = tick.merge(tickEnter), line = line.merge(tickEnter.append("line").attr("stroke", "currentColor").attr(x + "2", k * tickSizeInner)), text = text.merge(tickEnter.append("text").attr("fill", "currentColor").attr(x, k * spacing).attr("dy", 1 === orient ? "0em" : 3 === orient ? "0.71em" : "0.32em")), context !== selection && (path = path.transition(context), tick = tick.transition(context), line = line.transition(context), text = text.transition(context), tickExit = tickExit.transition(context).attr("opacity", 1e-6).attr("transform", function(d) {
return isFinite(d = position(d)) ? transform(d) : this.getAttribute("transform");
}), tickEnter.attr("opacity", 1e-6).attr("transform", function(d) {
var p = this.parentNode.__axis;
return transform(p && isFinite(p = p(d)) ? p : position(d));
})), tickExit.remove(), path.attr("d", 4 === orient || 2 == orient ? tickSizeOuter ? "M" + k * tickSizeOuter + "," + range0 + "H0.5V" + range1 + "H" + k * tickSizeOuter : "M0.5," + range0 + "V" + range1 : tickSizeOuter ? "M" + range0 + "," + k * tickSizeOuter + "V0.5H" + range1 + "V" + k * tickSizeOuter : "M" + range0 + ",0.5H" + range1), tick.attr("opacity", 1).attr("transform", function(d) {
return transform(position(d));
}), line.attr(x + "2", k * tickSizeInner), text.attr(x, k * spacing).text(format), selection.filter(entering).attr("fill", "none").attr("font-size", 10).attr("font-family", "sans-serif").attr("text-anchor", 2 === orient ? "start" : 4 === orient ? "end" : "middle"), selection.each(function() {
this.__axis = position;
});
}
return axis.scale = function(_) {
return arguments.length ? (scale = _, axis) : scale;
}, axis.ticks = function() {
return tickArguments = slice$1.call(arguments), axis;
}, axis.tickArguments = function(_) {
return arguments.length ? (tickArguments = null == _ ? [] : slice$1.call(_), axis) : tickArguments.slice();
}, axis.tickValues = function(_) {
return arguments.length ? (tickValues = null == _ ? null : slice$1.call(_), axis) : tickValues && tickValues.slice();
}, axis.tickFormat = function(_) {
return arguments.length ? (tickFormat = _, axis) : tickFormat;
}, axis.tickSize = function(_) {
return arguments.length ? (tickSizeInner = tickSizeOuter = +_, axis) : tickSizeInner;
}, axis.tickSizeInner = function(_) {
return arguments.length ? (tickSizeInner = +_, axis) : tickSizeInner;
}, axis.tickSizeOuter = function(_) {
return arguments.length ? (tickSizeOuter = +_, axis) : tickSizeOuter;
}, axis.tickPadding = function(_) {
return arguments.length ? (tickPadding = +_, axis) : tickPadding;
}, axis;
}
var noop = {
value: ()=>{}
};
function dispatch() {
for(var t, i = 0, n = arguments.length, _ = {}; i < n; ++i){
if (!(t = arguments[i] + "") || t in _ || /[\s.]/.test(t)) throw Error("illegal type: " + t);
_[t] = [];
}
return new Dispatch(_);
}
function Dispatch(_) {
this._ = _;
}
function set$1(type, name, callback) {
for(var i = 0, n = type.length; i < n; ++i)if (type[i].name === name) {
type[i] = noop, type = type.slice(0, i).concat(type.slice(i + 1));
break;
}
return null != callback && type.push({
name: name,
value: callback
}), type;
}
Dispatch.prototype = dispatch.prototype = {
constructor: Dispatch,
on: function(typename, callback) {
var t, _ = this._, T = (typename + "").trim().split(/^|\s+/).map(function(t) {
var name = "", i = t.indexOf(".");
if (i >= 0 && (name = t.slice(i + 1), t = t.slice(0, i)), t && !_.hasOwnProperty(t)) throw Error("unknown type: " + t);
return {
type: t,
name: name
};
}), i = -1, n = T.length;
// If no callback was specified, return the callback of the given type and name.
if (arguments.length < 2) {
for(; ++i < n;)if ((t = (typename = T[i]).type) && (t = function(type, name) {
for(var c, i = 0, n = type.length; i < n; ++i)if ((c = type[i]).name === name) return c.value;
}(_[t], typename.name))) return t;
return;
}
// If a type was specified, set the callback for the given type and name.
// Otherwise, if a null callback was specified, remove callbacks of the given name.
if (null != callback && "function" != typeof callback) throw Error("invalid callback: " + callback);
for(; ++i < n;)if (t = (typename = T[i]).type) _[t] = set$1(_[t], typename.name, callback);
else if (null == callback) for(t in _)_[t] = set$1(_[t], typename.name, null);
return this;
},
copy: function() {
var copy = {}, _ = this._;
for(var t in _)copy[t] = _[t].slice();
return new Dispatch(copy);
},
call: function(type, that) {
if ((n = arguments.length - 2) > 0) for(var n, t, args = Array(n), i = 0; i < n; ++i)args[i] = arguments[i + 2];
if (!this._.hasOwnProperty(type)) throw Error("unknown type: " + type);
for(t = this._[type], i = 0, n = t.length; i < n; ++i)t[i].value.apply(that, args);
},
apply: function(type, that, args) {
if (!this._.hasOwnProperty(type)) throw Error("unknown type: " + type);
for(var t = this._[type], i = 0, n = t.length; i < n; ++i)t[i].value.apply(that, args);
}
};
var xhtml = "http://www.w3.org/1999/xhtml", namespaces = {
svg: "http://www.w3.org/2000/svg",
xhtml: xhtml,
xlink: "http://www.w3.org/1999/xlink",
xml: "http://www.w3.org/XML/1998/namespace",
xmlns: "http://www.w3.org/2000/xmlns/"
};
function namespace(name) {
var prefix = name += "", i = prefix.indexOf(":");
return i >= 0 && "xmlns" !== (prefix = name.slice(0, i)) && (name = name.slice(i + 1)), namespaces.hasOwnProperty(prefix) ? {
space: namespaces[prefix],
local: name
} : name; // eslint-disable-line no-prototype-builtins
}
function creator(name) {
var fullname = namespace(name);
return (fullname.local ? function(fullname) {
return function() {
return this.ownerDocument.createElementNS(fullname.space, fullname.local);
};
} : function(name) {
return function() {
var document1 = this.ownerDocument, uri = this.namespaceURI;
return uri === xhtml && document1.documentElement.namespaceURI === xhtml ? document1.createElement(name) : document1.createElementNS(uri, name);
};
})(fullname);
}
function none() {}
function selector(selector) {
return null == selector ? none : function() {
return this.querySelector(selector);
};
}
function array$1(x) {
return "object" == typeof x && "length" in x ? x // Array, TypedArray, NodeList, array-like
: Array.from(x); // Map, Set, iterable, string, or anything else
}
function empty$1() {
return [];
}
function selectorAll(selector) {
return null == selector ? empty$1 : function() {
return this.querySelectorAll(selector);
};
}
function matcher(selector) {
return function() {
return this.matches(selector);
};
}
function childMatcher(selector) {
return function(node) {
return node.matches(selector);
};
}
var find = Array.prototype.find;
function childFirst() {
return this.firstElementChild;
}
var filter$1 = Array.prototype.filter;
function children() {
return this.children;
}
function sparse(update) {
return Array(update.length);
}
function EnterNode(parent, datum) {
this.ownerDocument = parent.ownerDocument, this.namespaceURI = parent.namespaceURI, this._next = null, this._parent = parent, this.__data__ = datum;
}
function bindIndex(parent, group, enter, update, exit, data) {
// Put any non-null nodes that fit into update.
// Put any null nodes into enter.
// Put any remaining data into enter.
for(var node, i = 0, groupLength = group.length, dataLength = data.length; i < dataLength; ++i)(node = group[i]) ? (node.__data__ = data[i], update[i] = node) : enter[i] = new EnterNode(parent, data[i]);
// Put any non-null nodes that don’t fit into exit.
for(; i < groupLength; ++i)(node = group[i]) && (exit[i] = node);
}
function bindKey(parent, group, enter, update, exit, data, key) {
var i, node, keyValue, nodeByKeyValue = new Map, groupLength = group.length, dataLength = data.length, keyValues = Array(groupLength);
// Compute the key for each node.
// If multiple nodes have the same key, the duplicates are added to exit.
for(i = 0; i < groupLength; ++i)(node = group[i]) && (keyValues[i] = keyValue = key.call(node, node.__data__, i, group) + "", nodeByKeyValue.has(keyValue) ? exit[i] = node : nodeByKeyValue.set(keyValue, node));
// Compute the key for each datum.
// If there a node associated with this key, join and add it to update.
// If there is not (or the key is a duplicate), add it to enter.
for(i = 0; i < dataLength; ++i)keyValue = key.call(parent, data[i], i, data) + "", (node = nodeByKeyValue.get(keyValue)) ? (update[i] = node, node.__data__ = data[i], nodeByKeyValue.delete(keyValue)) : enter[i] = new EnterNode(parent, data[i]);
// Add any remaining nodes that were not bound to data to exit.
for(i = 0; i < groupLength; ++i)(node = group[i]) && nodeByKeyValue.get(keyValues[i]) === node && (exit[i] = node);
}
function datum(node) {
return node.__data__;
}
function ascending$1(a, b) {
return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
}
function defaultView(node) {
return node.ownerDocument && node.ownerDocument.defaultView // node is a Node
|| node.document && node // node is a Window
|| node.defaultView; // node is a Document
}
function styleValue(node, name) {
return node.style.getPropertyValue(name) || defaultView(node).getComputedStyle(node, null).getPropertyValue(name);
}
function classArray(string) {
return string.trim().split(/^|\s+/);
}
function classList(node) {
return node.classList || new ClassList(node);
}
function ClassList(node) {
this._node = node, this._names = classArray(node.getAttribute("class") || "");
}
function classedAdd(node, names) {
for(var list = classList(node), i = -1, n = names.length; ++i < n;)list.add(names[i]);
}
function classedRemove(node, names) {
for(var list = classList(node), i = -1, n = names.length; ++i < n;)list.remove(names[i]);
}
function textRemove() {
this.textContent = "";
}
function htmlRemove() {
this.innerHTML = "";
}
function raise() {
this.nextSibling && this.parentNode.appendChild(this);
}
function lower() {
this.previousSibling && this.parentNode.insertBefore(this, this.parentNode.firstChild);
}
function constantNull() {
return null;
}
function remove() {
var parent = this.parentNode;
parent && parent.removeChild(this);
}
function selection_cloneShallow() {
var clone = this.cloneNode(!1), parent = this.parentNode;
return parent ? parent.insertBefore(clone, this.nextSibling) : clone;
}
function selection_cloneDeep() {
var clone = this.cloneNode(!0), parent = this.parentNode;
return parent ? parent.insertBefore(clone, this.nextSibling) : clone;
}
function onRemove(typename) {
return function() {
var on = this.__on;
if (on) {
for(var o, j = 0, i = -1, m = on.length; j < m; ++j)(o = on[j], typename.type && o.type !== typename.type || o.name !== typename.name) ? on[++i] = o : this.removeEventListener(o.type, o.listener, o.options);
++i ? on.length = i : delete this.__on;
}
};
}
function onAdd(typename, value, options) {
return function() {
var o, on = this.__on, listener = function(event) {
value.call(this, event, this.__data__);
};
if (on) {
for(var j = 0, m = on.length; j < m; ++j)if ((o = on[j]).type === typename.type && o.name === typename.name) {
this.removeEventListener(o.type, o.listener, o.options), this.addEventListener(o.type, o.listener = listener, o.options = options), o.value = value;
return;
}
}
this.addEventListener(typename.type, listener, options), o = {
type: typename.type,
name: typename.name,
value: value,
listener: listener,
options: options
}, on ? on.push(o) : this.__on = [
o
];
};
}
function dispatchEvent(node, type, params) {
var window1 = defaultView(node), event = window1.CustomEvent;
"function" == typeof event ? event = new event(type, params) : (event = window1.document.createEvent("Event"), params ? (event.initEvent(type, params.bubbles, params.cancelable), event.detail = params.detail) : event.initEvent(type, !1, !1)), node.dispatchEvent(event);
}
EnterNode.prototype = {
constructor: EnterNode,
appendChild: function(child) {
return this._parent.insertBefore(child, this._next);
},
insertBefore: function(child, next) {
return this._parent.insertBefore(child, next);
},
querySelector: function(selector) {
return this._parent.querySelector(selector);
},
querySelectorAll: function(selector) {
return this._parent.querySelectorAll(selector);
}
}, ClassList.prototype = {
add: function(name) {
0 > this._names.indexOf(name) && (this._names.push(name), this._node.setAttribute("class", this._names.join(" ")));
},
remove: function(name) {
var i = this._names.indexOf(name);
i >= 0 && (this._names.splice(i, 1), this._node.setAttribute("class", this._names.join(" ")));
},
contains: function(name) {
return this._names.indexOf(name) >= 0;
}
};
var root = [
null
];
function Selection(groups, parents) {
this._groups = groups, this._parents = parents;
}
function selection() {
return new Selection([
[
document.documentElement
]
], root);
}
function select(selector) {
return "string" == typeof selector ? new Selection([
[
document.querySelector(selector)
]
], [
document.documentElement
]) : new Selection([
[
selector
]
], root);
}
Selection.prototype = selection.prototype = {
constructor: Selection,
select: function(select) {
"function" != typeof select && (select = selector(select));
for(var groups = this._groups, m = groups.length, subgroups = Array(m), j = 0; j < m; ++j)for(var node, subnode, group = groups[j], n = group.length, subgroup = subgroups[j] = Array(n), i = 0; i < n; ++i)(node = group[i]) && (subnode = select.call(node, node.__data__, i, group)) && ("__data__" in node && (subnode.__data__ = node.__data__), subgroup[i] = subnode);
return new Selection(subgroups, this._parents);
},
selectAll: function(select) {
if ("function" == typeof select) {
var select1;
select1 = select, select = function() {
var group = select1.apply(this, arguments);
return null == group ? [] : array$1(group);
};
} else select = selectorAll(select);
for(var groups = this._groups, m = groups.length, subgroups = [], parents = [], j = 0; j < m; ++j)for(var node, group = groups[j], n = group.length, i = 0; i < n; ++i)(node = group[i]) && (subgroups.push(select.call(node, node.__data__, i, group)), parents.push(node));
return new Selection(subgroups, parents);
},
selectChild: function(match) {
var match1;
return this.select(null == match ? childFirst : (match1 = "function" == typeof match ? match : childMatcher(match), function() {
return find.call(this.children, match1);
}));
},
selectChildren: function(match) {
var match1;
return this.selectAll(null == match ? children : (match1 = "function" == typeof match ? match : childMatcher(match), function() {
return filter$1.call(this.children, match1);
}));
},
filter: function(match) {
"function" != typeof match && (match = matcher(match));
for(var groups = this._groups, m = groups.length, subgroups = Array(m), j = 0; j < m; ++j)for(var node, group = groups[j], n = group.length, subgroup = subgroups[j] = [], i = 0; i < n; ++i)(node = group[i]) && match.call(node, node.__data__, i, group) && subgroup.push(node);
return new Selection(subgroups, this._parents);
},
data: function(value, key) {
if (!arguments.length) return Array.from(this, datum);
var bind = key ? bindKey : bindIndex, parents = this._parents, groups = this._groups;
"function" != typeof value && (x = value, value = function() {
return x;
});
for(var m = groups.length, update = Array(m), enter = Array(m), exit = Array(m), j = 0; j < m; ++j){
var parent = parents[j], group = groups[j], groupLength = group.length, data = array$1(value.call(parent, parent && parent.__data__, j, parents)), dataLength = data.length, enterGroup = enter[j] = Array(dataLength), updateGroup = update[j] = Array(dataLength);
bind(parent, group, enterGroup, updateGroup, exit[j] = Array(groupLength), data, key);
// Now connect the enter nodes to their following update node, such that
// appendChild can insert the materialized enter node before this node,
// rather than at the end of the parent node.
for(var x, previous, next, i0 = 0, i1 = 0; i0 < dataLength; ++i0)if (previous = enterGroup[i0]) {
for(i0 >= i1 && (i1 = i0 + 1); !(next = updateGroup[i1]) && ++i1 < dataLength;);
previous._next = next || null;
}
}
return (update = new Selection(update, parents))._enter = enter, update._exit = exit, update;
},
enter: function() {
return new Selection(this._enter || this._groups.map(sparse), this._parents);
},
exit: function() {
return new Selection(this._exit || this._groups.map(sparse), this._parents);
},
join: function(onenter, onupdate, onexit) {
var enter = this.enter(), update = this, exit = this.exit();
return enter = "function" == typeof onenter ? onenter(enter) : enter.append(onenter + ""), null != onupdate && (update = onupdate(update)), null == onexit ? exit.remove() : onexit(exit), enter && update ? enter.merge(update).order() : update;
},
merge: function(selection) {
if (!(selection instanceof Selection)) throw Error("invalid merge");
for(var groups0 = this._groups, groups1 = selection._groups, m0 = groups0.length, m1 = groups1.length, m = Math.min(m0, m1), merges = Array(m0), j = 0; j < m; ++j)for(var node, group0 = groups0[j], group1 = groups1[j], n = group0.length, merge = merges[j] = Array(n), i = 0; i < n; ++i)(node = group0[i] || group1[i]) && (merge[i] = node);
for(; j < m0; ++j)merges[j] = groups0[j];
return new Selection(merges, this._parents);
},
selection: function() {
return this;
},
order: function() {
for(var groups = this._groups, j = -1, m = groups.length; ++j < m;)for(var node, group = groups[j], i = group.length - 1, next = group[i]; --i >= 0;)(node = group[i]) && (next && 4 ^ node.compareDocumentPosition(next) && next.parentNode.insertBefore(node, next), next = node);
return this;
},
sort: function(compare) {
function compareNode(a, b) {
return a && b ? compare(a.__data__, b.__data__) : !a - !b;
}
compare || (compare = ascending$1);
for(var groups = this._groups, m = groups.length, sortgroups = Array(m), j = 0; j < m; ++j){
for(var node, group = groups[j], n = group.length, sortgroup = sortgroups[j] = Array(n), i = 0; i < n; ++i)(node = group[i]) && (sortgroup[i] = node);
sortgroup.sort(compareNode);
}
return new Selection(sortgroups, this._parents).order();
},
call: function() {
var callback = arguments[0];
return arguments[0] = this, callback.apply(null, arguments), this;
},
nodes: function() {
return Array.from(this);
},
node: function() {
for(var groups = this._groups, j = 0, m = groups.length; j < m; ++j)for(var group = groups[j], i = 0, n = group.length; i < n; ++i){
var node = group[i];
if (node) return node;
}
return null;
},
size: function() {
let size = 0;
for (const node of this)++size; // eslint-disable-line no-unused-vars
return size;
},
empty: function() {
return !this.node();
},
each: function(callback) {
for(var groups = this._groups, j = 0, m = groups.length; j < m; ++j)for(var node, group = groups[j], i = 0, n = group.length; i < n; ++i)(node = group[i]) && callback.call(node, node.__data__, i, group);
return this;
},
attr: function(name, value) {
var fullname = namespace(name);
if (arguments.length < 2) {
var node = this.node();
return fullname.local ? node.getAttributeNS(fullname.space, fullname.local) : node.getAttribute(fullname);
}
return this.each((null == value ? fullname.local ? function(fullname) {
return function() {
this.removeAttributeNS(fullname.space, fullname.local);
};
} : function(name) {
return function() {
this.removeAttribute(name);
};
} : "function" == typeof value ? fullname.local ? function(fullname, value) {
return function() {
var v = value.apply(this, arguments);
null == v ? this.removeAttributeNS(fullname.space, fullname.local) : this.setAttributeNS(fullname.space, fullname.local, v);
};
} : function(name, value) {
return function() {
var v = value.apply(this, arguments);
null == v ? this.removeAttribute(name) : this.setAttribute(name, v);
};
} : fullname.local ? function(fullname, value) {
return function() {
this.setAttributeNS(fullname.space, fullname.local, value);
};
} : function(name, value) {
return function() {
this.setAttribute(name, value);
};
})(fullname, value));
},
style: function(name, value, priority) {
return arguments.length > 1 ? this.each((null == value ? function(name) {
return function() {
this.style.removeProperty(name);
};
} : "function" == typeof value ? function(name, value, priority) {
return function() {
var v = value.apply(this, arguments);
null == v ? this.style.removeProperty(name) : this.style.setProperty(name, v, priority);
};
} : function(name, value, priority) {
return function() {
this.style.setProperty(name, value, priority);
};
})(name, value, null == priority ? "" : priority)) : styleValue(this.node(), name);
},
property: function(name, value) {
return arguments.length > 1 ? this.each((null == value ? function(name) {
return function() {
delete this[name];
};
} : "function" == typeof value ? function(name, value) {
return function() {
var v = value.apply(this, arguments);
null == v ? delete this[name] : this[name] = v;
};
} : function(name, value) {
return function() {
this[name] = value;
};
})(name, value)) : this.node()[name];
},
classed: function(name, value) {
var names = classArray(name + "");
if (arguments.length < 2) {
for(var list = classList(this.node()), i = -1, n = names.length; ++i < n;)if (!list.contains(names[i])) return !1;
return !0;
}
return this.each(("function" == typeof value ? function(names, value) {
return function() {
(value.apply(this, arguments) ? classedAdd : classedRemove)(this, names);
};
} : value ? function(names) {
return function() {
classedAdd(this, names);
};
} : function(names) {
return function() {
classedRemove(this, names);
};
})(names, value));
},
text: function(value) {
return arguments.length ? this.each(null == value ? textRemove : ("function" == typeof value ? function(value) {
return function() {
var v = value.apply(this, arguments);
this.textContent = null == v ? "" : v;
};
} : function(value) {
return function() {
this.textContent = value;
};
})(value)) : this.node().textContent;
},
html: function(value) {
return arguments.length ? this.each(null == value ? htmlRemove : ("function" == typeof value ? function(value) {
return function() {
var v = value.apply(this, arguments);
this.innerHTML = null == v ? "" : v;
};
} : function(value) {
return function() {
this.innerHTML = value;
};
})(value)) : this.node().innerHTML;
},
raise: function() {
return this.each(raise);
},
lower: function() {
return this.each(lower);
},
append: function(name) {
var create = "function" == typeof name ? name : creator(name);
return this.select(function() {
return this.appendChild(create.apply(this, arguments));
});
},
insert: function(name, before) {
var create = "function" == typeof name ? name : creator(name), select = null == before ? constantNull : "function" == typeof before ? before : selector(before);
return this.select(function() {
return this.insertBefore(create.apply(this, arguments), select.apply(this, arguments) || null);
});
},
remove: function() {
return this.each(remove);
},
clone: function(deep) {
return this.select(deep ? selection_cloneDeep : selection_cloneShallow);
},
datum: function(value) {
return arguments.length ? this.property("__data__", value) : this.node().__data__;
},
on: function(typename, value, options) {
var i, t, typenames = (typename + "").trim().split(/^|\s+/).map(function(t) {
var name = "", i = t.indexOf(".");
return i >= 0 && (name = t.slice(i + 1), t = t.slice(0, i)), {
type: t,
name: name
};
}), n = typenames.length;
if (arguments.length < 2) {
var on = this.node().__on;
if (on) {
for(var o, j = 0, m = on.length; j < m; ++j)for(i = 0, o = on[j]; i < n; ++i)if ((t = typenames[i]).type === o.type && t.name === o.name) return o.value;
}
return;
}
for(i = 0, on = value ? onAdd : onRemove; i < n; ++i)this.each(on(typenames[i], value, options));
return this;
},
dispatch: function(type, params) {
return this.each(("function" == typeof params ? function(type, params) {
return function() {
return dispatchEvent(this, type, params.apply(this, arguments));
};
} : function(type, params) {
return function() {
return dispatchEvent(this, type, params);
};
})(type, params));
},
[Symbol.iterator]: function*() {
for(var groups = this._groups, j = 0, m = groups.length; j < m; ++j)for(var node, group = groups[j], i = 0, n = group.length; i < n; ++i)(node = group[i]) && (yield node);
}
};
var nextId = 0;
function local() {
return new Local;
}
function Local() {
this._ = "@" + (++nextId).toString(36);
}
function sourceEvent(event) {
let sourceEvent;
for(; sourceEvent = event.sourceEvent;)event = sourceEvent;
return event;
}
function pointer(event, node) {
if (event = sourceEvent(event), void 0 === node && (node = event.currentTarget), node) {
var svg = node.ownerSVGElement || node;
if (svg.createSVGPoint) {
var point = svg.createSVGPoint();
return point.x = event.clientX, point.y = event.clientY, [
(point = point.matrixTransform(node.getScreenCTM().inverse())).x,
point.y
];
}
if (node.getBoundingClientRect) {
var rect = node.getBoundingClientRect();
return [
event.clientX - rect.left - node.clientLeft,
event.clientY - rect.top - node.clientTop
];
}
}
return [
event.pageX,
event.pageY
];
}
function nopropagation(event) {
event.stopImmediatePropagation();
}
function noevent(event) {
event.preventDefault(), event.stopImmediatePropagation();
}
function dragDisable(view) {
var root = view.document.documentElement, selection = select(view).on("dragstart.drag", noevent, !0);
"onselectstart" in root ? selection.on("selectstart.drag", noevent, !0) : (root.__noselect = root.style.MozUserSelect, root.style.MozUserSelect = "none");
}
function yesdrag(view, noclick) {
var root = view.document.documentElement, selection = select(view).on("dragstart.drag", null);
noclick && (selection.on("click.drag", noevent, !0), setTimeout(function() {
selection.on("click.drag", null);
}, 0)), "onselectstart" in root ? selection.on("selectstart.drag", null) : (root.style.MozUserSelect = root.__noselect, delete root.__noselect);
}
Local.prototype = local.prototype = {
constructor: Local,
get: function(node) {
for(var id = this._; !(id in node);)if (!(node = node.parentNode)) return;
return node[id];
},
set: function(node, value) {
return node[this._] = value;
},
remove: function(node) {
return this._ in node && delete node[this._];
},
toString: function() {
return this._;
}
};
var constant$2 = (x)=>()=>x;
function DragEvent(type, { sourceEvent, subject, target, identifier, active, x, y, dx, dy, dispatch }) {
Object.defineProperties(this, {
type: {
value: type,
enumerable: !0,
configurable: !0
},
sourceEvent: {
value: sourceEvent,
enumerable: !0,
configurable: !0
},
subject: {
value: subject,
enumerable: !0,
configurable: !0
},
target: {
value: target,
enumerable: !0,
configurable: !0
},
identifier: {
value: identifier,
enumerable: !0,
configurable: !0
},
active: {
value: active,
enumerable: !0,
configurable: !0
},
x: {
value: x,
enumerable: !0,
configurable: !0
},
y: {
value: y,
enumerable: !0,
configurable: !0
},
dx: {
value: dx,
enumerable: !0,
configurable: !0
},
dy: {
value: dy,
enumerable: !0,
configurable: !0
},
_: {
value: dispatch
}
});
}
// Ignore right-click, since that should open the context menu.
function defaultFilter(event) {
return !event.ctrlKey && !event.button;
}
function defaultContainer() {
return this.parentNode;
}
function defaultSubject(event, d) {
return null == d ? {
x: event.x,
y: event.y
} : d;
}
function defaultTouchable() {
return navigator.maxTouchPoints || "ontouchstart" in this;
}
function define1(constructor, factory, prototype) {
constructor.prototype = factory.prototype = prototype, prototype.constructor = constructor;
}
function extend(parent, definition) {
var prototype = Object.create(parent.prototype);
for(var key in definition)prototype[key] = definition[key];
return prototype;
}
function Color() {}
DragEvent.prototype.on = function() {
var value = this._.on.apply(this._, arguments);
return value === this._ ? this : value;
};
var reI = "\\s*([+-]?\\d+)\\s*", reN = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*", reP = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*", reHex = /^#([0-9a-f]{3,8})$/, reRgbInteger = RegExp("^rgb\\(" + [
reI,
reI,
reI
] + "\\)$"), reRgbPercent = RegExp("^rgb\\(" + [
reP,
reP,
reP
] + "\\)$"), reRgbaInteger = RegExp("^rgba\\(" + [
reI,
reI,
reI,
reN
] + "\\)$"), reRgbaPercent = RegExp("^rgba\\(" + [
reP,
reP,
reP,
reN
] + "\\)$"), reHslPercent = RegExp("^hsl\\(" + [
reN,
reP,
reP
] + "\\)$"), reHslaPercent = RegExp("^hsla\\(" + [
reN,
reP,
reP,
reN
] + "\\)$"), named = {
aliceblue: 0xf0f8ff,
antiquewhite: 0xfaebd7,
aqua: 0x00ffff,
aquamarine: 0x7fffd4,
azure: 0xf0ffff,
beige: 0xf5f5dc,
bisque: 0xffe4c4,
black: 0x000000,
blanchedalmond: 0xffebcd,
blue: 0x0000ff,
blueviolet: 0x8a2be2,
brown: 0xa52a2a,
burlywood: 0xdeb887,
cadetblue: 0x5f9ea0,
chartreuse: 0x7fff00,
chocolate: 0xd2691e,
coral: 0xff7f50,
cornflowerblue: 0x6495ed,
cornsilk: 0xfff8dc,
crimson: 0xdc143c,
cyan: 0x00ffff,
darkblue: 0x00008b,
darkcyan: 0x008b8b,
darkgoldenrod: 0xb8860b,
darkgray: 0xa9a9a9,
darkgreen: 0x006400,
darkgrey: 0xa9a9a9,
darkkhaki: 0xbdb76b,
darkmagenta: 0x8b008b,
darkolivegreen: 0x556b2f,
darkorange: 0xff8c00,
darkorchid: 0x9932cc,
darkred: 0x8b0000,
darksalmon: 0xe9967a,
darkseagreen: 0x8fbc8f,
darkslateblue: 0x483d8b,
darkslategray: 0x2f4f4f,
darkslategrey: 0x2f4f4f,
darkturquoise: 0x00ced1,
darkviolet: 0x9400d3,
deeppink: 0xff1493,
deepskyblue: 0x00bfff,
dimgray: 0x696969,
dimgrey: 0x696969,
dodgerblue: 0x1e90ff,
firebrick: 0xb22222,
floralwhite: 0xfffaf0,
forestgreen: 0x228b22,
fuchsia: 0xff00ff,
gainsboro: 0xdcdcdc,
ghostwhite: 0xf8f8ff,
gold: 0xffd700,
goldenrod: 0xdaa520,
gray: 0x808080,
green: 0x008000,
greenyellow: 0xadff2f,
grey: 0x808080,
honeydew: 0xf0fff0,
hotpink: 0xff69b4,
indianred: 0xcd5c5c,
indigo: 0x4b0082,
ivory: 0xfffff0,
khaki: 0xf0e68c,
lavender: 0xe6e6fa,
lavenderblush: 0xfff0f5,
lawngreen: 0x7cfc00,
lemonchiffon: 0xfffacd,
lightblue: 0xadd8e6,
lightcoral: 0xf08080,
lightcyan: 0xe0ffff,
lightgoldenrodyellow: 0xfafad2,
lightgray: 0xd3d3d3,
lightgreen: 0x90ee90,
lightgrey: 0xd3d3d3,
lightpink: 0xffb6c1,
lightsalmon: 0xffa07a,
lightseagreen: 0x20b2aa,
lightskyblue: 0x87cefa,
lightslategray: 0x778899,
lightslategrey: 0x778899,
lightsteelblue: 0xb0c4de,
lightyellow: 0xffffe0,
lime: 0x00ff00,
limegreen: 0x32cd32,
linen: 0xfaf0e6,
magenta: 0xff00ff,
maroon: 0x800000,
mediumaquamarine: 0x66cdaa,
mediumblue: 0x0000cd,
mediumorchid: 0xba55d3,
mediumpurple: 0x9370db,
mediumseagreen: 0x3cb371,
mediumslateblue: 0x7b68ee,
mediumspringgreen: 0x00fa9a,
mediumturquoise: 0x48d1cc,
mediumvioletred: 0xc71585,
midnightblue: 0x191970,
mintcream: 0xf5fffa,
mistyrose: 0xffe4e1,
moccasin: 0xffe4b5,
navajowhite: 0xffdead,
navy: 0x000080,
oldlace: 0xfdf5e6,
olive: 0x808000,
olivedrab: 0x6b8e23,
orange: 0xffa500,
orangered: 0xff4500,
orchid: 0xda70d6,
palegoldenrod: 0xeee8aa,
palegreen: 0x98fb98,
paleturquoise: 0xafeeee,
palevioletred: 0xdb7093,
papayawhip: 0xffefd5,
peachpuff: 0xffdab9,
peru: 0xcd853f,
pink: 0xffc0cb,
plum: 0xdda0dd,
powderblue: 0xb0e0e6,
purple: 0x800080,
rebeccapurple: 0x663399,
red: 0xff0000,
rosybrown: 0xbc8f8f,
royalblue: 0x4169e1,
saddlebrown: 0x8b4513,
salmon: 0xfa8072,
sandybrown: 0xf4a460,
seagreen: 0x2e8b57,
seashell: 0xfff5ee,
sienna: 0xa0522d,
silver: 0xc0c0c0,
skyblue: 0x87ceeb,
slateblue: 0x6a5acd,
slategray: 0x708090,
slategrey: 0x708090,
snow: 0xfffafa,
springgreen: 0x00ff7f,
steelblue: 0x4682b4,
tan: 0xd2b48c,
teal: 0x008080,
thistle: 0xd8bfd8,
tomato: 0xff6347,
turquoise: 0x40e0d0,
violet: 0xee82ee,
wheat: 0xf5deb3,
white: 0xffffff,
whitesmoke: 0xf5f5f5,
yellow: 0xffff00,
yellowgreen: 0x9acd32
};
function color_formatHex() {
return this.rgb().formatHex();
}
function color_formatRgb() {
return this.rgb().formatRgb();
}
function color(format) {
var m, l;
return format = (format + "").trim().toLowerCase(), (m = reHex.exec(format)) ? (l = m[1].length, m = parseInt(m[1], 16), 6 === l ? rgbn(m) // #ff0000
: 3 === l ? new Rgb(m >> 8 & 0xf | m >> 4 & 0xf0, m >> 4 & 0xf | 0xf0 & m, (0xf & m) << 4 | 0xf & m, 1) // #f00
: 8 === l ? rgba(m >> 24 & 0xff, m >> 16 & 0xff, m >> 8 & 0xff, (0xff & m) / 0xff) // #ff000000
: 4 === l ? rgba(m >> 12 & 0xf | m >> 8 & 0xf0, m >> 8 & 0xf | m >> 4 & 0xf0, m >> 4 & 0xf | 0xf0 & m, ((0xf & m) << 4 | 0xf & m) / 0xff) // #f000
: null // invalid hex
) : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)
: (m = reRgbPercent.exec(format)) ? new Rgb(255 * m[1] / 100, 255 * m[2] / 100, 255 * m[3] / 100, 1) // rgb(100%, 0%, 0%)
: (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)
: (m = reRgbaPercent.exec(format)) ? rgba(255 * m[1] / 100, 255 * m[2] / 100, 255 * m[3] / 100, m[4]) // rgb(100%, 0%, 0%, 1)
: (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)
: (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)
: named.hasOwnProperty(format) ? rgbn(named[format]) // eslint-disable-line no-prototype-builtins
: "transparent" === format ? new Rgb(NaN, NaN, NaN, 0) : null;
}
function rgbn(n) {
return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, 0xff & n, 1);
}
function rgba(r, g, b, a) {
return a <= 0 && (r = g = b = NaN), new Rgb(r, g, b, a);
}
function rgbConvert(o) {
return (o instanceof Color || (o = color(o)), o) ? new Rgb((o = o.rgb()).r, o.g, o.b, o.opacity) : new Rgb;
}
function rgb(r, g, b, opacity) {
return 1 == arguments.length ? rgbConvert(r) : new Rgb(r, g, b, null == opacity ? 1 : opacity);
}
function Rgb(r, g, b, opacity) {
this.r = +r, this.g = +g, this.b = +b, this.opacity = +opacity;
}
function rgb_formatHex() {
return "#" + hex(this.r) + hex(this.g) + hex(this.b);
}
function rgb_formatRgb() {
var a = this.opacity;
return (1 === (a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a))) ? "rgb(" : "rgba(") + Math.max(0, Math.min(255, Math.round(this.r) || 0)) + ", " + Math.max(0, Math.min(255, Math.round(this.g) || 0)) + ", " + Math.max(0, Math.min(255, Math.round(this.b) || 0)) + (1 === a ? ")" : ", " + a + ")");
}
function hex(value) {
return ((value = Math.max(0, Math.min(255, Math.round(value) || 0))) < 16 ? "0" : "") + value.toString(16);
}
function hsla(h, s, l, a) {
return a <= 0 ? h = s = l = NaN : l <= 0 || l >= 1 ? h = s = NaN : s <= 0 && (h = NaN), new Hsl(h, s, l, a);
}
function hslConvert(o) {
if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);
if (o instanceof Color || (o = color(o)), !o) return new Hsl;
if (o instanceof Hsl) return o;
var r = (o = o.rgb()).r / 255, g = o.g / 255, b = o.b / 255, min = Math.min(r, g, b), max = Math.max(r, g, b), h = NaN, s = max - min, l = (max + min) / 2;
return s ? (h = r === max ? (g - b) / s + (g < b) * 6 : g === max ? (b - r) / s + 2 : (r - g) / s + 4, s /= l < 0.5 ? max + min : 2 - max - min, h *= 60) : s = l > 0 && l < 1 ? 0 : h, new Hsl(h, s, l, o.opacity);
}
function hsl(h, s, l, opacity) {
return 1 == arguments.length ? hslConvert(h) : new Hsl(h, s, l, null == opacity ? 1 : opacity);
}
function Hsl(h, s, l, opacity) {
this.h = +h, this.s = +s, this.l = +l, this.opacity = +opacity;
}
/* From FvD 13.37, CSS Color Module Level 3 */ function hsl2rgb(h, m1, m2) {
return (h < 60 ? m1 + (m2 - m1) * h / 60 : h < 180 ? m2 : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60 : m1) * 255;
}
define1(Color, color, {
copy: function(channels) {
return Object.assign(new this.constructor, this, channels);
},
displayable: function() {
return this.rgb().displayable();
},
hex: color_formatHex,
formatHex: color_formatHex,
formatHsl: function() {
return hslConvert(this).formatHsl();
},
formatRgb: color_formatRgb,
toString: color_formatRgb
}), define1(Rgb, rgb, extend(Color, {
brighter: function(k) {
return k = null == k ? 1.4285714285714286 : Math.pow(1.4285714285714286, k), new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
},
darker: function(k) {
return k = null == k ? 0.7 : Math.pow(0.7, k), new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
},
rgb: function() {
return this;
},
displayable: function() {
return -0.5 <= this.r && this.r < 255.5 && -0.5 <= this.g && this.g < 255.5 && -0.5 <= this.b && this.b < 255.5 && 0 <= this.opacity && this.opacity <= 1;
},
hex: rgb_formatHex,
formatHex: rgb_formatHex,
formatRgb: rgb_formatRgb,
toString: rgb_formatRgb
})), define1(Hsl, hsl, extend(Color, {
brighter: function(k) {
return k = null == k ? 1.4285714285714286 : Math.pow(1.4285714285714286, k), new Hsl(this.h, this.s, this.l * k, this.opacity);
},
darker: function(k) {
return k = null == k ? 0.7 : Math.pow(0.7, k), new Hsl(this.h, this.s, this.l * k, this.opacity);
},
rgb: function() {
var h = this.h % 360 + (this.h < 0) * 360, s = isNaN(h) || isNaN(this.s) ? 0 : this.s, l = this.l, m2 = l + (l < 0.5 ? l : 1 - l) * s, m1 = 2 * l - m2;
return new Rgb(hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2), hsl2rgb(h, m1, m2), hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2), this.opacity);
},
displayable: function() {
return (0 <= this.s && this.s <= 1 || isNaN(this.s)) && 0 <= this.l && this.l <= 1 && 0 <= this.opacity && this.opacity <= 1;
},
formatHsl: function() {
var a = this.opacity;
return (1 === (a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a))) ? "hsl(" : "hsla(") + (this.h || 0) + ", " + 100 * (this.s || 0) + "%, " + 100 * (this.l || 0) + "%" + (1 === a ? ")" : ", " + a + ")");
}
}));
const radians = Math.PI / 180, degrees = 180 / Math.PI, t0 = 4 / 29, t1 = 6 / 29, t2 = 6 / 29 * 3 * (6 / 29), t3 = 6 / 29 * (6 / 29) * (6 / 29);
function labConvert(o) {
if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity);
if (o instanceof Hcl) return hcl2lab(o);
o instanceof Rgb || (o = rgbConvert(o));
var x, z, r = rgb2lrgb(o.r), g = rgb2lrgb(o.g), b = rgb2lrgb(o.b), y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / 1);
return r === g && g === b ? x = z = y : (x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / 0.96422), z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / 0.82521)), new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity);
}
function lab(l, a, b, opacity) {
return 1 == arguments.length ? labConvert(l) : new Lab(l, a, b, null == opacity ? 1 : opacity);
}
function Lab(l, a, b, opacity) {
this.l = +l, this.a = +a, this.b = +b, this.opacity = +opacity;
}
function xyz2lab(t) {
return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;
}
function lab2xyz(t) {
return t > t1 ? t * t * t : t2 * (t - t0);
}
function lrgb2rgb(x) {
return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);
}
function rgb2lrgb(x) {
return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
}
function hclConvert(o) {
if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity);
if (o instanceof Lab || (o = labConvert(o)), 0 === o.a && 0 === o.b) return new Hcl(NaN, 0 < o.l && o.l < 100 ? 0 : NaN, o.l, o.opacity);
var h = Math.atan2(o.b, o.a) * degrees;
return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity);
}
function hcl(h, c, l, opacity) {
return 1 == arguments.length ? hclConvert(h) : new Hcl(h, c, l, null == opacity ? 1 : opacity);
}
function Hcl(h, c, l, opacity) {
this.h = +h, this.c = +c, this.l = +l, this.opacity = +opacity;
}
function hcl2lab(o) {
if (isNaN(o.h)) return new Lab(o.l, 0, 0, o.opacity);
var h = o.h * radians;
return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity);
}
define1(Lab, lab, extend(Color, {
brighter: function(k) {
return new Lab(this.l + 18 * (null == k ? 1 : k), this.a, this.b, this.opacity);
},
darker: function(k) {
return new Lab(this.l - 18 * (null == k ? 1 : k), this.a, this.b, this.opacity);
},
rgb: function() {
var y = (this.l + 16) / 116, x = isNaN(this.a) ? y : y + this.a / 500, z = isNaN(this.b) ? y : y - this.b / 200;
return new Rgb(lrgb2rgb(3.1338561 * (x = 0.96422 * lab2xyz(x)) - 1.6168667 * (y = +lab2xyz(y)) - 0.4906146 * (z = 0.82521 * lab2xyz(z))), lrgb2rgb(-0.9787684 * x + 1.9161415 * y + 0.0334540 * z), lrgb2rgb(0.0719453 * x - 0.2289914 * y + 1.4052427 * z), this.opacity);
}
})), define1(Hcl, hcl, extend(Color, {
brighter: function(k) {
return new Hcl(this.h, this.c, this.l + 18 * (null == k ? 1 : k), this.opacity);
},
darker: function(k) {
return new Hcl(this.h, this.c, this.l - 18 * (null == k ? 1 : k), this.opacity);
},
rgb: function() {
return hcl2lab(this).rgb();
}
}));
var BC_DA = -1.78277 * 0.29227 - 0.1347134789;
function cubehelix(h, s, l, opacity) {
return 1 == arguments.length ? function(o) {
if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity);
o instanceof Rgb || (o = rgbConvert(o));
var r = o.r / 255, g = o.g / 255, b = o.b / 255, l = (BC_DA * b + -1.7884503806 * r - 3.5172982438 * g) / (BC_DA + -1.7884503806 - 3.5172982438), bl = b - l, k = -((1.97294 * (g - l) - -0.29227 * bl) / 0.90649), s = Math.sqrt(k * k + bl * bl) / (1.97294 * l * (1 - l)), h = s ? Math.atan2(k, bl) * degrees - 120 : NaN;
return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity);
}(h) : new Cubehelix(h, s, l, null == opacity ? 1 : opacity);
}
function Cubehelix(h, s, l, opacity) {
this.h = +h, this.s = +s, this.l = +l, this.opacity = +opacity;
}
function basis(t1, v0, v1, v2, v3) {
var t2 = t1 * t1, t3 = t2 * t1;
return ((1 - 3 * t1 + 3 * t2 - t3) * v0 + (4 - 6 * t2 + 3 * t3) * v1 + (1 + 3 * t1 + 3 * t2 - 3 * t3) * v2 + t3 * v3) / 6;
}
function basis$1(values) {
var n = values.length - 1;
return function(t) {
var i = t <= 0 ? t = 0 : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n), v1 = values[i], v2 = values[i + 1], v0 = i > 0 ? values[i - 1] : 2 * v1 - v2, v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1;
return basis((t - i / n) * n, v0, v1, v2, v3);
};
}
function basisClosed(values) {
var n = values.length;
return function(t) {
var i = Math.floor(((t %= 1) < 0 ? ++t : t) * n), v0 = values[(i + n - 1) % n], v1 = values[i % n], v2 = values[(i + 1) % n], v3 = values[(i + 2) % n];
return basis((t - i / n) * n, v0, v1, v2, v3);
};
}
define1(Cubehelix, cubehelix, extend(Color, {
brighter: function(k) {
return k = null == k ? 1.4285714285714286 : Math.pow(1.4285714285714286, k), new Cubehelix(this.h, this.s, this.l * k, this.opacity);
},
darker: function(k) {
return k = null == k ? 0.7 : Math.pow(0.7, k), new Cubehelix(this.h, this.s, this.l * k, this.opacity);
},
rgb: function() {
var h = isNaN(this.h) ? 0 : (this.h + 120) * radians, l = +this.l, a = isNaN(this.s) ? 0 : this.s * l * (1 - l), cosh = Math.cos(h), sinh = Math.sin(h);
return new Rgb(255 * (l + a * (-0.14861 * cosh + 1.78277 * sinh)), 255 * (l + a * (-0.29227 * cosh + -0.90649 * sinh)), 255 * (l + 1.97294 * cosh * a), this.opacity);
}
}));
var constant$3 = (x)=>()=>x;
function linear(a, d) {
return function(t) {
return a + t * d;
};
}
function hue(a, b) {
var d = b - a;
return d ? linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : constant$3(isNaN(a) ? b : a);
}
function nogamma(a, b) {
var d = b - a;
return d ? linear(a, d) : constant$3(isNaN(a) ? b : a);
}
var interpolateRgb = function rgbGamma(y) {
var y1, color = 1 == (y1 = +y) ? nogamma : function(a, b) {
var a1, b1, y;
return b - a ? (a1 = a, b1 = b, a1 = Math.pow(a1, y = y1), b1 = Math.pow(b1, y) - a1, y = 1 / y, function(t) {
return Math.pow(a1 + t * b1, y);
}) : constant$3(isNaN(a) ? b : a);
};
function rgb$1(start, end) {
var r = color((start = rgb(start)).r, (end = rgb(end)).r), g = color(start.g, end.g), b = color(start.b, end.b), opacity = nogamma(start.opacity, end.opacity);
return function(t) {
return start.r = r(t), start.g = g(t), start.b = b(t), start.opacity = opacity(t), start + "";
};
}
return rgb$1.gamma = rgbGamma, rgb$1;
}(1);
function rgbSpline(spline) {
return function(colors) {
var i, color, n = colors.length, r = Array(n), g = Array(n), b = Array(n);
for(i = 0; i < n; ++i)color = rgb(colors[i]), r[i] = color.r || 0, g[i] = color.g || 0, b[i] = color.b || 0;
return r = spline(r), g = spline(g), b = spline(b), color.opacity = 1, function(t) {
return color.r = r(t), color.g = g(t), color.b = b(t), color + "";
};
};
}
var rgbBasis = rgbSpline(basis$1), rgbBasisClosed = rgbSpline(basisClosed);
function numberArray(a, b) {
b || (b = []);
var i, n = a ? Math.min(b.length, a.length) : 0, c = b.slice();
return function(t) {
for(i = 0; i < n; ++i)c[i] = a[i] * (1 - t) + b[i] * t;
return c;
};
}
function isNumberArray(x) {
return ArrayBuffer.isView(x) && !(x instanceof DataView);
}
function genericArray(a, b) {
var i, nb = b ? b.length : 0, na = a ? Math.min(nb, a.length) : 0, x = Array(na), c = Array(nb);
for(i = 0; i < na; ++i)x[i] = interpolate(a[i], b[i]);
for(; i < nb; ++i)c[i] = b[i];
return function(t) {
for(i = 0; i < na; ++i)c[i] = x[i](t);
return c;
};
}
function date(a, b) {
var d = new Date;
return a *= 1, b *= 1, function(t) {
return d.setTime(a * (1 - t) + b * t), d;
};
}
function interpolateNumber(a, b) {
return a *= 1, b *= 1, function(t) {
return a * (1 - t) + b * t;
};
}
function object(a, b) {
var k, i = {}, c = {};
for(k in (null === a || "object" != typeof a) && (a = {}), (null === b || "object" != typeof b) && (b = {}), b)k in a ? i[k] = interpolate(a[k], b[k]) : c[k] = b[k];
return function(t) {
for(k in i)c[k] = i[k](t);
return c;
};
}
var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, reB = RegExp(reA.source, "g");
function interpolateString(a, b) {
var b1, b2, am, bm, bs, bi = reA.lastIndex = reB.lastIndex = 0, i = -1, s = [], q = []; // number interpolators
// Interpolate pairs of numbers in a & b.
for(// Coerce inputs to strings.
a += "", b += ""; (am = reA.exec(a)) && (bm = reB.exec(b));)(bs = bm.index) > bi && (bs = b.slice(bi, bs), s[i] ? s[i] += bs : s[++i] = bs), (am = am[0]) === (bm = bm[0]) ? s[i] ? s[i] += bm : s[++i] = bm : (s[++i] = null, q.push({
i: i,
x: interpolateNumber(am, bm)
})), bi = reB.lastIndex;
// Special optimization for only a single match.
// Otherwise, interpolate each of the numbers and rejoin the string.
return bi < b.length && (bs = b.slice(bi), s[i] ? s[i] += bs : s[++i] = bs), s.length < 2 ? q[0] ? (b1 = q[0].x, function(t) {
return b1(t) + "";
}) : (b2 = b, function() {
return b2;
}) : (b = q.length, function(t) {
for(var o, i = 0; i < b; ++i)s[(o = q[i]).i] = o.x(t);
return s.join("");
});
}
function interpolate(a, b) {
var c, t = typeof b;
return null == b || "boolean" === t ? constant$3(b) : ("number" === t ? interpolateNumber : "string" === t ? (c = color(b)) ? (b = c, interpolateRgb) : interpolateString : b instanceof color ? interpolateRgb : b instanceof Date ? date : isNumberArray(b) ? numberArray : Array.isArray(b) ? genericArray : "function" != typeof b.valueOf && "function" != typeof b.toString || isNaN(b) ? object : interpolateNumber)(a, b);
}
function interpolateRound(a, b) {
return a *= 1, b *= 1, function(t) {
return Math.round(a * (1 - t) + b * t);
};
}
var degrees$1 = 180 / Math.PI, identity$2 = {
translateX: 0,
translateY: 0,
rotate: 0,
skewX: 0,
scaleX: 1,
scaleY: 1
};
function decompose(a, b, c, d, e, f) {
var scaleX, scaleY, skewX;
return (scaleX = Math.sqrt(a * a + b * b)) && (a /= scaleX, b /= scaleX), (skewX = a * c + b * d) && (c -= a * skewX, d -= b * skewX), (scaleY = Math.sqrt(c * c + d * d)) && (c /= scaleY, d /= scaleY, skewX /= scaleY), a * d < b * c && (a = -a, b = -b, skewX = -skewX, scaleX = -scaleX), {
translateX: e,
translateY: f,
rotate: Math.atan2(b, a) * degrees$1,
skewX: Math.atan(skewX) * degrees$1,
scaleX: scaleX,
scaleY: scaleY
};
}
function interpolateTransform(parse, pxComma, pxParen, degParen) {
function pop(s) {
return s.length ? s.pop() + " " : "";
}
return function(a, b) {
var a1, b1, a2, b2, s = [], q = []; // number interpolators
return a = parse(a), b = parse(b), !function(xa, ya, xb, yb, s, q) {
if (xa !== xb || ya !== yb) {
var i = s.push("translate(", null, pxComma, null, pxParen);
q.push({
i: i - 4,
x: interpolateNumber(xa, xb)
}, {
i: i - 2,
x: interpolateNumber(ya, yb)
});
} else (xb || yb) && s.push("translate(" + xb + pxComma + yb + pxParen);
}(a.translateX, a.translateY, b.translateX, b.translateY, s, q), (a1 = a.rotate) !== (b1 = b.rotate) ? (a1 - b1 > 180 ? b1 += 360 : b1 - a1 > 180 && (a1 += 360), q.push({
i: s.push(pop(s) + "rotate(", null, degParen) - 2,
x: interpolateNumber(a1, b1)
})) : b1 && s.push(pop(s) + "rotate(" + b1 + degParen), (a2 = a.skewX) !== (b2 = b.skewX) ? q.push({
i: s.push(pop(s) + "skewX(", null, degParen) - 2,
x: interpolateNumber(a2, b2)
}) : b2 && s.push(pop(s) + "skewX(" + b2 + degParen), !function(xa, ya, xb, yb, s, q) {
if (xa !== xb || ya !== yb) {
var i = s.push(pop(s) + "scale(", null, ",", null, ")");
q.push({
i: i - 4,
x: interpolateNumber(xa, xb)
}, {
i: i - 2,
x: interpolateNumber(ya, yb)
});
} else (1 !== xb || 1 !== yb) && s.push(pop(s) + "scale(" + xb + "," + yb + ")");
}(a.scaleX, a.scaleY, b.scaleX, b.scaleY, s, q), a = b = null, function(t) {
for(var o, i = -1, n = q.length; ++i < n;)s[(o = q[i]).i] = o.x(t);
return s.join("");
};
};
}
var interpolateTransformCss = interpolateTransform(/* eslint-disable no-undef */ function(value) {
const m = new ("function" == typeof DOMMatrix ? DOMMatrix : WebKitCSSMatrix)(value + "");
return m.isIdentity ? identity$2 : decompose(m.a, m.b, m.c, m.d, m.e, m.f);
}, "px, ", "px)", "deg)"), interpolateTransformSvg = interpolateTransform(function(value) {
return null == value ? identity$2 : (svgNode || (svgNode = document.createElementNS("http://www.w3.org/2000/svg", "g")), svgNode.setAttribute("transform", value), value = svgNode.transform.baseVal.consolidate()) ? decompose((value = value.matrix).a, value.b, value.c, value.d, value.e, value.f) : identity$2;
}, ", ", ")", ")");
function cosh(x) {
return ((x = Math.exp(x)) + 1 / x) / 2;
}
var interpolateZoom = function zoomRho(rho, rho2, rho4) {
// p0 = [ux0, uy0, w0]
// p1 = [ux1, uy1, w1]
function zoom(p0, p1) {
var i, S, ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy;
// Special case for u0 ≅ u1.
if (d2 < 1e-12) S = Math.log(w1 / w0) / rho, i = function(t) {
return [
ux0 + t * dx,
uy0 + t * dy,
w0 * Math.exp(rho * t * S)
];
};
else {
var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + rho4 * d2) / (2 * w0 * rho2 * d1), b1 = (w1 * w1 - w0 * w0 - rho4 * d2) / (2 * w1 * rho2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0);
S = (Math.log(Math.sqrt(b1 * b1 + 1) - b1) - r0) / rho, i = function(t) {
var x, x1, s = t * S, coshr0 = cosh(r0), u = w0 / (rho2 * d1) * (coshr0 * (((x = Math.exp(2 * (x = rho * s + r0))) - 1) / (x + 1)) - ((x1 = Math.exp(x1 = r0)) - 1 / x1) / 2);
return [
ux0 + u * dx,
uy0 + u * dy,
w0 * coshr0 / cosh(rho * s + r0)
];
};
}
return i.duration = 1000 * S * rho / Math.SQRT2, i;
}
return zoom.rho = function(_) {
var _1 = Math.max(1e-3, +_), _2 = _1 * _1;
return zoomRho(_1, _2, _2 * _2);
}, zoom;
}(Math.SQRT2, 2, 4);
function hsl$1(hue) {
return function(start, end) {
var h = hue((start = hsl(start)).h, (end = hsl(end)).h), s = nogamma(start.s, end.s), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity);
return function(t) {
return start.h = h(t), start.s = s(t), start.l = l(t), start.opacity = opacity(t), start + "";
};
};
}
var hsl$2 = hsl$1(hue), hslLong = hsl$1(nogamma);
function hcl$1(hue) {
return function(start, end) {
var h = hue((start = hcl(start)).h, (end = hcl(end)).h), c = nogamma(start.c, end.c), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity);
return function(t) {
return start.h = h(t), start.c = c(t), start.l = l(t), start.opacity = opacity(t), start + "";
};
};
}
var hcl$2 = hcl$1(hue), hclLong = hcl$1(nogamma);
function cubehelix$1(hue) {
return function cubehelixGamma(y) {
function cubehelix$1(start, end) {
var h = hue((start = cubehelix(start)).h, (end = cubehelix(end)).h), s = nogamma(start.s, end.s), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity);
return function(t) {
return start.h = h(t), start.s = s(t), start.l = l(Math.pow(t, y)), start.opacity = opacity(t), start + "";
};
}
return y *= 1, cubehelix$1.gamma = cubehelixGamma, cubehelix$1;
}(1);
}
var cubehelix$2 = cubehelix$1(hue), cubehelixLong = cubehelix$1(nogamma);
function piecewise(interpolate$1, values) {
void 0 === values && (values = interpolate$1, interpolate$1 = interpolate);
for(var i = 0, n = values.length - 1, v = values[0], I = Array(n < 0 ? 0 : n); i < n;)I[i] = interpolate$1(v, v = values[++i]);
return function(t) {
var i = Math.max(0, Math.min(n - 1, Math.floor(t *= n)));
return I[i](t - i);
};
}
var locale$1, svgNode, taskHead, taskTail, frame = 0, timeout = 0, interval = 0, clockLast = 0, clockNow = 0, clockSkew = 0, clock = "object" == typeof performance && performance.now ? performance : Date, setFrame = "object" == typeof window && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : function(f) {
setTimeout(f, 17);
};
function now() {
return clockNow || (setFrame(clearNow), clockNow = clock.now() + clockSkew);
}
function clearNow() {
clockNow = 0;
}
function Timer() {
this._call = this._time = this._next = null;
}
function timer(callback, delay, time) {
var t = new Timer;
return t.restart(callback, delay, time), t;
}
function timerFlush() {
now(), ++frame;
for(var e, t = taskHead; t;)(e = clockNow - t._time) >= 0 && t._call.call(null, e), t = t._next;
--frame;
}
function wake() {
clockNow = (clockLast = clock.now()) + clockSkew, frame = timeout = 0;
try {
timerFlush();
} finally{
frame = 0, function() {
for(var t0, t2, t1 = taskHead, time = 1 / 0; t1;)t1._call ? (time > t1._time && (time = t1._time), t0 = t1, t1 = t1._next) : (t2 = t1._next, t1._next = null, t1 = t0 ? t0._next = t2 : taskHead = t2);
taskTail = t0, sleep(time);
}(), clockNow = 0;
}
}
function poke() {
var now = clock.now(), delay = now - clockLast;
delay > 1000 && (clockSkew -= delay, clockLast = now);
}
function sleep(time) {
!frame && (timeout && (timeout = clearTimeout(timeout)), time - clockNow > 24 ? (time < 1 / 0 && (timeout = setTimeout(wake, time - clock.now() - clockSkew)), interval && (interval = clearInterval(interval))) : (interval || (clockLast = clock.now(), interval = setInterval(poke, 1000)), frame = 1, setFrame(wake))); // Soonest alarm already set, or will be.
}
function timeout$1(callback, delay, time) {
var t = new Timer;
return delay = null == delay ? 0 : +delay, t.restart((elapsed)=>{
t.stop(), callback(elapsed + delay);
}, delay, time), t;
}
Timer.prototype = timer.prototype = {
constructor: Timer,
restart: function(callback, delay, time) {
if ("function" != typeof callback) throw TypeError("callback is not a function");
time = (null == time ? now() : +time) + (null == delay ? 0 : +delay), this._next || taskTail === this || (taskTail ? taskTail._next = this : taskHead = this, taskTail = this), this._call = callback, this._time = time, sleep();
},
stop: function() {
this._call && (this._call = null, this._time = 1 / 0, sleep());
}
};
var emptyOn = dispatch("start", "end", "cancel", "interrupt"), emptyTween = [];
function schedule(node, name, id, index, group, timing) {
var schedules = node.__transition;
if (schedules) {
if (id in schedules) return;
} else node.__transition = {};
!function(node, id, self1) {
var tween, schedules = node.__transition;
function start(elapsed) {
var i, j, n, o;
// If the state is not SCHEDULED, then we previously errored on start.
if (1 !== self1.state) return stop();
for(i in schedules)if ((o = schedules[i]).name === self1.name) {
// While this element already has a starting transition during this frame,
// defer starting an interrupting transition until that transition has a
// chance to tick (and possibly end); see d3/d3-transition#54!
if (3 === o.state) return timeout$1(start);
// Interrupt the active transition, if any.
4 === o.state ? (o.state = 6, o.timer.stop(), o.on.call("interrupt", node, node.__data__, o.index, o.group), delete schedules[i]) : +i < id && (o.state = 6, o.timer.stop(), o.on.call("cancel", node, node.__data__, o.index, o.group), delete schedules[i]);
}
if (// Defer the first tick to end of the current frame; see d3/d3#1576.
// Note the transition may be canceled after start and before the first tick!
// Note this must be scheduled before the start event; see d3/d3-transition#16!
// Assuming this is successful, subsequent callbacks go straight to tick.
timeout$1(function() {
3 === self1.state && (self1.state = 4, self1.timer.restart(tick, self1.delay, self1.time), tick(elapsed));
}), // Dispatch the start event.
// Note this must be done before the tween are initialized.
self1.state = 2, self1.on.call("start", node, node.__data__, self1.index, self1.group), 2 === self1.state) {
for(i = 0, self1.state = 3, // Initialize the tween, deleting null tween.
tween = Array(n = self1.tween.length), j = -1; i < n; ++i)(o = self1.tween[i].value.call(node, node.__data__, self1.index, self1.group)) && (tween[++j] = o);
tween.length = j + 1;
} // interrupted
}
function tick(elapsed) {
for(var t = elapsed < self1.duration ? self1.ease.call(null, elapsed / self1.duration) : (self1.timer.restart(stop), self1.state = 5, 1), i = -1, n = tween.length; ++i < n;)tween[i].call(node, t);
// Dispatch the end event.
5 === self1.state && (self1.on.call("end", node, node.__data__, self1.index, self1.group), stop());
}
function stop() {
for(var i in self1.state = 6, self1.timer.stop(), delete schedules[id], schedules)return; // eslint-disable-line no-unused-vars
delete node.__transition;
}
// Initialize the self timer when the transition is created.
// Note the actual delay is not known until the first callback!
schedules[id] = self1, self1.timer = timer(function(elapsed) {
self1.state = 1, self1.timer.restart(start, self1.delay, self1.time), self1.delay <= elapsed && start(elapsed - self1.delay);
}, 0, self1.time);
}(node, id, {
name: name,
index: index,
group: group,
on: emptyOn,
tween: emptyTween,
time: timing.time,
delay: timing.delay,
duration: timing.duration,
ease: timing.ease,
timer: null,
state: 0
});
}
function init(node, id) {
var schedule = get$1(node, id);
if (schedule.state > 0) throw Error("too late; already scheduled");
return schedule;
}
function set$2(node, id) {
var schedule = get$1(node, id);
if (schedule.state > 3) throw Error("too late; already running");
return schedule;
}
function get$1(node, id) {
var schedule = node.__transition;
if (!schedule || !(schedule = schedule[id])) throw Error("transition not found");
return schedule;
}
function interrupt(node, name) {
var schedule, active, i, schedules = node.__transition, empty = !0;
if (schedules) {
for(i in name = null == name ? null : name + "", schedules){
if ((schedule = schedules[i]).name !== name) {
empty = !1;
continue;
}
active = schedule.state > 2 && schedule.state < 5, schedule.state = 6, schedule.timer.stop(), schedule.on.call(active ? "interrupt" : "cancel", node, node.__data__, schedule.index, schedule.group), delete schedules[i];
}
empty && delete node.__transition;
}
}
function tweenValue(transition, name, value) {
var id = transition._id;
return transition.each(function() {
var schedule = set$2(this, id);
(schedule.value || (schedule.value = {}))[name] = value.apply(this, arguments);
}), function(node) {
return get$1(node, id).value[name];
};
}
function interpolate$1(a, b) {
var c;
return ("number" == typeof b ? interpolateNumber : b instanceof color ? interpolateRgb : (c = color(b)) ? (b = c, interpolateRgb) : interpolateString)(a, b);
}
var Selection$1 = selection.prototype.constructor;
function styleRemove$1(name) {
return function() {
this.style.removeProperty(name);
};
}
var id = 0;
function Transition(groups, parents, name, id) {
this._groups = groups, this._parents = parents, this._name = name, this._id = id;
}
function transition(name) {
return selection().transition(name);
}
var selection_prototype = selection.prototype;
function quadInOut(t) {
return ((t *= 2) <= 1 ? t * t : --t * (2 - t) + 1) / 2;
}
function cubicInOut(t) {
return ((t *= 2) <= 1 ? t * t * t : (t -= 2) * t * t + 2) / 2;
}
Transition.prototype = transition.prototype = {
constructor: Transition,
select: function(select) {
var name = this._name, id = this._id;
"function" != typeof select && (select = selector(select));
for(var groups = this._groups, m = groups.length, subgroups = Array(m), j = 0; j < m; ++j)for(var node, subnode, group = groups[j], n = group.length, subgroup = subgroups[j] = Array(n), i = 0; i < n; ++i)(node = group[i]) && (subnode = select.call(node, node.__data__, i, group)) && ("__data__" in node && (subnode.__data__ = node.__data__), subgroup[i] = subnode, schedule(subgroup[i], name, id, i, subgroup, get$1(node, id)));
return new Transition(subgroups, this._parents, name, id);
},
selectAll: function(select) {
var name = this._name, id = this._id;
"function" != typeof select && (select = selectorAll(select));
for(var groups = this._groups, m = groups.length, subgroups = [], parents = [], j = 0; j < m; ++j)for(var node, group = groups[j], n = group.length, i = 0; i < n; ++i)if (node = group[i]) {
for(var child, children = select.call(node, node.__data__, i, group), inherit = get$1(node, id), k = 0, l = children.length; k < l; ++k)(child = children[k]) && schedule(child, name, id, k, children, inherit);
subgroups.push(children), parents.push(node);
}
return new Transition(subgroups, parents, name, id);
},
filter: function(match) {
"function" != typeof match && (match = matcher(match));
for(var groups = this._groups, m = groups.length, subgroups = Array(m), j = 0; j < m; ++j)for(var node, group = groups[j], n = group.length, subgroup = subgroups[j] = [], i = 0; i < n; ++i)(node = group[i]) && match.call(node, node.__data__, i, group) && subgroup.push(node);
return new Transition(subgroups, this._parents, this._name, this._id);
},
merge: function(transition) {
if (transition._id !== this._id) throw Error();
for(var groups0 = this._groups, groups1 = transition._groups, m0 = groups0.length, m1 = groups1.length, m = Math.min(m0, m1), merges = Array(m0), j = 0; j < m; ++j)for(var node, group0 = groups0[j], group1 = groups1[j], n = group0.length, merge = merges[j] = Array(n), i = 0; i < n; ++i)(node = group0[i] || group1[i]) && (merge[i] = node);
for(; j < m0; ++j)merges[j] = groups0[j];
return new Transition(merges, this._parents, this._name, this._id);
},
selection: function() {
return new Selection$1(this._groups, this._parents);
},
transition: function() {
for(var name = this._name, id0 = this._id, id1 = ++id, groups = this._groups, m = groups.length, j = 0; j < m; ++j)for(var node, group = groups[j], n = group.length, i = 0; i < n; ++i)if (node = group[i]) {
var inherit = get$1(node, id0);
schedule(node, name, id1, i, group, {
time: inherit.time + inherit.delay + inherit.duration,
delay: 0,
duration: inherit.duration,
ease: inherit.ease
});
}
return new Transition(groups, this._parents, name, id1);
},
call: selection_prototype.call,
nodes: selection_prototype.nodes,
node: selection_prototype.node,
size: selection_prototype.size,
empty: selection_prototype.empty,
each: selection_prototype.each,
on: function(name, listener) {
var on0, on1, sit, id = this._id;
return arguments.length < 2 ? get$1(this.node(), id).on.on(name) : this.each((sit = (name + "").trim().split(/^|\s+/).every(function(t) {
var i = t.indexOf(".");
return i >= 0 && (t = t.slice(0, i)), !t || "start" === t;
}) ? init : set$2, function() {
var schedule = sit(this, id), on = schedule.on;
on !== on0 && (on1 = (on0 = on).copy()).on(name, listener), schedule.on = on1;
}));
},
attr: function(name, value) {
var fullname = namespace(name), i = "transform" === fullname ? interpolateTransformSvg : interpolate$1;
return this.attrTween(name, "function" == typeof value ? (fullname.local ? function(fullname, interpolate, value) {
var string00, string10, interpolate0;
return function() {
var string0, string1, value1 = value(this);
return null == value1 ? void this.removeAttributeNS(fullname.space, fullname.local) : (string0 = this.getAttributeNS(fullname.space, fullname.local)) === (string1 = value1 + "") ? null : string0 === string00 && string1 === string10 ? interpolate0 : (string10 = string1, interpolate0 = interpolate(string00 = string0, value1));
};
} : function(name, interpolate, value) {
var string00, string10, interpolate0;
return function() {
var string0, string1, value1 = value(this);
return null == value1 ? void this.removeAttribute(name) : (string0 = this.getAttribute(name)) === (string1 = value1 + "") ? null : string0 === string00 && string1 === string10 ? interpolate0 : (string10 = string1, interpolate0 = interpolate(string00 = string0, value1));
};
})(fullname, i, tweenValue(this, "attr." + name, value)) : null == value ? (fullname.local ? function(fullname) {
return function() {
this.removeAttributeNS(fullname.space, fullname.local);
};
} : function(name) {
return function() {
this.removeAttribute(name);
};
})(fullname) : (fullname.local ? function(fullname, interpolate, value1) {
var string00, interpolate0, string1 = value1 + "";
return function() {
var string0 = this.getAttributeNS(fullname.space, fullname.local);
return string0 === string1 ? null : string0 === string00 ? interpolate0 : interpolate0 = interpolate(string00 = string0, value1);
};
} : function(name, interpolate, value1) {
var string00, interpolate0, string1 = value1 + "";
return function() {
var string0 = this.getAttribute(name);
return string0 === string1 ? null : string0 === string00 ? interpolate0 : interpolate0 = interpolate(string00 = string0, value1);
};
})(fullname, i, value));
},
attrTween: function(name, value) {
var key = "attr." + name;
if (arguments.length < 2) return (key = this.tween(key)) && key._value;
if (null == value) return this.tween(key, null);
if ("function" != typeof value) throw Error();
var fullname = namespace(name);
return this.tween(key, (fullname.local ? function(fullname, value) {
var t0, i0;
function tween() {
var i = value.apply(this, arguments);
return i !== i0 && (t0 = (i0 = i) && function(t) {
this.setAttributeNS(fullname.space, fullname.local, i.call(this, t));
}), t0;
}
return tween._value = value, tween;
} : function(name, value) {
var t0, i0;
function tween() {
var i = value.apply(this, arguments);
return i !== i0 && (t0 = (i0 = i) && function(t) {
this.setAttribute(name, i.call(this, t));
}), t0;
}
return tween._value = value, tween;
})(fullname, value));
},
style: function(name, value, priority) {
var name1, string00, string10, interpolate0, name2, value1, string001, string101, interpolate01, id, name3, on0, on1, listener0, remove, key, event, name4, string002, interpolate02, string1, i = "transform" == (name += "") ? interpolateTransformCss : interpolate$1;
return null == value ? this.styleTween(name, (name1 = name, function() {
var string0 = styleValue(this, name1), string1 = (this.style.removeProperty(name1), styleValue(this, name1));
return string0 === string1 ? null : string0 === string00 && string1 === string10 ? interpolate0 : interpolate0 = i(string00 = string0, string10 = string1);
})).on("end.style." + name, styleRemove$1(name)) : "function" == typeof value ? this.styleTween(name, (name2 = name, value1 = tweenValue(this, "style." + name, value), function() {
var string0 = styleValue(this, name2), value11 = value1(this), string1 = value11 + "";
return null == value11 && (this.style.removeProperty(name2), string1 = value11 = styleValue(this, name2)), string0 === string1 ? null : string0 === string001 && string1 === string101 ? interpolate01 : (string101 = string1, interpolate01 = i(string001 = string0, value11));
})).each((id = this._id, event = "end." + (key = "style." + (name3 = name)), function() {
var schedule = set$2(this, id), on = schedule.on, listener = null == schedule.value[key] ? remove || (remove = styleRemove$1(name3)) : void 0;
(on !== on0 || listener0 !== listener) && (on1 = (on0 = on).copy()).on(event, listener0 = listener), schedule.on = on1;
})) : this.styleTween(name, (name4 = name, string1 = value + "", function() {
var string0 = styleValue(this, name4);
return string0 === string1 ? null : string0 === string002 ? interpolate02 : interpolate02 = i(string002 = string0, value);
}), priority).on("end.style." + name, null);
},
styleTween: function(name, value, priority) {
var key = "style." + (name += "");
if (arguments.length < 2) return (key = this.tween(key)) && key._value;
if (null == value) return this.tween(key, null);
if ("function" != typeof value) throw Error();
return this.tween(key, function(name, value, priority) {
var t, i0;
function tween() {
var i = value.apply(this, arguments);
return i !== i0 && (t = (i0 = i) && function(t) {
this.style.setProperty(name, i.call(this, t), priority);
}), t;
}
return tween._value = value, tween;
}(name, value, null == priority ? "" : priority));
},
text: function(value) {
var value1, value2;
return this.tween("text", "function" == typeof value ? (value1 = tweenValue(this, "text", value), function() {
var value11 = value1(this);
this.textContent = null == value11 ? "" : value11;
}) : (value2 = null == value ? "" : value + "", function() {
this.textContent = value2;
}));
},
textTween: function(value) {
var key = "text";
if (arguments.length < 1) return (key = this.tween(key)) && key._value;
if (null == value) return this.tween(key, null);
if ("function" != typeof value) throw Error();
return this.tween(key, function(value) {
var t0, i0;
function tween() {
var i = value.apply(this, arguments);
return i !== i0 && (t0 = (i0 = i) && function(t) {
this.textContent = i.call(this, t);
}), t0;
}
return tween._value = value, tween;
}(value));
},
remove: function() {
var id;
return this.on("end.remove", (id = this._id, function() {
var parent = this.parentNode;
for(var i in this.__transition)if (+i !== id) return;
parent && parent.removeChild(this);
}));
},
tween: function(name, value) {
var id = this._id;
if (name += "", arguments.length < 2) {
for(var t, tween = get$1(this.node(), id).tween, i = 0, n = tween.length; i < n; ++i)if ((t = tween[i]).name === name) return t.value;
return null;
}
return this.each((null == value ? function(id, name) {
var tween0, tween1;
return function() {
var schedule = set$2(this, id), tween = schedule.tween;
// If this node shared tween with the previous node,
// just assign the updated shared tween and we’re done!
// Otherwise, copy-on-write.
if (tween !== tween0) {
tween1 = tween0 = tween;
for(var i = 0, n = tween1.length; i < n; ++i)if (tween1[i].name === name) {
(tween1 = tween1.slice()).splice(i, 1);
break;
}
}
schedule.tween = tween1;
};
} : function(id, name, value) {
var tween0, tween1;
if ("function" != typeof value) throw Error();
return function() {
var schedule = set$2(this, id), tween = schedule.tween;
// If this node shared tween with the previous node,
// just assign the updated shared tween and we’re done!
// Otherwise, copy-on-write.
if (tween !== tween0) {
tween1 = (tween0 = tween).slice();
for(var t = {
name: name,
value: value
}, i = 0, n = tween1.length; i < n; ++i)if (tween1[i].name === name) {
tween1[i] = t;
break;
}
i === n && tween1.push(t);
}
schedule.tween = tween1;
};
})(id, name, value));
},
delay: function(value) {
var id = this._id;
return arguments.length ? this.each(("function" == typeof value ? function(id, value) {
return function() {
init(this, id).delay = +value.apply(this, arguments);
};
} : function(id, value) {
return value *= 1, function() {
init(this, id).delay = value;
};
})(id, value)) : get$1(this.node(), id).delay;
},
duration: function(value) {
var id = this._id;
return arguments.length ? this.each(("function" == typeof value ? function(id, value) {
return function() {
set$2(this, id).duration = +value.apply(this, arguments);
};
} : function(id, value) {
return value *= 1, function() {
set$2(this, id).duration = value;
};
})(id, value)) : get$1(this.node(), id).duration;
},
ease: function(value) {
var id = this._id;
return arguments.length ? this.each(function(id, value) {
if ("function" != typeof value) throw Error();
return function() {
set$2(this, id).ease = value;
};
}(id, value)) : get$1(this.node(), id).ease;
},
easeVarying: function(value) {
var id;
if ("function" != typeof value) throw Error();
return this.each((id = this._id, function() {
var v = value.apply(this, arguments);
if ("function" != typeof v) throw Error();
set$2(this, id).ease = v;
}));
},
end: function() {
var on0, on1, that = this, id = that._id, size = that.size();
return new Promise(function(resolve, reject) {
var cancel = {
value: reject
}, end = {
value: function() {
0 == --size && resolve();
}
};
that.each(function() {
var schedule = set$2(this, id), on = schedule.on;
on !== on0 && ((on1 = (on0 = on).copy())._.cancel.push(cancel), on1._.interrupt.push(cancel), on1._.end.push(end)), schedule.on = on1;
}), 0 === size && resolve();
});
},
[Symbol.iterator]: selection_prototype[Symbol.iterator]
};
var polyIn = function custom(e) {
function polyIn(t) {
return Math.pow(t, e);
}
return e *= 1, polyIn.exponent = custom, polyIn;
}(3), polyOut = function custom(e) {
function polyOut(t) {
return 1 - Math.pow(1 - t, e);
}
return e *= 1, polyOut.exponent = custom, polyOut;
}(3), polyInOut = function custom(e) {
function polyInOut(t) {
return ((t *= 2) <= 1 ? Math.pow(t, e) : 2 - Math.pow(2 - t, e)) / 2;
}
return e *= 1, polyInOut.exponent = custom, polyInOut;
}(3), pi = Math.PI, halfPi = pi / 2;
function sinInOut(t) {
return (1 - Math.cos(pi * t)) / 2;
}
// tpmt is two power minus ten times t scaled to [0,1]
function tpmt(x) {
return (Math.pow(2, -10 * x) - 0.0009765625) * 1.0009775171065494;
}
function expInOut(t) {
return ((t *= 2) <= 1 ? tpmt(1 - t) : 2 - tpmt(t - 1)) / 2;
}
function circleInOut(t) {
return ((t *= 2) <= 1 ? 1 - Math.sqrt(1 - t * t) : Math.sqrt(1 - (t -= 2) * t) + 1) / 2;
}
var b1 = 4 / 11, b2 = 6 / 11, b3 = 8 / 11, b4 = 3 / 4, b5 = 9 / 11, b6 = 10 / 11, b7 = 15 / 16, b8 = 21 / 22, b9 = 63 / 64, b0 = 1 / (4 / 11) / (4 / 11);
function bounceOut(t) {
return (t *= 1) < b1 ? b0 * t * t : t < b3 ? b0 * (t -= b2) * t + b4 : t < b6 ? b0 * (t -= b5) * t + b7 : b0 * (t -= b8) * t + b9;
}
var backIn = function custom(s) {
function backIn(t) {
return (t *= 1) * t * (s * (t - 1) + t);
}
return s *= 1, backIn.overshoot = custom, backIn;
}(1.70158), backOut = function custom(s) {
function backOut(t) {
return --t * t * ((t + 1) * s + t) + 1;
}
return s *= 1, backOut.overshoot = custom, backOut;
}(1.70158), backInOut = function custom(s) {
function backInOut(t) {
return ((t *= 2) < 1 ? t * t * ((s + 1) * t - s) : (t -= 2) * t * ((s + 1) * t + s) + 2) / 2;
}
return s *= 1, backInOut.overshoot = custom, backInOut;
}(1.70158), tau = 2 * Math.PI, elasticIn = function custom(a, p) {
var s = Math.asin(1 / (a = Math.max(1, a))) * (p /= tau);
function elasticIn(t) {
return a * tpmt(- --t) * Math.sin((s - t) / p);
}
return elasticIn.amplitude = function(a) {
return custom(a, p * tau);
}, elasticIn.period = function(p) {
return custom(a, p);
}, elasticIn;
}(1, 0.3), elasticOut = function custom(a, p) {
var s = Math.asin(1 / (a = Math.max(1, a))) * (p /= tau);
function elasticOut(t) {
return 1 - a * tpmt(t *= 1) * Math.sin((t + s) / p);
}
return elasticOut.amplitude = function(a) {
return custom(a, p * tau);
}, elasticOut.period = function(p) {
return custom(a, p);
}, elasticOut;
}(1, 0.3), elasticInOut = function custom(a, p) {
var s = Math.asin(1 / (a = Math.max(1, a))) * (p /= tau);
function elasticInOut(t) {
return ((t = 2 * t - 1) < 0 ? a * tpmt(-t) * Math.sin((s - t) / p) : 2 - a * tpmt(t) * Math.sin((s + t) / p)) / 2;
}
return elasticInOut.amplitude = function(a) {
return custom(a, p * tau);
}, elasticInOut.period = function(p) {
return custom(a, p);
}, elasticInOut;
}(1, 0.3), defaultTiming = {
time: null,
delay: 0,
duration: 250,
ease: cubicInOut
};
selection.prototype.interrupt = function(name) {
return this.each(function() {
interrupt(this, name);
});
}, selection.prototype.transition = function(name) {
var id1, timing;
name instanceof Transition ? (id1 = name._id, name = name._name) : (id1 = ++id, (timing = defaultTiming).time = now(), name = null == name ? null : name + "");
for(var groups = this._groups, m = groups.length, j = 0; j < m; ++j)for(var node, group = groups[j], n = group.length, i = 0; i < n; ++i)(node = group[i]) && schedule(node, name, id1, i, group, timing || function(node, id) {
for(var timing; !(timing = node.__transition) || !(timing = timing[id]);)if (!(node = node.parentNode)) throw Error(`transition ${id} not found`);
return timing;
}(node, id1));
return new Transition(groups, this._parents, name, id1);
};
var root$1 = [
null
], constant$4 = (x)=>()=>x;
function BrushEvent(type, { sourceEvent, target, selection, mode, dispatch }) {
Object.defineProperties(this, {
type: {
value: type,
enumerable: !0,
configurable: !0
},
sourceEvent: {
value: sourceEvent,
enumerable: !0,
configurable: !0
},
target: {
value: target,
enumerable: !0,
configurable: !0
},
selection: {
value: selection,
enumerable: !0,
configurable: !0
},
mode: {
value: mode,
enumerable: !0,
configurable: !0
},
_: {
value: dispatch
}
});
}
function noevent$1(event) {
event.preventDefault(), event.stopImmediatePropagation();
}
var MODE_DRAG = {
name: "drag"
}, MODE_SPACE = {
name: "space"
}, MODE_HANDLE = {
name: "handle"
}, MODE_CENTER = {
name: "center"
};
const { abs, max: max$1, min: min$1 } = Math;
function number1(e) {
return [
+e[0],
+e[1]
];
}
function number2(e) {
return [
number1(e[0]),
number1(e[1])
];
}
var X = {
name: "x",
handles: [
"w",
"e"
].map(type),
input: function(x, e) {
return null == x ? null : [
[
+x[0],
e[0][1]
],
[
+x[1],
e[1][1]
]
];
},
output: function(xy) {
return xy && [
xy[0][0],
xy[1][0]
];
}
}, Y = {
name: "y",
handles: [
"n",
"s"
].map(type),
input: function(y, e) {
return null == y ? null : [
[
e[0][0],
+y[0]
],
[
e[1][0],
+y[1]
]
];
},
output: function(xy) {
return xy && [
xy[0][1],
xy[1][1]
];
}
}, XY = {
name: "xy",
handles: [
"n",
"w",
"e",
"s",
"nw",
"ne",
"sw",
"se"
].map(type),
input: function(xy) {
return null == xy ? null : number2(xy);
},
output: function(xy) {
return xy;
}
}, cursors = {
overlay: "crosshair",
selection: "move",
n: "ns-resize",
e: "ew-resize",
s: "ns-resize",
w: "ew-resize",
nw: "nwse-resize",
ne: "nesw-resize",
se: "nwse-resize",
sw: "nesw-resize"
}, flipX = {
e: "w",
w: "e",
nw: "ne",
ne: "nw",
se: "sw",
sw: "se"
}, flipY = {
n: "s",
s: "n",
nw: "sw",
ne: "se",
se: "ne",
sw: "nw"
}, signsX = {
overlay: 1,
selection: 1,
n: null,
e: 1,
s: null,
w: -1,
nw: -1,
ne: 1,
se: 1,
sw: -1
}, signsY = {
overlay: 1,
selection: 1,
n: -1,
e: null,
s: 1,
w: null,
nw: -1,
ne: -1,
se: 1,
sw: 1
};
function type(t) {
return {
type: t
};
}
// Ignore right-click, since that should open the context menu.
function defaultFilter$1(event) {
return !event.ctrlKey && !event.button;
}
function defaultExtent() {
var svg = this.ownerSVGElement || this;
return svg.hasAttribute("viewBox") ? [
[
(svg = svg.viewBox.baseVal).x,
svg.y
],
[
svg.x + svg.width,
svg.y + svg.height
]
] : [
[
0,
0
],
[
svg.width.baseVal.value,
svg.height.baseVal.value
]
];
}
function defaultTouchable$1() {
return navigator.maxTouchPoints || "ontouchstart" in this;
}
// Like d3.local, but with the name “__brush” rather than auto-generated.
function local$1(node) {
for(; !node.__brush;)if (!(node = node.parentNode)) return;
return node.__brush;
}
function brush$1(dim) {
var touchending, extent = defaultExtent, filter = defaultFilter$1, touchable = defaultTouchable$1, keys = !0, listeners = dispatch("start", "brush", "end"), handleSize = 6;
function brush(group) {
var overlay = group.property("__brush", initialize).selectAll(".overlay").data([
type("overlay")
]);
overlay.enter().append("rect").attr("class", "overlay").attr("pointer-events", "all").attr("cursor", cursors.overlay).merge(overlay).each(function() {
var extent = local$1(this).extent;
select(this).attr("x", extent[0][0]).attr("y", extent[0][1]).attr("width", extent[1][0] - extent[0][0]).attr("height", extent[1][1] - extent[0][1]);
}), group.selectAll(".selection").data([
type("selection")
]).enter().append("rect").attr("class", "selection").attr("cursor", cursors.selection).attr("fill", "#777").attr("fill-opacity", 0.3).attr("stroke", "#fff").attr("shape-rendering", "crispEdges");
var handle = group.selectAll(".handle").data(dim.handles, function(d) {
return d.type;
});
handle.exit().remove(), handle.enter().append("rect").attr("class", function(d) {
return "handle handle--" + d.type;
}).attr("cursor", function(d) {
return cursors[d.type];
}), group.each(redraw).attr("fill", "none").attr("pointer-events", "all").on("mousedown.brush", started).filter(touchable).on("touchstart.brush", started).on("touchmove.brush", touchmoved).on("touchend.brush touchcancel.brush", touchended).style("touch-action", "none").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)");
}
function redraw() {
var group = select(this), selection = local$1(this).selection;
selection ? (group.selectAll(".selection").style("display", null).attr("x", selection[0][0]).attr("y", selection[0][1]).attr("width", selection[1][0] - selection[0][0]).attr("height", selection[1][1] - selection[0][1]), group.selectAll(".handle").style("display", null).attr("x", function(d) {
return "e" === d.type[d.type.length - 1] ? selection[1][0] - handleSize / 2 : selection[0][0] - handleSize / 2;
}).attr("y", function(d) {
return "s" === d.type[0] ? selection[1][1] - handleSize / 2 : selection[0][1] - handleSize / 2;
}).attr("width", function(d) {
return "n" === d.type || "s" === d.type ? selection[1][0] - selection[0][0] + handleSize : handleSize;
}).attr("height", function(d) {
return "e" === d.type || "w" === d.type ? selection[1][1] - selection[0][1] + handleSize : handleSize;
})) : group.selectAll(".selection,.handle").style("display", "none").attr("x", null).attr("y", null).attr("width", null).attr("height", null);
}
function emitter(that, args, clean) {
var emit = that.__brush.emitter;
return !emit || clean && emit.clean ? new Emitter(that, args, clean) : emit;
}
function Emitter(that, args, clean) {
this.that = that, this.args = args, this.state = that.__brush, this.active = 0, this.clean = clean;
}
function started(event) {
if ((!touchending || event.touches) && filter.apply(this, arguments)) {
var w0, w1, n0, n1, e0, e1, s0, s1, moving, lockX, lockY, that = this, type = event.target.__data__.type, mode = (keys && event.metaKey ? type = "overlay" : type) === "selection" ? MODE_DRAG : keys && event.altKey ? MODE_CENTER : MODE_HANDLE, signX = dim === Y ? null : signsX[type], signY = dim === X ? null : signsY[type], state = local$1(that), extent = state.extent, selection = state.selection, W = extent[0][0], N = extent[0][1], E = extent[1][0], S = extent[1][1], dx = 0, dy = 0, shifting = signX && signY && keys && event.shiftKey, points = Array.from(event.touches || [
event
], (t)=>{
const i = t.identifier;
return (t = pointer(t, that)).point0 = t.slice(), t.identifier = i, t;
});
if ("overlay" === type) {
selection && (moving = !0);
const pts = [
points[0],
points[1] || points[0]
];
state.selection = selection = [
[
w0 = dim === Y ? W : min$1(pts[0][0], pts[1][0]),
n0 = dim === X ? N : min$1(pts[0][1], pts[1][1])
],
[
e0 = dim === Y ? E : max$1(pts[0][0], pts[1][0]),
s0 = dim === X ? S : max$1(pts[0][1], pts[1][1])
]
], points.length > 1 && move();
} else w0 = selection[0][0], n0 = selection[0][1], e0 = selection[1][0], s0 = selection[1][1];
w1 = w0, n1 = n0, e1 = e0, s1 = s0;
var group = select(that).attr("pointer-events", "none"), overlay = group.selectAll(".overlay").attr("cursor", cursors[type]);
interrupt(that);
var emit = emitter(that, arguments, !0).beforestart();
if (event.touches) emit.moved = moved, emit.ended = ended;
else {
var view = select(event.view).on("mousemove.brush", moved, !0).on("mouseup.brush", ended, !0);
keys && view.on("keydown.brush", function(event) {
switch(event.keyCode){
case 16:
shifting = signX && signY;
break;
case 18:
mode === MODE_HANDLE && (signX && (e0 = e1 - dx * signX, w0 = w1 + dx * signX), signY && (s0 = s1 - dy * signY, n0 = n1 + dy * signY), mode = MODE_CENTER, move());
break;
case 32:
(mode === MODE_HANDLE || mode === MODE_CENTER) && (signX < 0 ? e0 = e1 - dx : signX > 0 && (w0 = w1 - dx), signY < 0 ? s0 = s1 - dy : signY > 0 && (n0 = n1 - dy), mode = MODE_SPACE, overlay.attr("cursor", cursors.selection), move());
break;
default:
return;
}
noevent$1(event);
}, !0).on("keyup.brush", function(event) {
switch(event.keyCode){
case 16:
shifting && (lockX = lockY = shifting = !1, move());
break;
case 18:
mode === MODE_CENTER && (signX < 0 ? e0 = e1 : signX > 0 && (w0 = w1), signY < 0 ? s0 = s1 : signY > 0 && (n0 = n1), mode = MODE_HANDLE, move());
break;
case 32:
mode === MODE_SPACE && (event.altKey ? (signX && (e0 = e1 - dx * signX, w0 = w1 + dx * signX), signY && (s0 = s1 - dy * signY, n0 = n1 + dy * signY), mode = MODE_CENTER) : (signX < 0 ? e0 = e1 : signX > 0 && (w0 = w1), signY < 0 ? s0 = s1 : signY > 0 && (n0 = n1), mode = MODE_HANDLE), overlay.attr("cursor", cursors[type]), move());
break;
default:
return;
}
noevent$1(event);
}, !0), dragDisable(event.view);
}
redraw.call(that), emit.start(event, mode.name);
}
function moved(event) {
for (const p of event.changedTouches || [
event
])for (const d of points)d.identifier === p.identifier && (d.cur = pointer(p, that));
if (shifting && !lockX && !lockY && 1 === points.length) {
const point = points[0];
abs(point.cur[0] - point[0]) > abs(point.cur[1] - point[1]) ? lockY = !0 : lockX = !0;
}
for (const point of points)point.cur && (point[0] = point.cur[0], point[1] = point.cur[1]);
moving = !0, noevent$1(event), move(event);
}
function move(event) {
var t;
const point = points[0], point0 = point.point0;
switch(dx = point[0] - point0[0], dy = point[1] - point0[1], mode){
case MODE_SPACE:
case MODE_DRAG:
signX && (dx = max$1(W - w0, min$1(E - e0, dx)), w1 = w0 + dx, e1 = e0 + dx), signY && (dy = max$1(N - n0, min$1(S - s0, dy)), n1 = n0 + dy, s1 = s0 + dy);
break;
case MODE_HANDLE:
points[1] ? (signX && (w1 = max$1(W, min$1(E, points[0][0])), e1 = max$1(W, min$1(E, points[1][0])), signX = 1), signY && (n1 = max$1(N, min$1(S, points[0][1])), s1 = max$1(N, min$1(S, points[1][1])), signY = 1)) : (signX < 0 ? (dx = max$1(W - w0, min$1(E - w0, dx)), w1 = w0 + dx, e1 = e0) : signX > 0 && (dx = max$1(W - e0, min$1(E - e0, dx)), w1 = w0, e1 = e0 + dx), signY < 0 ? (dy = max$1(N - n0, min$1(S - n0, dy)), n1 = n0 + dy, s1 = s0) : signY > 0 && (dy = max$1(N - s0, min$1(S - s0, dy)), n1 = n0, s1 = s0 + dy));
break;
case MODE_CENTER:
signX && (w1 = max$1(W, min$1(E, w0 - dx * signX)), e1 = max$1(W, min$1(E, e0 + dx * signX))), signY && (n1 = max$1(N, min$1(S, n0 - dy * signY)), s1 = max$1(N, min$1(S, s0 + dy * signY)));
}
e1 < w1 && (signX *= -1, t = w0, w0 = e0, e0 = t, t = w1, w1 = e1, e1 = t, type in flipX && overlay.attr("cursor", cursors[type = flipX[type]])), s1 < n1 && (signY *= -1, t = n0, n0 = s0, s0 = t, t = n1, n1 = s1, s1 = t, type in flipY && overlay.attr("cursor", cursors[type = flipY[type]])), state.selection && (selection = state.selection), lockX && (w1 = selection[0][0], e1 = selection[1][0]), lockY && (n1 = selection[0][1], s1 = selection[1][1]), (selection[0][0] !== w1 || selection[0][1] !== n1 || selection[1][0] !== e1 || selection[1][1] !== s1) && (state.selection = [
[
w1,
n1
],
[
e1,
s1
]
], redraw.call(that), emit.brush(event, mode.name));
}
function ended(event) {
var extent;
if (!function(event) {
event.stopImmediatePropagation();
}(event), event.touches) {
if (event.touches.length) return;
touchending && clearTimeout(touchending), touchending = setTimeout(function() {
touchending = null;
}, 500);
} else yesdrag(event.view, moving), view.on("keydown.brush keyup.brush mousemove.brush mouseup.brush", null);
group.attr("pointer-events", "all"), overlay.attr("cursor", cursors.overlay), state.selection && (selection = state.selection), ((extent = selection)[0][0] === extent[1][0] || extent[0][1] === extent[1][1]) && (state.selection = null, redraw.call(that)), emit.end(event, mode.name);
}
}
function touchmoved(event) {
emitter(this, arguments).moved(event);
}
function touchended(event) {
emitter(this, arguments).ended(event);
}
function initialize() {
var state = this.__brush || {
selection: null
};
return state.extent = number2(extent.apply(this, arguments)), state.dim = dim, state;
}
return brush.move = function(group, selection) {
group.tween ? group.on("start.brush", function(event) {
emitter(this, arguments).beforestart().start(event);
}).on("interrupt.brush end.brush", function(event) {
emitter(this, arguments).end(event);
}).tween("brush", function() {
var that = this, state = that.__brush, emit = emitter(that, arguments), selection0 = state.selection, selection1 = dim.input("function" == typeof selection ? selection.apply(this, arguments) : selection, state.extent), i = interpolate(selection0, selection1);
function tween(t) {
state.selection = 1 === t && null === selection1 ? null : i(t), redraw.call(that), emit.brush();
}
return null !== selection0 && null !== selection1 ? tween : tween(1);
}) : group.each(function() {
var args = arguments, state = this.__brush, selection1 = dim.input("function" == typeof selection ? selection.apply(this, args) : selection, state.extent), emit = emitter(this, args).beforestart();
interrupt(this), state.selection = null === selection1 ? null : selection1, redraw.call(this), emit.start().brush().end();
});
}, brush.clear = function(group) {
brush.move(group, null);
}, Emitter.prototype = {
beforestart: function() {
return 1 == ++this.active && (this.state.emitter = this, this.starting = !0), this;
},
start: function(event, mode) {
return this.starting ? (this.starting = !1, this.emit("start", event, mode)) : this.emit("brush", event), this;
},
brush: function(event, mode) {
return this.emit("brush", event, mode), this;
},
end: function(event, mode) {
return 0 == --this.active && (delete this.state.emitter, this.emit("end", event, mode)), this;
},
emit: function(type, event, mode) {
var d = select(this.that).datum();
listeners.call(type, this.that, new BrushEvent(type, {
sourceEvent: event,
target: brush,
selection: dim.output(this.state.selection),
mode,
dispatch: listeners
}), d);
}
}, brush.extent = function(_) {
return arguments.length ? (extent = "function" == typeof _ ? _ : constant$4(number2(_)), brush) : extent;
}, brush.filter = function(_) {
return arguments.length ? (filter = "function" == typeof _ ? _ : constant$4(!!_), brush) : filter;
}, brush.touchable = function(_) {
return arguments.length ? (touchable = "function" == typeof _ ? _ : constant$4(!!_), brush) : touchable;
}, brush.handleSize = function(_) {
return arguments.length ? (handleSize = +_, brush) : handleSize;
}, brush.keyModifiers = function(_) {
return arguments.length ? (keys = !!_, brush) : keys;
}, brush.on = function() {
var value = listeners.on.apply(listeners, arguments);
return value === listeners ? brush : value;
}, brush;
}
var abs$1 = Math.abs, cos = Math.cos, sin = Math.sin, pi$1 = Math.PI, halfPi$1 = pi$1 / 2, tau$1 = 2 * pi$1, max$2 = Math.max;
function range(i, j) {
return Array.from({
length: j - i
}, (_, k)=>i + k);
}
function chord$1(directed, transpose) {
var padAngle = 0, sortGroups = null, sortSubgroups = null, sortChords = null;
function chord(matrix) {
var dx, n = matrix.length, groupSums = Array(n), groupIndex = range(0, n), chords = Array(n * n), groups = Array(n), k = 0;
matrix = Float64Array.from({
length: n * n
}, transpose ? (_, i)=>matrix[i % n][i / n | 0] : (_, i)=>matrix[i / n | 0][i % n]);
// Compute the scaling factor from value to angle in [0, 2pi].
for(let i = 0; i < n; ++i){
let x = 0;
for(let j = 0; j < n; ++j)x += matrix[i * n + j] + directed * matrix[j * n + i];
k += groupSums[i] = x;
}
dx = (k = max$2(0, tau$1 - padAngle * n) / k) ? padAngle : tau$1 / n;
// Compute the angles for each group and constituent chord.
{
let x = 0;
for (const i of (sortGroups && groupIndex.sort((a, b)=>sortGroups(groupSums[a], groupSums[b])), groupIndex)){
const x0 = x;
if (directed) {
const subgroupIndex = range(~n + 1, n).filter((j)=>j < 0 ? matrix[~j * n + i] : matrix[i * n + j]);
for (const j of (sortSubgroups && subgroupIndex.sort((a, b)=>sortSubgroups(a < 0 ? -matrix[~a * n + i] : matrix[i * n + a], b < 0 ? -matrix[~b * n + i] : matrix[i * n + b])), subgroupIndex))j < 0 ? (chords[~j * n + i] || (chords[~j * n + i] = {
source: null,
target: null
})).target = {
index: i,
startAngle: x,
endAngle: x += matrix[~j * n + i] * k,
value: matrix[~j * n + i]
} : (chords[i * n + j] || (chords[i * n + j] = {
source: null,
target: null
})).source = {
index: i,
startAngle: x,
endAngle: x += matrix[i * n + j] * k,
value: matrix[i * n + j]
};
groups[i] = {
index: i,
startAngle: x0,
endAngle: x,
value: groupSums[i]
};
} else {
const subgroupIndex = range(0, n).filter((j)=>matrix[i * n + j] || matrix[j * n + i]);
for (const j of (sortSubgroups && subgroupIndex.sort((a, b)=>sortSubgroups(matrix[i * n + a], matrix[i * n + b])), subgroupIndex)){
let chord;
if (i < j ? (chord = chords[i * n + j] || (chords[i * n + j] = {
source: null,
target: null
})).source = {
index: i,
startAngle: x,
endAngle: x += matrix[i * n + j] * k,
value: matrix[i * n + j]
} : ((chord = chords[j * n + i] || (chords[j * n + i] = {
source: null,
target: null
})).target = {
index: i,
startAngle: x,
endAngle: x += matrix[i * n + j] * k,
value: matrix[i * n + j]
}, i === j && (chord.source = chord.target)), chord.source && chord.target && chord.source.value < chord.target.value) {
const source = chord.source;
chord.source = chord.target, chord.target = source;
}
}
groups[i] = {
index: i,
startAngle: x0,
endAngle: x,
value: groupSums[i]
};
}
x += dx;
}
}
return(// Remove empty chords.
(chords = Object.values(chords)).groups = groups, sortChords ? chords.sort(sortChords) : chords);
}
return chord.padAngle = function(_) {
return arguments.length ? (padAngle = max$2(0, _), chord) : padAngle;
}, chord.sortGroups = function(_) {
return arguments.length ? (sortGroups = _, chord) : sortGroups;
}, chord.sortSubgroups = function(_) {
return arguments.length ? (sortSubgroups = _, chord) : sortSubgroups;
}, chord.sortChords = function(_) {
return arguments.length ? (null == _ ? sortChords = null : (sortChords = function(a, b) {
return _(a.source.value + a.target.value, b.source.value + b.target.value);
})._ = _, chord) : sortChords && sortChords._;
}, chord;
}
const pi$2 = Math.PI, tau$2 = 2 * pi$2, tauEpsilon = tau$2 - 1e-6;
function Path() {
this._x0 = this._y0 = this._x1 = this._y1 = null, this._ = "";
}
function path() {
return new Path;
}
Path.prototype = path.prototype = {
constructor: Path,
moveTo: function(x, y) {
this._ += "M" + (this._x0 = this._x1 = +x) + "," + (this._y0 = this._y1 = +y);
},
closePath: function() {
null !== this._x1 && (this._x1 = this._x0, this._y1 = this._y0, this._ += "Z");
},
lineTo: function(x, y) {
this._ += "L" + (this._x1 = +x) + "," + (this._y1 = +y);
},
quadraticCurveTo: function(x1, y1, x, y) {
this._ += "Q" + +x1 + "," + +y1 + "," + (this._x1 = +x) + "," + (this._y1 = +y);
},
bezierCurveTo: function(x1, y1, x2, y2, x, y) {
this._ += "C" + +x1 + "," + +y1 + "," + +x2 + "," + +y2 + "," + (this._x1 = +x) + "," + (this._y1 = +y);
},
arcTo: function(x1, y1, x2, y2, r) {
x1 *= 1, y1 *= 1, x2 *= 1, y2 *= 1, r *= 1;
var x0 = this._x1, y0 = this._y1, x21 = x2 - x1, y21 = y2 - y1, x01 = x0 - x1, y01 = y0 - y1, l01_2 = x01 * x01 + y01 * y01;
// Is the radius negative? Error.
if (r < 0) throw Error("negative radius: " + r);
// Is this path empty? Move to (x1,y1).
if (null === this._x1) this._ += "M" + (this._x1 = x1) + "," + (this._y1 = y1);
else if (l01_2 > 1e-6) {
if (Math.abs(y01 * x21 - y21 * x01) > 1e-6 && r) {
var x20 = x2 - x0, y20 = y2 - y0, l21_2 = x21 * x21 + y21 * y21, l21 = Math.sqrt(l21_2), l01 = Math.sqrt(l01_2), l = r * Math.tan((pi$2 - Math.acos((l21_2 + l01_2 - (x20 * x20 + y20 * y20)) / (2 * l21 * l01))) / 2), t01 = l / l01, t21 = l / l21;
Math.abs(t01 - 1) > 1e-6 && (this._ += "L" + (x1 + t01 * x01) + "," + (y1 + t01 * y01)), this._ += "A" + r + "," + r + ",0,0," + +(y01 * x20 > x01 * y20) + "," + (this._x1 = x1 + t21 * x21) + "," + (this._y1 = y1 + t21 * y21);
} else this._ += "L" + (this._x1 = x1) + "," + (this._y1 = y1);
}
},
arc: function(x, y, r, a0, a1, ccw) {
x *= 1, y *= 1, r *= 1, ccw = !!ccw;
var dx = r * Math.cos(a0), dy = r * Math.sin(a0), x0 = x + dx, y0 = y + dy, cw = 1 ^ ccw, da = ccw ? a0 - a1 : a1 - a0;
// Is the radius negative? Error.
if (r < 0) throw Error("negative radius: " + r);
null === this._x1 ? this._ += "M" + x0 + "," + y0 : (Math.abs(this._x1 - x0) > 1e-6 || Math.abs(this._y1 - y0) > 1e-6) && (this._ += "L" + x0 + "," + y0), r && (da < 0 && (da = da % tau$2 + tau$2), da > tauEpsilon ? this._ += "A" + r + "," + r + ",0,1," + cw + "," + (x - dx) + "," + (y - dy) + "A" + r + "," + r + ",0,1," + cw + "," + (this._x1 = x0) + "," + (this._y1 = y0) : da > 1e-6 && (this._ += "A" + r + "," + r + ",0," + +(da >= pi$2) + "," + cw + "," + (this._x1 = x + r * Math.cos(a1)) + "," + (this._y1 = y + r * Math.sin(a1))));
},
rect: function(x, y, w, h) {
this._ += "M" + (this._x0 = this._x1 = +x) + "," + (this._y0 = this._y1 = +y) + "h" + +w + "v" + +h + "h" + -w + "Z";
},
toString: function() {
return this._;
}
};
var slice$2 = Array.prototype.slice;
function constant$5(x) {
return function() {
return x;
};
}
function defaultSource(d) {
return d.source;
}
function defaultTarget(d) {
return d.target;
}
function defaultRadius(d) {
return d.radius;
}
function defaultStartAngle(d) {
return d.startAngle;
}
function defaultEndAngle(d) {
return d.endAngle;
}
function defaultPadAngle() {
return 0;
}
function defaultArrowheadRadius() {
return 10;
}
function ribbon(headRadius) {
var source = defaultSource, target = defaultTarget, sourceRadius = defaultRadius, targetRadius = defaultRadius, startAngle = defaultStartAngle, endAngle = defaultEndAngle, padAngle = defaultPadAngle, context = null;
function ribbon() {
var buffer, s = source.apply(this, arguments), t = target.apply(this, arguments), ap = padAngle.apply(this, arguments) / 2, argv = slice$2.call(arguments), sr = +sourceRadius.apply(this, (argv[0] = s, argv)), sa0 = startAngle.apply(this, argv) - halfPi$1, sa1 = endAngle.apply(this, argv) - halfPi$1, tr = +targetRadius.apply(this, (argv[0] = t, argv)), ta0 = startAngle.apply(this, argv) - halfPi$1, ta1 = endAngle.apply(this, argv) - halfPi$1;
if (context || (context = buffer = path()), ap > 1e-12 && (abs$1(sa1 - sa0) > 2 * ap + 1e-12 ? sa1 > sa0 ? (sa0 += ap, sa1 -= ap) : (sa0 -= ap, sa1 += ap) : sa0 = sa1 = (sa0 + sa1) / 2, abs$1(ta1 - ta0) > 2 * ap + 1e-12 ? ta1 > ta0 ? (ta0 += ap, ta1 -= ap) : (ta0 -= ap, ta1 += ap) : ta0 = ta1 = (ta0 + ta1) / 2), context.moveTo(sr * cos(sa0), sr * sin(sa0)), context.arc(0, 0, sr, sa0, sa1), sa0 !== ta0 || sa1 !== ta1) {
if (headRadius) {
var hr = +headRadius.apply(this, arguments), tr2 = tr - hr, ta2 = (ta0 + ta1) / 2;
context.quadraticCurveTo(0, 0, tr2 * cos(ta0), tr2 * sin(ta0)), context.lineTo(tr * cos(ta2), tr * sin(ta2)), context.lineTo(tr2 * cos(ta1), tr2 * sin(ta1));
} else context.quadraticCurveTo(0, 0, tr * cos(ta0), tr * sin(ta0)), context.arc(0, 0, tr, ta0, ta1);
}
if (context.quadraticCurveTo(0, 0, sr * cos(sa0), sr * sin(sa0)), context.closePath(), buffer) return context = null, buffer + "" || null;
}
return headRadius && (ribbon.headRadius = function(_) {
return arguments.length ? (headRadius = "function" == typeof _ ? _ : constant$5(+_), ribbon) : headRadius;
}), ribbon.radius = function(_) {
return arguments.length ? (sourceRadius = targetRadius = "function" == typeof _ ? _ : constant$5(+_), ribbon) : sourceRadius;
}, ribbon.sourceRadius = function(_) {
return arguments.length ? (sourceRadius = "function" == typeof _ ? _ : constant$5(+_), ribbon) : sourceRadius;
}, ribbon.targetRadius = function(_) {
return arguments.length ? (targetRadius = "function" == typeof _ ? _ : constant$5(+_), ribbon) : targetRadius;
}, ribbon.startAngle = function(_) {
return arguments.length ? (startAngle = "function" == typeof _ ? _ : constant$5(+_), ribbon) : startAngle;
}, ribbon.endAngle = function(_) {
return arguments.length ? (endAngle = "function" == typeof _ ? _ : constant$5(+_), ribbon) : endAngle;
}, ribbon.padAngle = function(_) {
return arguments.length ? (padAngle = "function" == typeof _ ? _ : constant$5(+_), ribbon) : padAngle;
}, ribbon.source = function(_) {
return arguments.length ? (source = _, ribbon) : source;
}, ribbon.target = function(_) {
return arguments.length ? (target = _, ribbon) : target;
}, ribbon.context = function(_) {
return arguments.length ? (context = null == _ ? null : _, ribbon) : context;
}, ribbon;
}
var slice$3 = Array.prototype.slice;
function ascending$2(a, b) {
return a - b;
}
var constant$6 = (x)=>()=>x;
function noop$1() {}
var cases = [
[],
[
[
[
1.0,
1.5
],
[
0.5,
1.0
]
]
],
[
[
[
1.5,
1.0
],
[
1.0,
1.5
]
]
],
[
[
[
1.5,
1.0
],
[
0.5,
1.0
]
]
],
[
[
[
1.0,
0.5
],
[
1.5,
1.0
]
]
],
[
[
[
1.0,
1.5
],
[
0.5,
1.0
]
],
[
[
1.0,
0.5
],
[
1.5,
1.0
]
]
],
[
[
[
1.0,
0.5
],
[
1.0,
1.5
]
]
],
[
[
[
1.0,
0.5
],
[
0.5,
1.0
]
]
],
[
[
[
0.5,
1.0
],
[
1.0,
0.5
]
]
],
[
[
[
1.0,
1.5
],
[
1.0,
0.5
]
]
],
[
[
[
0.5,
1.0
],
[
1.0,
0.5
]
],
[
[
1.5,
1.0
],
[
1.0,
1.5
]
]
],
[
[
[
1.5,
1.0
],
[
1.0,
0.5
]
]
],
[
[
[
0.5,
1.0
],
[
1.5,
1.0
]
]
],
[
[
[
1.0,
1.5
],
[
1.5,
1.0
]
]
],
[
[
[
0.5,
1.0
],
[
1.0,
1.5
]
]
],
[]
];
function contours() {
var dx = 1, dy = 1, threshold = thresholdSturges, smooth = smoothLinear;
function contours(values) {
var tz = threshold(values);
// Convert number of thresholds into uniform thresholds.
if (Array.isArray(tz)) tz = tz.slice().sort(ascending$2);
else {
var domain = extent(values), start = domain[0], stop = domain[1];
tz = tickStep(start, stop, tz), tz = sequence(Math.floor(start / tz) * tz, Math.floor(stop / tz) * tz, tz);
}
return tz.map(function(value) {
return contour(values, value);
});
}
// Accumulate, smooth contour rings, assign holes to exterior rings.
// Based on https://github.com/mbostock/shapefile/blob/v0.6.2/shp/polygon.js
function contour(values, value) {
var polygons = [], holes = [];
return(// Marching squares with isolines stitched into rings.
// Based on https://github.com/topojson/topojson-client/blob/v3.0.0/src/stitch.js
function(values, value, callback) {
var x, y, t0, t1, t2, t3, fragmentByStart = [], fragmentByEnd = [];
for(// Special case for the first row (y = -1, t2 = t3 = 0).
x = y = -1, cases[(t1 = values[0] >= value) << 1].forEach(stitch); ++x < dx - 1;)cases[(t0 = t1) | (t1 = values[x + 1] >= value) << 1].forEach(stitch);
// General case for the intermediate rows.
for(cases[t1 << 0].forEach(stitch); ++y < dy - 1;){
for(x = -1, cases[(t1 = values[y * dx + dx] >= value) << 1 | (t2 = values[y * dx] >= value) << 2].forEach(stitch); ++x < dx - 1;)t0 = t1, t1 = values[y * dx + dx + x + 1] >= value, t3 = t2, cases[t0 | t1 << 1 | (t2 = values[y * dx + x + 1] >= value) << 2 | t3 << 3].forEach(stitch);
cases[t1 | t2 << 3].forEach(stitch);
}
for(// Special case for the last row (y = dy - 1, t0 = t1 = 0).
x = -1, cases[(t2 = values[y * dx] >= value) << 2].forEach(stitch); ++x < dx - 1;)t3 = t2, cases[(t2 = values[y * dx + x + 1] >= value) << 2 | t3 << 3].forEach(stitch);
function stitch(line) {
var f, g, start = [
line[0][0] + x,
line[0][1] + y
], end = [
line[1][0] + x,
line[1][1] + y
], startIndex = index(start), endIndex = index(end);
(f = fragmentByEnd[startIndex]) ? (g = fragmentByStart[endIndex]) ? (delete fragmentByEnd[f.end], delete fragmentByStart[g.start], f === g ? (f.ring.push(end), callback(f.ring)) : fragmentByStart[f.start] = fragmentByEnd[g.end] = {
start: f.start,
end: g.end,
ring: f.ring.concat(g.ring)
}) : (delete fragmentByEnd[f.end], f.ring.push(end), fragmentByEnd[f.end = endIndex] = f) : (f = fragmentByStart[endIndex]) ? (g = fragmentByEnd[startIndex]) ? (delete fragmentByStart[f.start], delete fragmentByEnd[g.end], f === g ? (f.ring.push(end), callback(f.ring)) : fragmentByStart[g.start] = fragmentByEnd[f.end] = {
start: g.start,
end: f.end,
ring: g.ring.concat(f.ring)
}) : (delete fragmentByStart[f.start], f.ring.unshift(start), fragmentByStart[f.start = startIndex] = f) : fragmentByStart[startIndex] = fragmentByEnd[endIndex] = {
start: startIndex,
end: endIndex,
ring: [
start,
end
]
};
}
cases[t2 << 3].forEach(stitch);
}(values, value, function(ring) {
smooth(ring, values, value), function(ring) {
for(var i = 0, n = ring.length, area = ring[n - 1][1] * ring[0][0] - ring[n - 1][0] * ring[0][1]; ++i < n;)area += ring[i - 1][1] * ring[i][0] - ring[i - 1][0] * ring[i][1];
return area;
}(ring) > 0 ? polygons.push([
ring
]) : holes.push(ring);
}), holes.forEach(function(hole) {
for(var polygon, i = 0, n = polygons.length; i < n; ++i)if (-1 !== function(ring, hole) {
for(var c, i = -1, n = hole.length; ++i < n;)if (c = function(ring, point) {
for(var x = point[0], y = point[1], contains = -1, i = 0, n = ring.length, j = n - 1; i < n; j = i++){
var pi = ring[i], xi = pi[0], yi = pi[1], pj = ring[j], xj = pj[0], yj = pj[1];
if (function(a, b, c) {
var i, p, q, r;
return (b[0] - a[0]) * (c[1] - a[1]) == (c[0] - a[0]) * (b[1] - a[1]) && (p = a[i = +(a[0] === b[0])], q = c[i], r = b[i], p <= q && q <= r || r <= q && q <= p);
}(pi, pj, point)) return 0;
yi > y != yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi && (contains = -contains);
}
return contains;
}(ring, hole[i])) return c;
return 0;
}((polygon = polygons[i])[0], hole)) {
polygon.push(hole);
return;
}
}), {
type: "MultiPolygon",
value: value,
coordinates: polygons
});
}
function index(point) {
return 2 * point[0] + point[1] * (dx + 1) * 4;
}
function smoothLinear(ring, values, value) {
ring.forEach(function(point) {
var v0, x = point[0], y = point[1], xt = 0 | x, yt = 0 | y, v1 = values[yt * dx + xt];
x > 0 && x < dx && xt === x && (v0 = values[yt * dx + xt - 1], point[0] = x + (value - v0) / (v1 - v0) - 0.5), y > 0 && y < dy && yt === y && (v0 = values[(yt - 1) * dx + xt], point[1] = y + (value - v0) / (v1 - v0) - 0.5);
});
}
return contours.contour = contour, contours.size = function(_) {
if (!arguments.length) return [
dx,
dy
];
var _0 = Math.floor(_[0]), _1 = Math.floor(_[1]);
if (!(_0 >= 0 && _1 >= 0)) throw Error("invalid size");
return dx = _0, dy = _1, contours;
}, contours.thresholds = function(_) {
return arguments.length ? (threshold = "function" == typeof _ ? _ : Array.isArray(_) ? constant$6(slice$3.call(_)) : constant$6(_), contours) : threshold;
}, contours.smooth = function(_) {
return arguments.length ? (smooth = _ ? smoothLinear : noop$1, contours) : smooth === smoothLinear;
}, contours;
}
// TODO Optimize edge cases.
// TODO Optimize index calculation.
// TODO Optimize arguments.
function blurX(source, target, r) {
for(var n = source.width, m = source.height, w = (r << 1) + 1, j = 0; j < m; ++j)for(var i = 0, sr = 0; i < n + r; ++i)i < n && (sr += source.data[i + j * n]), i >= r && (i >= w && (sr -= source.data[i - w + j * n]), target.data[i - r + j * n] = sr / Math.min(i + 1, n - 1 + w - i, w));
}
// TODO Optimize edge cases.
// TODO Optimize index calculation.
// TODO Optimize arguments.
function blurY(source, target, r) {
for(var n = source.width, m = source.height, w = (r << 1) + 1, i = 0; i < n; ++i)for(var j = 0, sr = 0; j < m + r; ++j)j < m && (sr += source.data[i + j * n]), j >= r && (j >= w && (sr -= source.data[i + (j - w) * n]), target.data[i + (j - r) * n] = sr / Math.min(j + 1, m - 1 + w - j, w));
}
function defaultX(d) {
return d[0];
}
function defaultY(d) {
return d[1];
}
function defaultWeight() {
return 1;
}
const EDGE_STACK = new Uint32Array(512);
class Delaunator {
static from(points, getX = defaultGetX, getY = defaultGetY) {
const n = points.length, coords = new Float64Array(2 * n);
for(let i = 0; i < n; i++){
const p = points[i];
coords[2 * i] = getX(p), coords[2 * i + 1] = getY(p);
}
return new Delaunator(coords);
}
constructor(coords){
const n = coords.length >> 1;
if (n > 0 && 'number' != typeof coords[0]) throw Error('Expected coords to contain numbers.');
this.coords = coords;
// arrays that will store the triangulation graph
const maxTriangles = Math.max(2 * n - 5, 0);
this._triangles = new Uint32Array(3 * maxTriangles), this._halfedges = new Int32Array(3 * maxTriangles), // temporary arrays for tracking the edges of the advancing convex hull
this._hashSize = Math.ceil(Math.sqrt(n)), this._hullPrev = new Uint32Array(n), this._hullNext = new Uint32Array(n), this._hullTri = new Uint32Array(n), this._hullHash = new Int32Array(this._hashSize).fill(-1), // temporary arrays for sorting points
this._ids = new Uint32Array(n), this._dists = new Float64Array(n), this.update();
}
update() {
let i0, i1, i2;
const { coords, _hullPrev: hullPrev, _hullNext: hullNext, _hullTri: hullTri, _hullHash: hullHash } = this, n = coords.length >> 1;
// populate an array of point indices; calculate input data bbox
let minX = 1 / 0, minY = 1 / 0, maxX = -1 / 0, maxY = -1 / 0;
for(let i = 0; i < n; i++){
const x = coords[2 * i], y = coords[2 * i + 1];
x < minX && (minX = x), y < minY && (minY = y), x > maxX && (maxX = x), y > maxY && (maxY = y), this._ids[i] = i;
}
const cx = (minX + maxX) / 2, cy = (minY + maxY) / 2;
let minDist = 1 / 0;
// pick a seed point close to the center
for(let i = 0; i < n; i++){
const d = dist(cx, cy, coords[2 * i], coords[2 * i + 1]);
d < minDist && (i0 = i, minDist = d);
}
const i0x = coords[2 * i0], i0y = coords[2 * i0 + 1];
minDist = 1 / 0;
// find the point closest to the seed
for(let i = 0; i < n; i++){
if (i === i0) continue;
const d = dist(i0x, i0y, coords[2 * i], coords[2 * i + 1]);
d < minDist && d > 0 && (i1 = i, minDist = d);
}
let i1x = coords[2 * i1], i1y = coords[2 * i1 + 1], minRadius = 1 / 0;
// find the third point which forms the smallest circumcircle with the first two
for(let i = 0; i < n; i++){
if (i === i0 || i === i1) continue;
const r = function(ax, ay, bx, by, cx, cy) {
const dx = bx - ax, dy = by - ay, ex = cx - ax, ey = cy - ay, bl = dx * dx + dy * dy, cl = ex * ex + ey * ey, d = 0.5 / (dx * ey - dy * ex), x = (ey * bl - dy * cl) * d, y = (dx * cl - ex * bl) * d;
return x * x + y * y;
}(i0x, i0y, i1x, i1y, coords[2 * i], coords[2 * i + 1]);
r < minRadius && (i2 = i, minRadius = r);
}
let i2x = coords[2 * i2], i2y = coords[2 * i2 + 1];
if (minRadius === 1 / 0) {
// order collinear points by dx (or dy if all x are identical)
// and return the list as a hull
for(let i = 0; i < n; i++)this._dists[i] = coords[2 * i] - coords[0] || coords[2 * i + 1] - coords[1];
quicksort(this._ids, this._dists, 0, n - 1);
const hull = new Uint32Array(n);
let j = 0;
for(let i = 0, d0 = -1 / 0; i < n; i++){
const id = this._ids[i];
this._dists[id] > d0 && (hull[j++] = id, d0 = this._dists[id]);
}
this.hull = hull.subarray(0, j), this.triangles = new Uint32Array(0), this.halfedges = new Uint32Array(0);
return;
}
// swap the order of the seed points for counter-clockwise orientation
if (orient(i0x, i0y, i1x, i1y, i2x, i2y)) {
const i = i1, x = i1x, y = i1y;
i1 = i2, i1x = i2x, i1y = i2y, i2 = i, i2x = x, i2y = y;
}
const center = function(ax, ay, bx, by, cx, cy) {
const dx = bx - ax, dy = by - ay, ex = cx - ax, ey = cy - ay, bl = dx * dx + dy * dy, cl = ex * ex + ey * ey, d = 0.5 / (dx * ey - dy * ex);
return {
x: ax + (ey * bl - dy * cl) * d,
y: ay + (dx * cl - ex * bl) * d
};
}(i0x, i0y, i1x, i1y, i2x, i2y);
this._cx = center.x, this._cy = center.y;
for(let i = 0; i < n; i++)this._dists[i] = dist(coords[2 * i], coords[2 * i + 1], center.x, center.y);
// sort the points by distance from the seed triangle circumcenter
quicksort(this._ids, this._dists, 0, n - 1), // set up the seed triangle as the starting hull
this._hullStart = i0;
let hullSize = 3;
hullNext[i0] = hullPrev[i2] = i1, hullNext[i1] = hullPrev[i0] = i2, hullNext[i2] = hullPrev[i1] = i0, hullTri[i0] = 0, hullTri[i1] = 1, hullTri[i2] = 2, hullHash.fill(-1), hullHash[this._hashKey(i0x, i0y)] = i0, hullHash[this._hashKey(i1x, i1y)] = i1, hullHash[this._hashKey(i2x, i2y)] = i2, this.trianglesLen = 0, this._addTriangle(i0, i1, i2, -1, -1, -1);
for(let k = 0, xp, yp; k < this._ids.length; k++){
const i = this._ids[k], x = coords[2 * i], y = coords[2 * i + 1];
// skip near-duplicate points
if (k > 0 && 0.0000000000000002220446049250313 >= Math.abs(x - xp) && 0.0000000000000002220446049250313 >= Math.abs(y - yp) || (xp = x, yp = y, i === i0 || i === i1 || i === i2)) continue;
// find a visible edge on the convex hull using edge hash
let start = 0;
for(let j = 0, key = this._hashKey(x, y); j < this._hashSize && (-1 === (start = hullHash[(key + j) % this._hashSize]) || start === hullNext[start]); j++);
let e = start = hullPrev[start], q;
for(; q = hullNext[e], !orient(x, y, coords[2 * e], coords[2 * e + 1], coords[2 * q], coords[2 * q + 1]);)if ((e = q) === start) {
e = -1;
break;
}
if (-1 === e) continue; // likely a near-duplicate point; skip it
// add the first triangle from the point
let t = this._addTriangle(e, i, hullNext[e], -1, -1, hullTri[e]);
// recursively flip triangles from the point until they satisfy the Delaunay condition
hullTri[i] = this._legalize(t + 2), hullTri[e] = t, hullSize++;
// walk forward through the hull, adding more triangles and flipping recursively
let n = hullNext[e];
for(; q = hullNext[n], orient(x, y, coords[2 * n], coords[2 * n + 1], coords[2 * q], coords[2 * q + 1]);)t = this._addTriangle(n, i, q, hullTri[i], -1, hullTri[n]), hullTri[i] = this._legalize(t + 2), hullNext[n] = n, hullSize--, n = q;
// walk backward from the other side, adding more triangles and flipping
if (e === start) for(; orient(x, y, coords[2 * (q = hullPrev[e])], coords[2 * q + 1], coords[2 * e], coords[2 * e + 1]);)t = this._addTriangle(q, i, e, -1, hullTri[e], hullTri[q]), this._legalize(t + 2), hullTri[q] = t, hullNext[e] = e, hullSize--, e = q;
// update the hull indices
this._hullStart = hullPrev[i] = e, hullNext[e] = hullPrev[n] = i, hullNext[i] = n, // save the two new edges in the hash table
hullHash[this._hashKey(x, y)] = i, hullHash[this._hashKey(coords[2 * e], coords[2 * e + 1])] = e;
}
this.hull = new Uint32Array(hullSize);
for(let i = 0, e = this._hullStart; i < hullSize; i++)this.hull[i] = e, e = hullNext[e];
// trim typed triangle mesh arrays
this.triangles = this._triangles.subarray(0, this.trianglesLen), this.halfedges = this._halfedges.subarray(0, this.trianglesLen);
}
_hashKey(x, y) {
return Math.floor(// monotonically increases with real angle, but doesn't need expensive trigonometry
function(dx, dy) {
const p = dx / (Math.abs(dx) + Math.abs(dy));
return (dy > 0 ? 3 - p : 1 + p) / 4; // [0..1]
}(x - this._cx, y - this._cy) * this._hashSize) % this._hashSize;
}
_legalize(a) {
const { _triangles: triangles, _halfedges: halfedges, coords } = this;
let i = 0, ar = 0;
// recursion eliminated with a fixed-size stack
for(;;){
const b = halfedges[a], a0 = a - a % 3;
if (ar = a0 + (a + 2) % 3, -1 === b) {
if (0 === i) break;
a = EDGE_STACK[--i];
continue;
}
const b0 = b - b % 3, al = a0 + (a + 1) % 3, bl = b0 + (b + 2) % 3, p0 = triangles[ar], pr = triangles[a], pl = triangles[al], p1 = triangles[bl];
if (function(ax, ay, bx, by, cx, cy, px, py) {
const dx = ax - px, dy = ay - py, ex = bx - px, ey = by - py, fx = cx - px, fy = cy - py, bp = ex * ex + ey * ey, cp = fx * fx + fy * fy;
return dx * (ey * cp - bp * fy) - dy * (ex * cp - bp * fx) + (dx * dx + dy * dy) * (ex * fy - ey * fx) < 0;
}(coords[2 * p0], coords[2 * p0 + 1], coords[2 * pr], coords[2 * pr + 1], coords[2 * pl], coords[2 * pl + 1], coords[2 * p1], coords[2 * p1 + 1])) {
triangles[a] = p1, triangles[b] = p0;
const hbl = halfedges[bl];
// edge swapped on the other side of the hull (rare); fix the halfedge reference
if (-1 === hbl) {
let e = this._hullStart;
do {
if (this._hullTri[e] === bl) {
this._hullTri[e] = a;
break;
}
e = this._hullPrev[e];
}while (e !== this._hullStart)
}
this._link(a, hbl), this._link(b, halfedges[ar]), this._link(ar, bl);
const br = b0 + (b + 1) % 3;
i < EDGE_STACK.length && (EDGE_STACK[i++] = br);
} else {
if (0 === i) break;
a = EDGE_STACK[--i];
}
}
return ar;
}
_link(a, b) {
this._halfedges[a] = b, -1 !== b && (this._halfedges[b] = a);
}
// add a new triangle given vertex indices and adjacent half-edge ids
_addTriangle(i0, i1, i2, a, b, c) {
const t = this.trianglesLen;
return this._triangles[t] = i0, this._triangles[t + 1] = i1, this._triangles[t + 2] = i2, this._link(t, a), this._link(t + 1, b), this._link(t + 2, c), this.trianglesLen += 3, t;
}
}
function dist(ax, ay, bx, by) {
const dx = ax - bx, dy = ay - by;
return dx * dx + dy * dy;
}
// return 2d orientation sign if we're confident in it through J. Shewchuk's error bound check
function orientIfSure(px, py, rx, ry, qx, qy) {
const l = (ry - py) * (qx - px), r = (rx - px) * (qy - py);
return Math.abs(l - r) >= 3.3306690738754716e-16 * Math.abs(l + r) ? l - r : 0;
}
// a more robust orientation test that's stable in a given triangle (to fix robustness issues)
function orient(rx, ry, qx, qy, px, py) {
return 0 > (orientIfSure(px, py, rx, ry, qx, qy) || orientIfSure(rx, ry, qx, qy, px, py) || orientIfSure(qx, qy, px, py, rx, ry));
}
function quicksort(ids, dists, left, right) {
if (right - left <= 20) for(let i = left + 1; i <= right; i++){
const temp = ids[i], tempDist = dists[temp];
let j = i - 1;
for(; j >= left && dists[ids[j]] > tempDist;)ids[j + 1] = ids[j--];
ids[j + 1] = temp;
}
else {
const median = left + right >> 1;
let i = left + 1, j = right;
swap$1(ids, median, i), dists[ids[left]] > dists[ids[right]] && swap$1(ids, left, right), dists[ids[i]] > dists[ids[right]] && swap$1(ids, i, right), dists[ids[left]] > dists[ids[i]] && swap$1(ids, left, i);
const temp = ids[i], tempDist = dists[temp];
for(;;){
do i++;
while (dists[ids[i]] < tempDist)
do j--;
while (dists[ids[j]] > tempDist)
if (j < i) break;
swap$1(ids, i, j);
}
ids[left + 1] = ids[j], ids[j] = temp, right - i + 1 >= j - left ? (quicksort(ids, dists, i, right), quicksort(ids, dists, left, j - 1)) : (quicksort(ids, dists, left, j - 1), quicksort(ids, dists, i, right));
}
}
function swap$1(arr, i, j) {
const tmp = arr[i];
arr[i] = arr[j], arr[j] = tmp;
}
function defaultGetX(p) {
return p[0];
}
function defaultGetY(p) {
return p[1];
}
class Path$1 {
constructor(){
this._x0 = this._y0 = this._x1 = this._y1 = null, this._ = "";
}
moveTo(x, y) {
this._ += `M${this._x0 = this._x1 = +x},${this._y0 = this._y1 = +y}`;
}
closePath() {
null !== this._x1 && (this._x1 = this._x0, this._y1 = this._y0, this._ += "Z");
}
lineTo(x, y) {
this._ += `L${this._x1 = +x},${this._y1 = +y}`;
}
arc(x, y, r) {
x *= 1, y *= 1, r *= 1;
const x0 = x + r, y0 = y;
if (r < 0) throw Error("negative radius");
null === this._x1 ? this._ += `M${x0},${y0}` : (Math.abs(this._x1 - x0) > 1e-6 || Math.abs(this._y1 - y0) > 1e-6) && (this._ += "L" + x0 + "," + y0), r && (this._ += `A${r},${r},0,1,1,${x - r},${y}A${r},${r},0,1,1,${this._x1 = x0},${this._y1 = y0}`);
}
rect(x, y, w, h) {
this._ += `M${this._x0 = this._x1 = +x},${this._y0 = this._y1 = +y}h${+w}v${+h}h${-w}Z`;
}
value() {
return this._ || null;
}
}
class Polygon {
constructor(){
this._ = [];
}
moveTo(x, y) {
this._.push([
x,
y
]);
}
closePath() {
this._.push(this._[0].slice());
}
lineTo(x, y) {
this._.push([
x,
y
]);
}
value() {
return this._.length ? this._ : null;
}
}
class Voronoi {
constructor(delaunay, [xmin, ymin, xmax, ymax] = [
0,
0,
960,
500
]){
if (!((xmax *= 1) >= (xmin *= 1)) || !((ymax *= 1) >= (ymin *= 1))) throw Error("invalid bounds");
this.delaunay = delaunay, this._circumcenters = new Float64Array(2 * delaunay.points.length), this.vectors = new Float64Array(2 * delaunay.points.length), this.xmax = xmax, this.xmin = xmin, this.ymax = ymax, this.ymin = ymin, this._init();
}
update() {
return this.delaunay.update(), this._init(), this;
}
_init() {
const { delaunay: { points, hull, triangles }, vectors } = this, circumcenters = this.circumcenters = this._circumcenters.subarray(0, triangles.length / 3 * 2);
for(let i = 0, j = 0, n = triangles.length, x, y; i < n; i += 3, j += 2){
const t1 = 2 * triangles[i], t2 = 2 * triangles[i + 1], t3 = 2 * triangles[i + 2], x1 = points[t1], y1 = points[t1 + 1], x2 = points[t2], y2 = points[t2 + 1], x3 = points[t3], y3 = points[t3 + 1], dx = x2 - x1, dy = y2 - y1, ex = x3 - x1, ey = y3 - y1, bl = dx * dx + dy * dy, cl = ex * ex + ey * ey, ab = (dx * ey - dy * ex) * 2;
if (ab) {
if (1e-8 > Math.abs(ab)) // almost equal points (degenerate triangle)
x = (x1 + x3) / 2, y = (y1 + y3) / 2;
else {
const d = 1 / ab;
x = x1 + (ey * bl - dy * cl) * d, y = y1 + (dx * cl - ex * bl) * d;
}
} else // degenerate case (collinear diagram)
x = (x1 + x3) / 2 - 1e8 * ey, y = (y1 + y3) / 2 + 1e8 * ex;
circumcenters[j] = x, circumcenters[j + 1] = y;
}
// Compute exterior cell rays.
let h = hull[hull.length - 1], p0, p1 = 4 * h, x0, x1 = points[2 * h], y0, y1 = points[2 * h + 1];
vectors.fill(0);
for(let i = 0; i < hull.length; ++i)h = hull[i], p0 = p1, x0 = x1, y0 = y1, p1 = 4 * h, x1 = points[2 * h], y1 = points[2 * h + 1], vectors[p0 + 2] = vectors[p1] = y0 - y1, vectors[p0 + 3] = vectors[p1 + 1] = x1 - x0;
}
render(context) {
const buffer = null == context ? context = new Path$1 : void 0, { delaunay: { halfedges, inedges, hull }, circumcenters, vectors } = this;
if (hull.length <= 1) return null;
for(let i = 0, n = halfedges.length; i < n; ++i){
const j = halfedges[i];
if (j < i) continue;
const ti = 2 * Math.floor(i / 3), tj = 2 * Math.floor(j / 3), xi = circumcenters[ti], yi = circumcenters[ti + 1], xj = circumcenters[tj], yj = circumcenters[tj + 1];
this._renderSegment(xi, yi, xj, yj, context);
}
let h0, h1 = hull[hull.length - 1];
for(let i = 0; i < hull.length; ++i){
h0 = h1;
const t = 2 * Math.floor(inedges[h1 = hull[i]] / 3), x = circumcenters[t], y = circumcenters[t + 1], v = 4 * h0, p = this._project(x, y, vectors[v + 2], vectors[v + 3]);
p && this._renderSegment(x, y, p[0], p[1], context);
}
return buffer && buffer.value();
}
renderBounds(context) {
const buffer = null == context ? context = new Path$1 : void 0;
return context.rect(this.xmin, this.ymin, this.xmax - this.xmin, this.ymax - this.ymin), buffer && buffer.value();
}
renderCell(i, context) {
const buffer = null == context ? context = new Path$1 : void 0, points = this._clip(i);
if (null === points || !points.length) return;
context.moveTo(points[0], points[1]);
let n = points.length;
for(; points[0] === points[n - 2] && points[1] === points[n - 1] && n > 1;)n -= 2;
for(let i = 2; i < n; i += 2)(points[i] !== points[i - 2] || points[i + 1] !== points[i - 1]) && context.lineTo(points[i], points[i + 1]);
return context.closePath(), buffer && buffer.value();
}
*cellPolygons() {
const { delaunay: { points } } = this;
for(let i = 0, n = points.length / 2; i < n; ++i){
const cell = this.cellPolygon(i);
cell && (cell.index = i, yield cell);
}
}
cellPolygon(i) {
const polygon = new Polygon;
return this.renderCell(i, polygon), polygon.value();
}
_renderSegment(x0, y0, x1, y1, context) {
let S;
const c0 = this._regioncode(x0, y0), c1 = this._regioncode(x1, y1);
0 === c0 && 0 === c1 ? (context.moveTo(x0, y0), context.lineTo(x1, y1)) : (S = this._clipSegment(x0, y0, x1, y1, c0, c1)) && (context.moveTo(S[0], S[1]), context.lineTo(S[2], S[3]));
}
contains(i, x, y) {
return (x *= 1) == x && (y *= 1) == y && this.delaunay._step(i, x, y) === i;
}
*neighbors(i) {
const ci = this._clip(i);
if (ci) for (const j of this.delaunay.neighbors(i)){
const cj = this._clip(j);
// find the common edge
if (cj) {
loop: for(let ai = 0, li = ci.length; ai < li; ai += 2)for(let aj = 0, lj = cj.length; aj < lj; aj += 2)if (ci[ai] == cj[aj] && ci[ai + 1] == cj[aj + 1] && ci[(ai + 2) % li] == cj[(aj + lj - 2) % lj] && ci[(ai + 3) % li] == cj[(aj + lj - 1) % lj]) {
yield j;
break loop;
}
}
}
}
_cell(i) {
const { circumcenters, delaunay: { inedges, halfedges, triangles } } = this, e0 = inedges[i];
if (-1 === e0) return null; // coincident point
const points = [];
let e = e0;
do {
const t = Math.floor(e / 3);
if (points.push(circumcenters[2 * t], circumcenters[2 * t + 1]), triangles[e = e % 3 == 2 ? e - 2 : e + 1] !== i) break; // bad triangulation
e = halfedges[e];
}while (e !== e0 && -1 !== e)
return points;
}
_clip(i) {
// degenerate case (1 valid point: return the box)
if (0 === i && 1 === this.delaunay.hull.length) return [
this.xmax,
this.ymin,
this.xmax,
this.ymax,
this.xmin,
this.ymax,
this.xmin,
this.ymin
];
const points = this._cell(i);
if (null === points) return null;
const { vectors: V } = this, v = 4 * i;
return V[v] || V[v + 1] ? this._clipInfinite(i, points, V[v], V[v + 1], V[v + 2], V[v + 3]) : this._clipFinite(i, points);
}
_clipFinite(i, points) {
let e0, e1;
const n = points.length;
let P = null, x0, y0, x1 = points[n - 2], y1 = points[n - 1], c0, c1 = this._regioncode(x1, y1);
for(let j = 0; j < n; j += 2)if (x0 = x1, y0 = y1, x1 = points[j], y1 = points[j + 1], c0 = c1, c1 = this._regioncode(x1, y1), 0 === c0 && 0 === c1) e0 = e1, e1 = 0, P ? P.push(x1, y1) : P = [
x1,
y1
];
else {
let S, sx0, sy0, sx1, sy1;
if (0 === c0) {
if (null === (S = this._clipSegment(x0, y0, x1, y1, c0, c1))) continue;
[sx0, sy0, sx1, sy1] = S;
} else {
if (null === (S = this._clipSegment(x1, y1, x0, y0, c1, c0))) continue;
[sx1, sy1, sx0, sy0] = S, e0 = e1, e1 = this._edgecode(sx0, sy0), e0 && e1 && this._edge(i, e0, e1, P, P.length), P ? P.push(sx0, sy0) : P = [
sx0,
sy0
];
}
e0 = e1, e1 = this._edgecode(sx1, sy1), e0 && e1 && this._edge(i, e0, e1, P, P.length), P ? P.push(sx1, sy1) : P = [
sx1,
sy1
];
}
if (P) e0 = e1, e1 = this._edgecode(P[0], P[1]), e0 && e1 && this._edge(i, e0, e1, P, P.length);
else if (this.contains(i, (this.xmin + this.xmax) / 2, (this.ymin + this.ymax) / 2)) return [
this.xmax,
this.ymin,
this.xmax,
this.ymax,
this.xmin,
this.ymax,
this.xmin,
this.ymin
];
return P;
}
_clipSegment(x0, y0, x1, y1, c0, c1) {
for(;;){
if (0 === c0 && 0 === c1) return [
x0,
y0,
x1,
y1
];
if (c0 & c1) return null;
let x, y, c = c0 || c1;
0b1000 & c ? (x = x0 + (x1 - x0) * (this.ymax - y0) / (y1 - y0), y = this.ymax) : 0b0100 & c ? (x = x0 + (x1 - x0) * (this.ymin - y0) / (y1 - y0), y = this.ymin) : 0b0010 & c ? (y = y0 + (y1 - y0) * (this.xmax - x0) / (x1 - x0), x = this.xmax) : (y = y0 + (y1 - y0) * (this.xmin - x0) / (x1 - x0), x = this.xmin), c0 ? (x0 = x, y0 = y, c0 = this._regioncode(x0, y0)) : (x1 = x, y1 = y, c1 = this._regioncode(x1, y1));
}
}
_clipInfinite(i, points, vx0, vy0, vxn, vyn) {
let P = Array.from(points), p;
if ((p = this._project(P[0], P[1], vx0, vy0)) && P.unshift(p[0], p[1]), (p = this._project(P[P.length - 2], P[P.length - 1], vxn, vyn)) && P.push(p[0], p[1]), P = this._clipFinite(i, P)) for(let j = 0, n = P.length, c0, c1 = this._edgecode(P[n - 2], P[n - 1]); j < n; j += 2)c0 = c1, c1 = this._edgecode(P[j], P[j + 1]), c0 && c1 && (j = this._edge(i, c0, c1, P, j), n = P.length);
else this.contains(i, (this.xmin + this.xmax) / 2, (this.ymin + this.ymax) / 2) && (P = [
this.xmin,
this.ymin,
this.xmax,
this.ymin,
this.xmax,
this.ymax,
this.xmin,
this.ymax
]);
return P;
}
_edge(i, e0, e1, P, j) {
for(; e0 !== e1;){
let x, y;
switch(e0){
case 0b0101:
e0 = 0b0100;
continue; // top-left
case 0b0100:
e0 = 0b0110, x = this.xmax, y = this.ymin;
break; // top
case 0b0110:
e0 = 0b0010;
continue; // top-right
case 0b0010:
e0 = 0b1010, x = this.xmax, y = this.ymax;
break; // right
case 0b1010:
e0 = 0b1000;
continue; // bottom-right
case 0b1000:
e0 = 0b1001, x = this.xmin, y = this.ymax;
break; // bottom
case 0b1001:
e0 = 0b0001;
continue; // bottom-left
case 0b0001:
e0 = 0b0101, x = this.xmin, y = this.ymin;
}
(P[j] !== x || P[j + 1] !== y) && this.contains(i, x, y) && (P.splice(j, 0, x, y), j += 2);
}
if (P.length > 4) for(let i = 0; i < P.length; i += 2){
const j = (i + 2) % P.length, k = (i + 4) % P.length;
(P[i] === P[j] && P[j] === P[k] || P[i + 1] === P[j + 1] && P[j + 1] === P[k + 1]) && (P.splice(j, 2), i -= 2);
}
return j;
}
_project(x0, y0, vx, vy) {
let t = 1 / 0, c, x, y;
if (vy < 0) {
if (y0 <= this.ymin) return null;
(c = (this.ymin - y0) / vy) < t && (y = this.ymin, x = x0 + (t = c) * vx);
} else if (vy > 0) {
if (y0 >= this.ymax) return null;
(c = (this.ymax - y0) / vy) < t && (y = this.ymax, x = x0 + (t = c) * vx);
}
if (vx > 0) {
if (x0 >= this.xmax) return null;
(c = (this.xmax - x0) / vx) < t && (x = this.xmax, y = y0 + (t = c) * vy);
} else if (vx < 0) {
if (x0 <= this.xmin) return null;
(c = (this.xmin - x0) / vx) < t && (x = this.xmin, y = y0 + (t = c) * vy);
}
return [
x,
y
];
}
_edgecode(x, y) {
return (x === this.xmin ? 0b0001 : 0b0010 * (x === this.xmax)) | (y === this.ymin ? 0b0100 : 0b1000 * (y === this.ymax));
}
_regioncode(x, y) {
return (x < this.xmin ? 0b0001 : 0b0010 * (x > this.xmax)) | (y < this.ymin ? 0b0100 : 0b1000 * (y > this.ymax));
}
}
const tau$3 = 2 * Math.PI, pow = Math.pow;
function pointX(p) {
return p[0];
}
function pointY(p) {
return p[1];
}
class Delaunay {
static from(points, fx = pointX, fy = pointY, that) {
return new Delaunay("length" in points ? function(points, fx, fy, that) {
const n = points.length, array = new Float64Array(2 * n);
for(let i = 0; i < n; ++i){
const p = points[i];
array[2 * i] = fx.call(that, p, i, points), array[2 * i + 1] = fy.call(that, p, i, points);
}
return array;
}(points, fx, fy, that) : Float64Array.from(function*(points, fx, fy, that) {
let i = 0;
for (const p of points)yield fx.call(that, p, i, points), yield fy.call(that, p, i, points), ++i;
}(points, fx, fy, that)));
}
constructor(points){
this._delaunator = new Delaunator(points), this.inedges = new Int32Array(points.length / 2), this._hullIndex = new Int32Array(points.length / 2), this.points = this._delaunator.coords, this._init();
}
update() {
return this._delaunator.update(), this._init(), this;
}
_init() {
const d = this._delaunator, points = this.points;
// check for collinear
if (d.hull && d.hull.length > 2 && // A triangulation is collinear if all its triangles have a non-null area
function(d) {
const { triangles, coords } = d;
for(let i = 0; i < triangles.length; i += 3){
const a = 2 * triangles[i], b = 2 * triangles[i + 1], c = 2 * triangles[i + 2];
if ((coords[c] - coords[a]) * (coords[b + 1] - coords[a + 1]) - (coords[b] - coords[a]) * (coords[c + 1] - coords[a + 1]) > 1e-10) return !1;
}
return !0;
}(d)) {
this.collinear = Int32Array.from({
length: points.length / 2
}, (_, i)=>i).sort((i, j)=>points[2 * i] - points[2 * j] || points[2 * i + 1] - points[2 * j + 1]); // for exact neighbors
const e = this.collinear[0], f = this.collinear[this.collinear.length - 1], bounds = [
points[2 * e],
points[2 * e + 1],
points[2 * f],
points[2 * f + 1]
], r = 1e-8 * Math.hypot(bounds[3] - bounds[1], bounds[2] - bounds[0]);
for(let i = 0, n = points.length / 2; i < n; ++i){
var x, y;
const p = [
(x = points[2 * i]) + Math.sin(x + (y = points[2 * i + 1])) * r,
y + Math.cos(x - y) * r
];
points[2 * i] = p[0], points[2 * i + 1] = p[1];
}
this._delaunator = new Delaunator(points);
} else delete this.collinear;
const halfedges = this.halfedges = this._delaunator.halfedges, hull = this.hull = this._delaunator.hull, triangles = this.triangles = this._delaunator.triangles, inedges = this.inedges.fill(-1), hullIndex = this._hullIndex.fill(-1);
// Compute an index from each point to an (arbitrary) incoming halfedge
// Used to give the first neighbor of each point; for this reason,
// on the hull we give priority to exterior halfedges
for(let e = 0, n = halfedges.length; e < n; ++e){
const p = triangles[e % 3 == 2 ? e - 2 : e + 1];
(-1 === halfedges[e] || -1 === inedges[p]) && (inedges[p] = e);
}
for(let i = 0, n = hull.length; i < n; ++i)hullIndex[hull[i]] = i;
// degenerate case: 1 or 2 (distinct) points
hull.length <= 2 && hull.length > 0 && (this.triangles = new Int32Array(3).fill(-1), this.halfedges = new Int32Array(3).fill(-1), this.triangles[0] = hull[0], this.triangles[1] = hull[1], this.triangles[2] = hull[1], inedges[hull[0]] = 1, 2 === hull.length && (inedges[hull[1]] = 0));
}
voronoi(bounds) {
return new Voronoi(this, bounds);
}
*neighbors(i) {
const { inedges, hull, _hullIndex, halfedges, triangles, collinear } = this;
// degenerate case with several collinear points
if (collinear) {
const l = collinear.indexOf(i);
l > 0 && (yield collinear[l - 1]), l < collinear.length - 1 && (yield collinear[l + 1]);
return;
}
const e0 = inedges[i];
if (-1 === e0) return; // coincident point
let e = e0, p0 = -1;
do {
if (yield p0 = triangles[e], triangles[e = e % 3 == 2 ? e - 2 : e + 1] !== i) return; // bad triangulation
if (-1 === (e = halfedges[e])) {
const p = hull[(_hullIndex[i] + 1) % hull.length];
p !== p0 && (yield p);
return;
}
}while (e !== e0)
}
find(x, y, i = 0) {
let c;
if ((x *= 1) != x || (y *= 1) != y) return -1;
const i0 = i;
for(; (c = this._step(i, x, y)) >= 0 && c !== i && c !== i0;)i = c;
return c;
}
_step(i, x, y) {
const { inedges, hull, _hullIndex, halfedges, triangles, points } = this;
if (-1 === inedges[i] || !points.length) return (i + 1) % (points.length >> 1);
let c = i, dc = pow(x - points[2 * i], 2) + pow(y - points[2 * i + 1], 2);
const e0 = inedges[i];
let e = e0;
do {
let t = triangles[e];
const dt = pow(x - points[2 * t], 2) + pow(y - points[2 * t + 1], 2);
if (dt < dc && (dc = dt, c = t), triangles[e = e % 3 == 2 ? e - 2 : e + 1] !== i) break; // bad triangulation
if (-1 === (e = halfedges[e])) {
if ((e = hull[(_hullIndex[i] + 1) % hull.length]) !== t && pow(x - points[2 * e], 2) + pow(y - points[2 * e + 1], 2) < dc) return e;
break;
}
}while (e !== e0)
return c;
}
render(context) {
const buffer = null == context ? context = new Path$1 : void 0, { points, halfedges, triangles } = this;
for(let i = 0, n = halfedges.length; i < n; ++i){
const j = halfedges[i];
if (j < i) continue;
const ti = 2 * triangles[i], tj = 2 * triangles[j];
context.moveTo(points[ti], points[ti + 1]), context.lineTo(points[tj], points[tj + 1]);
}
return this.renderHull(context), buffer && buffer.value();
}
renderPoints(context, r = 2) {
const buffer = null == context ? context = new Path$1 : void 0, { points } = this;
for(let i = 0, n = points.length; i < n; i += 2){
const x = points[i], y = points[i + 1];
context.moveTo(x + r, y), context.arc(x, y, r, 0, tau$3);
}
return buffer && buffer.value();
}
renderHull(context) {
const buffer = null == context ? context = new Path$1 : void 0, { hull, points } = this, h = 2 * hull[0], n = hull.length;
context.moveTo(points[h], points[h + 1]);
for(let i = 1; i < n; ++i){
const h = 2 * hull[i];
context.lineTo(points[h], points[h + 1]);
}
return context.closePath(), buffer && buffer.value();
}
hullPolygon() {
const polygon = new Polygon;
return this.renderHull(polygon), polygon.value();
}
renderTriangle(i, context) {
const buffer = null == context ? context = new Path$1 : void 0, { points, triangles } = this, t0 = 2 * triangles[i *= 3], t1 = 2 * triangles[i + 1], t2 = 2 * triangles[i + 2];
return context.moveTo(points[t0], points[t0 + 1]), context.lineTo(points[t1], points[t1 + 1]), context.lineTo(points[t2], points[t2 + 1]), context.closePath(), buffer && buffer.value();
}
*trianglePolygons() {
const { triangles } = this;
for(let i = 0, n = triangles.length / 3; i < n; ++i)yield this.trianglePolygon(i);
}
trianglePolygon(i) {
const polygon = new Polygon;
return this.renderTriangle(i, polygon), polygon.value();
}
}
var EOL = {}, EOF = {};
function objectConverter(columns) {
return Function("d", "return {" + columns.map(function(name, i) {
return JSON.stringify(name) + ": d[" + i + "] || \"\"";
}).join(",") + "}");
}
// Compute unique columns in order of discovery.
function inferColumns(rows) {
var columnSet = Object.create(null), columns = [];
return rows.forEach(function(row) {
for(var column in row)column in columnSet || columns.push(columnSet[column] = column);
}), columns;
}
function pad(value, width) {
var s = value + "", length = s.length;
return length < width ? Array(width - length + 1).join(0) + s : s;
}
function dsvFormat(delimiter) {
var reFormat = RegExp("[\"" + delimiter + "\n\r]"), DELIMITER = delimiter.charCodeAt(0);
function parseRows(text, f) {
var t, rows = [], N = text.length, I = 0, n = 0, eof = N <= 0, eol = !1; // current token followed by EOL?
function token() {
if (eof) return EOF;
if (eol) return eol = !1, EOL;
// Unescape quotes.
var i, c, j = I;
if (34 === text.charCodeAt(j)) {
for(; I++ < N && 34 !== text.charCodeAt(I) || 34 === text.charCodeAt(++I););
return (i = I) >= N ? eof = !0 : 10 === (c = text.charCodeAt(I++)) ? eol = !0 : 13 === c && (eol = !0, 10 === text.charCodeAt(I) && ++I), text.slice(j + 1, i - 1).replace(/""/g, "\"");
}
// Find next delimiter or newline.
for(; I < N;){
if (10 === (c = text.charCodeAt(i = I++))) eol = !0;
else if (13 === c) eol = !0, 10 === text.charCodeAt(I) && ++I;
else if (c !== DELIMITER) continue;
return text.slice(j, i);
}
// Return last token before EOF.
return eof = !0, text.slice(j, N);
}
for(10 === text.charCodeAt(N - 1) && --N, 13 === text.charCodeAt(N - 1) && --N; (t = token()) !== EOF;){
for(var row = []; t !== EOL && t !== EOF;)row.push(t), t = token();
f && null == (row = f(row, n++)) || rows.push(row);
}
return rows;
}
function preformatBody(rows, columns) {
return rows.map(function(row) {
return columns.map(function(column) {
return formatValue(row[column]);
}).join(delimiter);
});
}
function formatRow(row) {
return row.map(formatValue).join(delimiter);
}
function formatValue(value) {
var date, hours, minutes, seconds, milliseconds, year;
return null == value ? "" : value instanceof Date ? (hours = (date = value).getUTCHours(), minutes = date.getUTCMinutes(), seconds = date.getUTCSeconds(), milliseconds = date.getUTCMilliseconds(), isNaN(date) ? "Invalid Date" : ((year = date.getUTCFullYear()) < 0 ? "-" + pad(-year, 6) : year > 9999 ? "+" + pad(year, 6) : pad(year, 4)) + "-" + pad(date.getUTCMonth() + 1, 2) + "-" + pad(date.getUTCDate(), 2) + (milliseconds ? "T" + pad(hours, 2) + ":" + pad(minutes, 2) + ":" + pad(seconds, 2) + "." + pad(milliseconds, 3) + "Z" : seconds ? "T" + pad(hours, 2) + ":" + pad(minutes, 2) + ":" + pad(seconds, 2) + "Z" : minutes || hours ? "T" + pad(hours, 2) + ":" + pad(minutes, 2) + "Z" : "")) : reFormat.test(value += "") ? "\"" + value.replace(/"/g, "\"\"") + "\"" : value;
}
return {
parse: function(text, f) {
var convert, columns, rows = parseRows(text, function(row, i) {
var object;
if (convert) return convert(row, i - 1);
columns = row, convert = f ? (object = objectConverter(row), function(row1, i) {
return f(object(row1), i, row);
}) : objectConverter(row);
});
return rows.columns = columns || [], rows;
},
parseRows: parseRows,
format: function(rows, columns) {
return null == columns && (columns = inferColumns(rows)), [
columns.map(formatValue).join(delimiter)
].concat(preformatBody(rows, columns)).join("\n");
},
formatBody: function(rows, columns) {
return null == columns && (columns = inferColumns(rows)), preformatBody(rows, columns).join("\n");
},
formatRows: function(rows) {
return rows.map(formatRow).join("\n");
},
formatRow: formatRow,
formatValue: formatValue
};
}
var csv = dsvFormat(","), csvParse = csv.parse, csvParseRows = csv.parseRows, csvFormat = csv.format, csvFormatBody = csv.formatBody, csvFormatRows = csv.formatRows, csvFormatRow = csv.formatRow, csvFormatValue = csv.formatValue, tsv = dsvFormat("\t"), tsvParse = tsv.parse, tsvParseRows = tsv.parseRows, tsvFormat = tsv.format, tsvFormatBody = tsv.formatBody, tsvFormatRows = tsv.formatRows, tsvFormatRow = tsv.formatRow, tsvFormatValue = tsv.formatValue;
// https://github.com/d3/d3-dsv/issues/45
const fixtz = new Date("2019-01-01T00:00").getHours() || new Date("2019-07-01T00:00").getHours();
function responseBlob(response) {
if (!response.ok) throw Error(response.status + " " + response.statusText);
return response.blob();
}
function responseArrayBuffer(response) {
if (!response.ok) throw Error(response.status + " " + response.statusText);
return response.arrayBuffer();
}
function responseText(response) {
if (!response.ok) throw Error(response.status + " " + response.statusText);
return response.text();
}
function text(input, init) {
return fetch(input, init).then(responseText);
}
function dsvParse(parse) {
return function(input, init, row) {
return 2 == arguments.length && "function" == typeof init && (row = init, init = void 0), text(input, init).then(function(response) {
return parse(response, row);
});
};
}
var csv$1 = dsvParse(csvParse), tsv$1 = dsvParse(tsvParse);
function responseJson(response) {
if (!response.ok) throw Error(response.status + " " + response.statusText);
if (204 !== response.status && 205 !== response.status) return response.json();
}
function parser(type) {
return (input, init)=>text(input, init).then((text)=>(new DOMParser).parseFromString(text, type));
}
var xml = parser("application/xml"), html = parser("text/html"), svg = parser("image/svg+xml");
function add(tree, x, y, d) {
if (isNaN(x) || isNaN(y)) return tree; // ignore invalid points
var parent, xm, ym, xp, yp, right, bottom, i, j, node = tree._root, leaf = {
data: d
}, x0 = tree._x0, y0 = tree._y0, x1 = tree._x1, y1 = tree._y1;
// If the tree is empty, initialize the root as a leaf.
if (!node) return tree._root = leaf, tree;
// Find the existing leaf for the new point, or add it.
for(; node.length;)if ((right = x >= (xm = (x0 + x1) / 2)) ? x0 = xm : x1 = xm, (bottom = y >= (ym = (y0 + y1) / 2)) ? y0 = ym : y1 = ym, parent = node, !(node = node[i = bottom << 1 | right])) return parent[i] = leaf, tree;
if (// Is the new point is exactly coincident with the existing point?
xp = +tree._x.call(null, node.data), yp = +tree._y.call(null, node.data), x === xp && y === yp) return leaf.next = node, parent ? parent[i] = leaf : tree._root = leaf, tree;
// Otherwise, split the leaf node until the old and new point are separated.
do parent = parent ? parent[i] = [
,
,
,
,
] : tree._root = [
,
,
,
,
], (right = x >= (xm = (x0 + x1) / 2)) ? x0 = xm : x1 = xm, (bottom = y >= (ym = (y0 + y1) / 2)) ? y0 = ym : y1 = ym;
while ((i = bottom << 1 | right) == (j = (yp >= ym) << 1 | xp >= xm))
return parent[j] = node, parent[i] = leaf, tree;
}
function Quad(node, x0, y0, x1, y1) {
this.node = node, this.x0 = x0, this.y0 = y0, this.x1 = x1, this.y1 = y1;
}
function defaultX$1(d) {
return d[0];
}
function defaultY$1(d) {
return d[1];
}
function quadtree(nodes, x, y) {
var tree = new Quadtree(null == x ? defaultX$1 : x, null == y ? defaultY$1 : y, NaN, NaN, NaN, NaN);
return null == nodes ? tree : tree.addAll(nodes);
}
function Quadtree(x, y, x0, y0, x1, y1) {
this._x = x, this._y = y, this._x0 = x0, this._y0 = y0, this._x1 = x1, this._y1 = y1, this._root = void 0;
}
function leaf_copy(leaf) {
for(var copy = {
data: leaf.data
}, next = copy; leaf = leaf.next;)next = next.next = {
data: leaf.data
};
return copy;
}
var treeProto = quadtree.prototype = Quadtree.prototype;
function constant$7(x) {
return function() {
return x;
};
}
function jiggle(random) {
return (random() - 0.5) * 1e-6;
}
function x(d) {
return d.x + d.vx;
}
function y(d) {
return d.y + d.vy;
}
function index$1(d) {
return d.index;
}
function find$1(nodeById, nodeId) {
var node = nodeById.get(nodeId);
if (!node) throw Error("node not found: " + nodeId);
return node;
}
function x$1(d) {
return d.x;
}
function y$1(d) {
return d.y;
}
treeProto.copy = function() {
var nodes, child, copy = new Quadtree(this._x, this._y, this._x0, this._y0, this._x1, this._y1), node = this._root;
if (!node) return copy;
if (!node.length) return copy._root = leaf_copy(node), copy;
for(nodes = [
{
source: node,
target: copy._root = [
,
,
,
,
]
}
]; node = nodes.pop();)for(var i = 0; i < 4; ++i)(child = node.source[i]) && (child.length ? nodes.push({
source: child,
target: node.target[i] = [
,
,
,
,
]
}) : node.target[i] = leaf_copy(child));
return copy;
}, treeProto.add = function(d) {
const x = +this._x.call(null, d), y = +this._y.call(null, d);
return add(this.cover(x, y), x, y, d);
}, treeProto.addAll = function(data) {
var d, i, x, y, n = data.length, xz = Array(n), yz = Array(n), x0 = 1 / 0, y0 = 1 / 0, x1 = -1 / 0, y1 = -1 / 0;
// Compute the points and their extent.
for(i = 0; i < n; ++i)!(isNaN(x = +this._x.call(null, d = data[i])) || isNaN(y = +this._y.call(null, d))) && (xz[i] = x, yz[i] = y, x < x0 && (x0 = x), x > x1 && (x1 = x), y < y0 && (y0 = y), y > y1 && (y1 = y));
// If there were no (valid) points, abort.
if (x0 > x1 || y0 > y1) return this;
// Add the new points.
for(// Expand the tree to cover the new points.
this.cover(x0, y0).cover(x1, y1), i = 0; i < n; ++i)add(this, xz[i], yz[i], data[i]);
return this;
}, treeProto.cover = function(x, y) {
if (isNaN(x *= 1) || isNaN(y *= 1)) return this; // ignore invalid points
var x0 = this._x0, y0 = this._y0, x1 = this._x1, y1 = this._y1;
// If the quadtree has no extent, initialize them.
// Integer extent are necessary so that if we later double the extent,
// the existing quadrant boundaries don’t change due to floating point error!
if (isNaN(x0)) x1 = (x0 = Math.floor(x)) + 1, y1 = (y0 = Math.floor(y)) + 1;
else {
for(var parent, i, z = x1 - x0 || 1, node = this._root; x0 > x || x >= x1 || y0 > y || y >= y1;)switch(i = (y < y0) << 1 | x < x0, (parent = [
,
,
,
,
])[i] = node, node = parent, z *= 2, i){
case 0:
x1 = x0 + z, y1 = y0 + z;
break;
case 1:
x0 = x1 - z, y1 = y0 + z;
break;
case 2:
x1 = x0 + z, y0 = y1 - z;
break;
case 3:
x0 = x1 - z, y0 = y1 - z;
}
this._root && this._root.length && (this._root = node);
}
return this._x0 = x0, this._y0 = y0, this._x1 = x1, this._y1 = y1, this;
}, treeProto.data = function() {
var data = [];
return this.visit(function(node) {
if (!node.length) do data.push(node.data);
while (node = node.next)
}), data;
}, treeProto.extent = function(_) {
return arguments.length ? this.cover(+_[0][0], +_[0][1]).cover(+_[1][0], +_[1][1]) : isNaN(this._x0) ? void 0 : [
[
this._x0,
this._y0
],
[
this._x1,
this._y1
]
];
}, treeProto.find = function(x, y, radius) {
var data, x1, y1, x2, y2, q, i, x0 = this._x0, y0 = this._y0, x3 = this._x1, y3 = this._y1, quads = [], node = this._root;
for(node && quads.push(new Quad(node, x0, y0, x3, y3)), null == radius ? radius = 1 / 0 : (x0 = x - radius, y0 = y - radius, x3 = x + radius, y3 = y + radius, radius *= radius); q = quads.pop();)// Stop searching if this quadrant can’t contain a closer node.
if ((node = q.node) && !((x1 = q.x0) > x3) && !((y1 = q.y0) > y3) && !((x2 = q.x1) < x0) && !((y2 = q.y1) < y0)) {
// Bisect the current quadrant.
if (node.length) {
var xm = (x1 + x2) / 2, ym = (y1 + y2) / 2;
quads.push(new Quad(node[3], xm, ym, x2, y2), new Quad(node[2], x1, ym, xm, y2), new Quad(node[1], xm, y1, x2, ym), new Quad(node[0], x1, y1, xm, ym)), (i = (y >= ym) << 1 | x >= xm) && (q = quads[quads.length - 1], quads[quads.length - 1] = quads[quads.length - 1 - i], quads[quads.length - 1 - i] = q);
} else {
var dx = x - +this._x.call(null, node.data), dy = y - +this._y.call(null, node.data), d2 = dx * dx + dy * dy;
if (d2 < radius) {
var d = Math.sqrt(radius = d2);
x0 = x - d, y0 = y - d, x3 = x + d, y3 = y + d, data = node.data;
}
}
}
return data;
}, treeProto.remove = function(d) {
if (isNaN(x = +this._x.call(null, d)) || isNaN(y = +this._y.call(null, d))) return this; // ignore invalid points
var parent, retainer, previous, next, x, y, xm, ym, right, bottom, i, j, node = this._root, x0 = this._x0, y0 = this._y0, x1 = this._x1, y1 = this._y1;
// If the tree is empty, initialize the root as a leaf.
if (!node) return this;
// Find the leaf node for the point.
// While descending, also retain the deepest parent with a non-removed sibling.
if (node.length) for(;;){
if ((right = x >= (xm = (x0 + x1) / 2)) ? x0 = xm : x1 = xm, (bottom = y >= (ym = (y0 + y1) / 2)) ? y0 = ym : y1 = ym, parent = node, !(node = node[i = bottom << 1 | right])) return this;
if (!node.length) break;
(parent[i + 1 & 3] || parent[i + 2 & 3] || parent[i + 3 & 3]) && (retainer = parent, j = i);
}
// Find the point to remove.
for(; node.data !== d;)if (previous = node, !(node = node.next)) return this;
return ((next = node.next) && delete node.next, previous) ? next ? previous.next = next : delete previous.next : parent ? (// Remove this leaf.
next ? parent[i] = next : delete parent[i], (node = parent[0] || parent[1] || parent[2] || parent[3]) && node === (parent[3] || parent[2] || parent[1] || parent[0]) && !node.length && (retainer ? retainer[j] = node : this._root = node)) : this._root = next, this;
}, treeProto.removeAll = function(data) {
for(var i = 0, n = data.length; i < n; ++i)this.remove(data[i]);
return this;
}, treeProto.root = function() {
return this._root;
}, treeProto.size = function() {
var size = 0;
return this.visit(function(node) {
if (!node.length) do ++size;
while (node = node.next)
}), size;
}, treeProto.visit = function(callback) {
var q, child, x0, y0, x1, y1, quads = [], node = this._root;
for(node && quads.push(new Quad(node, this._x0, this._y0, this._x1, this._y1)); q = quads.pop();)if (!callback(node = q.node, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1) && node.length) {
var xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
(child = node[3]) && quads.push(new Quad(child, xm, ym, x1, y1)), (child = node[2]) && quads.push(new Quad(child, x0, ym, xm, y1)), (child = node[1]) && quads.push(new Quad(child, xm, y0, x1, ym)), (child = node[0]) && quads.push(new Quad(child, x0, y0, xm, ym));
}
return this;
}, treeProto.visitAfter = function(callback) {
var q, quads = [], next = [];
for(this._root && quads.push(new Quad(this._root, this._x0, this._y0, this._x1, this._y1)); q = quads.pop();){
var node = q.node;
if (node.length) {
var child, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1, xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;
(child = node[0]) && quads.push(new Quad(child, x0, y0, xm, ym)), (child = node[1]) && quads.push(new Quad(child, xm, y0, x1, ym)), (child = node[2]) && quads.push(new Quad(child, x0, ym, xm, y1)), (child = node[3]) && quads.push(new Quad(child, xm, ym, x1, y1));
}
next.push(q);
}
for(; q = next.pop();)callback(q.node, q.x0, q.y0, q.x1, q.y1);
return this;
}, treeProto.x = function(_) {
return arguments.length ? (this._x = _, this) : this._x;
}, treeProto.y = function(_) {
return arguments.length ? (this._y = _, this) : this._y;
};
var initialAngle = Math.PI * (3 - Math.sqrt(5));
// Computes the decimal coefficient and exponent of the specified number x with
// significant digits p, where x is positive and p is in [1, 21] or undefined.
// For example, formatDecimalParts(1.23) returns ["123", 0].
function formatDecimalParts(x, p) {
if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e")) < 0) return null; // NaN, ±Infinity
var i, coefficient = x.slice(0, i);
// The string returned by toExponential either has the form \d\.\d+e[-+]\d+
// (e.g., 1.2e+3) or the form \de[-+]\d+ (e.g., 1e+3).
return [
coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,
+x.slice(i + 1)
];
}
function exponent$1(x) {
return (x = formatDecimalParts(Math.abs(x))) ? x[1] : NaN;
}
// [[fill]align][sign][symbol][0][width][,][.precision][~][type]
var re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;
function formatSpecifier(specifier) {
var match;
if (!(match = re.exec(specifier))) throw Error("invalid format: " + specifier);
return new FormatSpecifier({
fill: match[1],
align: match[2],
sign: match[3],
symbol: match[4],
zero: match[5],
width: match[6],
comma: match[7],
precision: match[8] && match[8].slice(1),
trim: match[9],
type: match[10]
});
}
function FormatSpecifier(specifier) {
this.fill = void 0 === specifier.fill ? " " : specifier.fill + "", this.align = void 0 === specifier.align ? ">" : specifier.align + "", this.sign = void 0 === specifier.sign ? "-" : specifier.sign + "", this.symbol = void 0 === specifier.symbol ? "" : specifier.symbol + "", this.zero = !!specifier.zero, this.width = void 0 === specifier.width ? void 0 : +specifier.width, this.comma = !!specifier.comma, this.precision = void 0 === specifier.precision ? void 0 : +specifier.precision, this.trim = !!specifier.trim, this.type = void 0 === specifier.type ? "" : specifier.type + "";
}
function formatRounded(x, p) {
var d = formatDecimalParts(x, p);
if (!d) return x + "";
var coefficient = d[0], exponent = d[1];
return exponent < 0 ? "0." + Array(-exponent).join("0") + coefficient : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1) : coefficient + Array(exponent - coefficient.length + 2).join("0");
}
formatSpecifier.prototype = FormatSpecifier.prototype, FormatSpecifier.prototype.toString = function() {
return this.fill + this.align + this.sign + this.symbol + (this.zero ? "0" : "") + (void 0 === this.width ? "" : Math.max(1, 0 | this.width)) + (this.comma ? "," : "") + (void 0 === this.precision ? "" : "." + Math.max(0, 0 | this.precision)) + (this.trim ? "~" : "") + this.type;
};
var formatTypes = {
"%": (x, p)=>(100 * x).toFixed(p),
b: (x)=>Math.round(x).toString(2),
c: (x)=>x + "",
d: function(x) {
return Math.abs(x = Math.round(x)) >= 1e21 ? x.toLocaleString("en").replace(/,/g, "") : x.toString(10);
},
e: (x, p)=>x.toExponential(p),
f: (x, p)=>x.toFixed(p),
g: (x, p)=>x.toPrecision(p),
o: (x)=>Math.round(x).toString(8),
p: (x, p)=>formatRounded(100 * x, p),
r: formatRounded,
s: function(x, p) {
var d = formatDecimalParts(x, p);
if (!d) return x + "";
var coefficient = d[0], exponent = d[1], i = exponent - (prefixExponent = 3 * Math.max(-8, Math.min(8, Math.floor(exponent / 3)))) + 1, n = coefficient.length;
return i === n ? coefficient : i > n ? coefficient + Array(i - n + 1).join("0") : i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i) : "0." + Array(1 - i).join("0") + formatDecimalParts(x, Math.max(0, p + i - 1))[0]; // less than 1y!
},
X: (x)=>Math.round(x).toString(16).toUpperCase(),
x: (x)=>Math.round(x).toString(16)
};
function identity$3(x) {
return x;
}
var map$1 = Array.prototype.map, prefixes = [
"y",
"z",
"a",
"f",
"p",
"n",
"\xB5",
"m",
"",
"k",
"M",
"G",
"T",
"P",
"E",
"Z",
"Y"
];
function formatLocale(locale) {
var grouping, thousands, numerals, group = void 0 === locale.grouping || void 0 === locale.thousands ? identity$3 : (grouping = map$1.call(locale.grouping, Number), thousands = locale.thousands + "", function(value, width) {
for(var i = value.length, t = [], j = 0, g = grouping[0], length = 0; i > 0 && g > 0 && (length + g + 1 > width && (g = Math.max(1, width - length)), t.push(value.substring(i -= g, i + g)), !((length += g + 1) > width));)g = grouping[j = (j + 1) % grouping.length];
return t.reverse().join(thousands);
}), currencyPrefix = void 0 === locale.currency ? "" : locale.currency[0] + "", currencySuffix = void 0 === locale.currency ? "" : locale.currency[1] + "", decimal = void 0 === locale.decimal ? "." : locale.decimal + "", numerals1 = void 0 === locale.numerals ? identity$3 : (numerals = map$1.call(locale.numerals, String), function(value) {
return value.replace(/[0-9]/g, function(i) {
return numerals[+i];
});
}), percent = void 0 === locale.percent ? "%" : locale.percent + "", minus = void 0 === locale.minus ? "\u2212" : locale.minus + "", nan = void 0 === locale.nan ? "NaN" : locale.nan + "";
function newFormat(specifier) {
var fill = (specifier = formatSpecifier(specifier)).fill, align = specifier.align, sign = specifier.sign, symbol = specifier.symbol, zero = specifier.zero, width = specifier.width, comma = specifier.comma, precision = specifier.precision, trim = specifier.trim, type = specifier.type;
"n" === type ? (comma = !0, type = "g") : formatTypes[type] || (void 0 === precision && (precision = 12), trim = !0, type = "g"), (zero || "0" === fill && "=" === align) && (zero = !0, fill = "0", align = "=");
// Compute the prefix and suffix.
// For SI-prefix, the suffix is lazily computed.
var prefix = "$" === symbol ? currencyPrefix : "#" === symbol && /[boxX]/.test(type) ? "0" + type.toLowerCase() : "", suffix = "$" === symbol ? currencySuffix : /[%p]/.test(type) ? percent : "", formatType = formatTypes[type], maybeSuffix = /[defgprs%]/.test(type);
function format(value) {
var i, n, c, valuePrefix = prefix, valueSuffix = suffix;
if ("c" === type) valueSuffix = formatType(value) + valueSuffix, value = "";
else {
// Determine the sign. -0 is not less than 0, but 1 / -0 is!
var valueNegative = (value *= 1) < 0 || 1 / value < 0;
// Break the formatted value into the integer “value” part that can be
// grouped, and fractional or exponential “suffix” part that is not.
if (// Perform the initial formatting.
value = isNaN(value) ? nan : formatType(Math.abs(value), precision), trim && (value = // Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k.
function(s) {
out: for(var i1, n = s.length, i = 1, i0 = -1; i < n; ++i)switch(s[i]){
case ".":
i0 = i1 = i;
break;
case "0":
0 === i0 && (i0 = i), i1 = i;
break;
default:
if (!+s[i]) break out;
i0 > 0 && (i0 = 0);
}
return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;
}(value)), valueNegative && 0 == +value && "+" !== sign && (valueNegative = !1), // Compute the prefix and suffix.
valuePrefix = (valueNegative ? "(" === sign ? sign : minus : "-" === sign || "(" === sign ? "" : sign) + valuePrefix, valueSuffix = ("s" === type ? prefixes[8 + prefixExponent / 3] : "") + valueSuffix + (valueNegative && "(" === sign ? ")" : ""), maybeSuffix) {
for(i = -1, n = value.length; ++i < n;)if (48 > (c = value.charCodeAt(i)) || c > 57) {
valueSuffix = (46 === c ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix, value = value.slice(0, i);
break;
}
}
}
comma && !zero && (value = group(value, 1 / 0));
// Compute the padding.
var length = valuePrefix.length + value.length + valueSuffix.length, padding = length < width ? Array(width - length + 1).join(fill) : "";
// Reconstruct the final output based on the desired alignment.
switch(comma && zero && (value = group(padding + value, padding.length ? width - valueSuffix.length : 1 / 0), padding = ""), align){
case "<":
value = valuePrefix + value + valueSuffix + padding;
break;
case "=":
value = valuePrefix + padding + value + valueSuffix;
break;
case "^":
value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length);
break;
default:
value = padding + valuePrefix + value + valueSuffix;
}
return numerals1(value);
}
return(// Set the default precision if not specified,
// or clamp the specified precision to the supported range.
// For significant precision, it must be in [1, 21].
// For fixed precision, it must be in [0, 20].
precision = void 0 === precision ? 6 : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision)) : Math.max(0, Math.min(20, precision)), format.toString = function() {
return specifier + "";
}, format);
}
return {
format: newFormat,
formatPrefix: function(specifier, value) {
var f = newFormat(((specifier = formatSpecifier(specifier)).type = "f", specifier)), e = 3 * Math.max(-8, Math.min(8, Math.floor(exponent$1(value) / 3))), k = Math.pow(10, -e), prefix = prefixes[8 + e / 3];
return function(value) {
return f(k * value) + prefix;
};
}
};
}
function defaultLocale(definition) {
return exports1.format = (locale = formatLocale(definition)).format, exports1.formatPrefix = locale.formatPrefix, locale;
}
function precisionFixed(step) {
return Math.max(0, -exponent$1(Math.abs(step)));
}
function precisionPrefix(step, value) {
return Math.max(0, 3 * Math.max(-8, Math.min(8, Math.floor(exponent$1(value) / 3))) - exponent$1(Math.abs(step)));
}
function precisionRound(step, max) {
return Math.max(0, exponent$1(max = Math.abs(max) - (step = Math.abs(step))) - exponent$1(step)) + 1;
}
defaultLocale({
thousands: ",",
grouping: [
3
],
currency: [
"$",
""
]
});
var pi$3 = Math.PI, halfPi$2 = pi$3 / 2, quarterPi = pi$3 / 4, tau$4 = 2 * pi$3, degrees$2 = 180 / pi$3, radians$1 = pi$3 / 180, abs$2 = Math.abs, atan = Math.atan, atan2 = Math.atan2, cos$1 = Math.cos, ceil = Math.ceil, exp = Math.exp, hypot = Math.hypot, log = Math.log, pow$1 = Math.pow, sin$1 = Math.sin, sign = Math.sign || function(x) {
return x > 0 ? 1 : x < 0 ? -1 : 0;
}, sqrt = Math.sqrt, tan = Math.tan;
function acos(x) {
return x > 1 ? 0 : x < -1 ? pi$3 : Math.acos(x);
}
function asin(x) {
return x > 1 ? halfPi$2 : x < -1 ? -halfPi$2 : Math.asin(x);
}
function noop$2() {}
function streamGeometry(geometry, stream) {
geometry && streamGeometryType.hasOwnProperty(geometry.type) && streamGeometryType[geometry.type](geometry, stream);
}
var streamObjectType = {
Feature: function(object, stream) {
streamGeometry(object.geometry, stream);
},
FeatureCollection: function(object, stream) {
for(var features = object.features, i = -1, n = features.length; ++i < n;)streamGeometry(features[i].geometry, stream);
}
}, streamGeometryType = {
Sphere: function(object, stream) {
stream.sphere();
},
Point: function(object, stream) {
object = object.coordinates, stream.point(object[0], object[1], object[2]);
},
MultiPoint: function(object, stream) {
for(var coordinates = object.coordinates, i = -1, n = coordinates.length; ++i < n;)object = coordinates[i], stream.point(object[0], object[1], object[2]);
},
LineString: function(object, stream) {
streamLine(object.coordinates, stream, 0);
},
MultiLineString: function(object, stream) {
for(var coordinates = object.coordinates, i = -1, n = coordinates.length; ++i < n;)streamLine(coordinates[i], stream, 0);
},
Polygon: function(object, stream) {
streamPolygon(object.coordinates, stream);
},
MultiPolygon: function(object, stream) {
for(var coordinates = object.coordinates, i = -1, n = coordinates.length; ++i < n;)streamPolygon(coordinates[i], stream);
},
GeometryCollection: function(object, stream) {
for(var geometries = object.geometries, i = -1, n = geometries.length; ++i < n;)streamGeometry(geometries[i], stream);
}
};
function streamLine(coordinates, stream, closed) {
var coordinate, i = -1, n = coordinates.length - closed;
for(stream.lineStart(); ++i < n;)coordinate = coordinates[i], stream.point(coordinate[0], coordinate[1], coordinate[2]);
stream.lineEnd();
}
function streamPolygon(coordinates, stream) {
var i = -1, n = coordinates.length;
for(stream.polygonStart(); ++i < n;)streamLine(coordinates[i], stream, 1);
stream.polygonEnd();
}
function geoStream(object, stream) {
object && streamObjectType.hasOwnProperty(object.type) ? streamObjectType[object.type](object, stream) : streamGeometry(object, stream);
}
var prefixExponent, locale, lambda00, phi00, lambda0, cosPhi0, sinPhi0, areaRingSum = new Adder(), areaSum = new Adder(), areaStream = {
point: noop$2,
lineStart: noop$2,
lineEnd: noop$2,
polygonStart: function() {
areaRingSum = new Adder(), areaStream.lineStart = areaRingStart, areaStream.lineEnd = areaRingEnd;
},
polygonEnd: function() {
var areaRing = +areaRingSum;
areaSum.add(areaRing < 0 ? tau$4 + areaRing : areaRing), this.lineStart = this.lineEnd = this.point = noop$2;
},
sphere: function() {
areaSum.add(tau$4);
}
};
function areaRingStart() {
areaStream.point = areaPointFirst;
}
function areaRingEnd() {
areaPoint(lambda00, phi00);
}
function areaPointFirst(lambda, phi) {
areaStream.point = areaPoint, lambda00 = lambda, phi00 = phi, lambda *= radians$1, phi *= radians$1, lambda0 = lambda, cosPhi0 = cos$1(phi = phi / 2 + quarterPi), sinPhi0 = sin$1(phi);
}
function areaPoint(lambda, phi) {
lambda *= radians$1, phi *= radians$1;
// Spherical excess E for a spherical triangle with vertices: south pole,
// previous point, current point. Uses a formula derived from Cagnoli’s
// theorem. See Todhunter, Spherical Trig. (1871), Sec. 103, Eq. (2).
var dLambda = lambda - lambda0, sdLambda = dLambda >= 0 ? 1 : -1, adLambda = sdLambda * dLambda, cosPhi = cos$1(phi = phi / 2 + quarterPi), sinPhi = sin$1(phi), k = sinPhi0 * sinPhi, u = cosPhi0 * cosPhi + k * cos$1(adLambda), v = k * sdLambda * sin$1(adLambda);
areaRingSum.add(atan2(v, u)), // Advance the previous points.
lambda0 = lambda, cosPhi0 = cosPhi, sinPhi0 = sinPhi;
}
function spherical(cartesian) {
return [
atan2(cartesian[1], cartesian[0]),
asin(cartesian[2])
];
}
function cartesian(spherical) {
var lambda = spherical[0], phi = spherical[1], cosPhi = cos$1(phi);
return [
cosPhi * cos$1(lambda),
cosPhi * sin$1(lambda),
sin$1(phi)
];
}
function cartesianDot(a, b) {
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
}
function cartesianCross(a, b) {
return [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0]
];
}
// TODO return a
function cartesianAddInPlace(a, b) {
a[0] += b[0], a[1] += b[1], a[2] += b[2];
}
function cartesianScale(vector, k) {
return [
vector[0] * k,
vector[1] * k,
vector[2] * k
];
}
// TODO return d
function cartesianNormalizeInPlace(d) {
var l = sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
d[0] /= l, d[1] /= l, d[2] /= l;
}
var boundsStream = {
point: boundsPoint,
lineStart: boundsLineStart,
lineEnd: boundsLineEnd,
polygonStart: function() {
boundsStream.point = boundsRingPoint, boundsStream.lineStart = boundsRingStart, boundsStream.lineEnd = boundsRingEnd, deltaSum = new Adder(), areaStream.polygonStart();
},
polygonEnd: function() {
areaStream.polygonEnd(), boundsStream.point = boundsPoint, boundsStream.lineStart = boundsLineStart, boundsStream.lineEnd = boundsLineEnd, areaRingSum < 0 ? (lambda0$1 = -(lambda1 = 180), phi0 = -(phi1 = 90)) : deltaSum > 1e-6 ? phi1 = 90 : deltaSum < -0.000001 && (phi0 = -90), range$1[0] = lambda0$1, range$1[1] = lambda1;
},
sphere: function() {
lambda0$1 = -(lambda1 = 180), phi0 = -(phi1 = 90);
}
};
function boundsPoint(lambda, phi) {
ranges.push(range$1 = [
lambda0$1 = lambda,
lambda1 = lambda
]), phi < phi0 && (phi0 = phi), phi > phi1 && (phi1 = phi);
}
function linePoint(lambda, phi) {
var p = cartesian([
lambda * radians$1,
phi * radians$1
]);
if (p0) {
var normal = cartesianCross(p0, p), inflection = cartesianCross([
normal[1],
-normal[0],
0
], normal);
cartesianNormalizeInPlace(inflection), inflection = spherical(inflection);
var phii, delta = lambda - lambda2, sign = delta > 0 ? 1 : -1, lambdai = inflection[0] * degrees$2 * sign, antimeridian = abs$2(delta) > 180;
antimeridian ^ (sign * lambda2 < lambdai && lambdai < sign * lambda) ? (phii = inflection[1] * degrees$2) > phi1 && (phi1 = phii) : antimeridian ^ (sign * lambda2 < (lambdai = (lambdai + 360) % 360 - 180) && lambdai < sign * lambda) ? (phii = -inflection[1] * degrees$2) < phi0 && (phi0 = phii) : (phi < phi0 && (phi0 = phi), phi > phi1 && (phi1 = phi)), antimeridian ? lambda < lambda2 ? angle(lambda0$1, lambda) > angle(lambda0$1, lambda1) && (lambda1 = lambda) : angle(lambda, lambda1) > angle(lambda0$1, lambda1) && (lambda0$1 = lambda) : lambda1 >= lambda0$1 ? (lambda < lambda0$1 && (lambda0$1 = lambda), lambda > lambda1 && (lambda1 = lambda)) : lambda > lambda2 ? angle(lambda0$1, lambda) > angle(lambda0$1, lambda1) && (lambda1 = lambda) : angle(lambda, lambda1) > angle(lambda0$1, lambda1) && (lambda0$1 = lambda);
} else ranges.push(range$1 = [
lambda0$1 = lambda,
lambda1 = lambda
]);
phi < phi0 && (phi0 = phi), phi > phi1 && (phi1 = phi), p0 = p, lambda2 = lambda;
}
function boundsLineStart() {
boundsStream.point = linePoint;
}
function boundsLineEnd() {
range$1[0] = lambda0$1, range$1[1] = lambda1, boundsStream.point = boundsPoint, p0 = null;
}
function boundsRingPoint(lambda, phi) {
if (p0) {
var delta = lambda - lambda2;
deltaSum.add(abs$2(delta) > 180 ? delta + (delta > 0 ? 360 : -360) : delta);
} else lambda00$1 = lambda, phi00$1 = phi;
areaStream.point(lambda, phi), linePoint(lambda, phi);
}
function boundsRingStart() {
areaStream.lineStart();
}
function boundsRingEnd() {
boundsRingPoint(lambda00$1, phi00$1), areaStream.lineEnd(), abs$2(deltaSum) > 1e-6 && (lambda0$1 = -(lambda1 = 180)), range$1[0] = lambda0$1, range$1[1] = lambda1, p0 = null;
}
// Finds the left-right distance between two longitudes.
// This is almost the same as (lambda1 - lambda0 + 360°) % 360°, except that we want
// the distance between ±180° to be 360°.
function angle(lambda0, lambda1) {
return (lambda1 -= lambda0) < 0 ? lambda1 + 360 : lambda1;
}
function rangeCompare(a, b) {
return a[0] - b[0];
}
function rangeContains(range, x) {
return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x;
}
var centroidStream = {
sphere: noop$2,
point: centroidPoint,
lineStart: centroidLineStart,
lineEnd: centroidLineEnd,
polygonStart: function() {
centroidStream.lineStart = centroidRingStart, centroidStream.lineEnd = centroidRingEnd;
},
polygonEnd: function() {
centroidStream.lineStart = centroidLineStart, centroidStream.lineEnd = centroidLineEnd;
}
};
// Arithmetic mean of Cartesian vectors.
function centroidPoint(lambda, phi) {
lambda *= radians$1;
var cosPhi = cos$1(phi *= radians$1);
centroidPointCartesian(cosPhi * cos$1(lambda), cosPhi * sin$1(lambda), sin$1(phi));
}
function centroidPointCartesian(x, y, z) {
++W0, X0 += (x - X0) / W0, Y0 += (y - Y0) / W0, Z0 += (z - Z0) / W0;
}
function centroidLineStart() {
centroidStream.point = centroidLinePointFirst;
}
function centroidLinePointFirst(lambda, phi) {
lambda *= radians$1;
var cosPhi = cos$1(phi *= radians$1);
x0 = cosPhi * cos$1(lambda), y0 = cosPhi * sin$1(lambda), z0 = sin$1(phi), centroidStream.point = centroidLinePoint, centroidPointCartesian(x0, y0, z0);
}
function centroidLinePoint(lambda, phi) {
lambda *= radians$1;
var cosPhi = cos$1(phi *= radians$1), x = cosPhi * cos$1(lambda), y = cosPhi * sin$1(lambda), z = sin$1(phi), w = atan2(sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z);
W1 += w, X1 += w * (x0 + (x0 = x)), Y1 += w * (y0 + (y0 = y)), Z1 += w * (z0 + (z0 = z)), centroidPointCartesian(x0, y0, z0);
}
function centroidLineEnd() {
centroidStream.point = centroidPoint;
}
// See J. E. Brock, The Inertia Tensor for a Spherical Triangle,
// J. Applied Mechanics 42, 239 (1975).
function centroidRingStart() {
centroidStream.point = centroidRingPointFirst;
}
function centroidRingEnd() {
centroidRingPoint(lambda00$2, phi00$2), centroidStream.point = centroidPoint;
}
function centroidRingPointFirst(lambda, phi) {
lambda00$2 = lambda, phi00$2 = phi, lambda *= radians$1, phi *= radians$1, centroidStream.point = centroidRingPoint;
var cosPhi = cos$1(phi);
x0 = cosPhi * cos$1(lambda), y0 = cosPhi * sin$1(lambda), z0 = sin$1(phi), centroidPointCartesian(x0, y0, z0);
}
function centroidRingPoint(lambda, phi) {
lambda *= radians$1;
var cosPhi = cos$1(phi *= radians$1), x = cosPhi * cos$1(lambda), y = cosPhi * sin$1(lambda), z = sin$1(phi), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = hypot(cx, cy, cz), w = asin(m), v = m && -w / m; // area weight multiplier
X2.add(v * cx), Y2.add(v * cy), Z2.add(v * cz), W1 += w, X1 += w * (x0 + (x0 = x)), Y1 += w * (y0 + (y0 = y)), Z1 += w * (z0 + (z0 = z)), centroidPointCartesian(x0, y0, z0);
}
function constant$8(x) {
return function() {
return x;
};
}
function compose(a, b) {
function compose(x, y) {
return b((x = a(x, y))[0], x[1]);
}
return a.invert && b.invert && (compose.invert = function(x, y) {
return (x = b.invert(x, y)) && a.invert(x[0], x[1]);
}), compose;
}
function rotationIdentity(lambda, phi) {
return [
abs$2(lambda) > pi$3 ? lambda + Math.round(-lambda / tau$4) * tau$4 : lambda,
phi
];
}
function rotateRadians(deltaLambda, deltaPhi, deltaGamma) {
return (deltaLambda %= tau$4) ? deltaPhi || deltaGamma ? compose(rotationLambda(deltaLambda), rotationPhiGamma(deltaPhi, deltaGamma)) : rotationLambda(deltaLambda) : deltaPhi || deltaGamma ? rotationPhiGamma(deltaPhi, deltaGamma) : rotationIdentity;
}
function forwardRotationLambda(deltaLambda) {
return function(lambda, phi) {
return [
(lambda += deltaLambda) > pi$3 ? lambda - tau$4 : lambda < -pi$3 ? lambda + tau$4 : lambda,
phi
];
};
}
function rotationLambda(deltaLambda) {
var rotation = forwardRotationLambda(deltaLambda);
return rotation.invert = forwardRotationLambda(-deltaLambda), rotation;
}
function rotationPhiGamma(deltaPhi, deltaGamma) {
var cosDeltaPhi = cos$1(deltaPhi), sinDeltaPhi = sin$1(deltaPhi), cosDeltaGamma = cos$1(deltaGamma), sinDeltaGamma = sin$1(deltaGamma);
function rotation(lambda, phi) {
var cosPhi = cos$1(phi), x = cos$1(lambda) * cosPhi, y = sin$1(lambda) * cosPhi, z = sin$1(phi), k = z * cosDeltaPhi + x * sinDeltaPhi;
return [
atan2(y * cosDeltaGamma - k * sinDeltaGamma, x * cosDeltaPhi - z * sinDeltaPhi),
asin(k * cosDeltaGamma + y * sinDeltaGamma)
];
}
return rotation.invert = function(lambda, phi) {
var cosPhi = cos$1(phi), x = cos$1(lambda) * cosPhi, y = sin$1(lambda) * cosPhi, z = sin$1(phi), k = z * cosDeltaGamma - y * sinDeltaGamma;
return [
atan2(y * cosDeltaGamma + z * sinDeltaGamma, x * cosDeltaPhi + k * sinDeltaPhi),
asin(k * cosDeltaPhi - x * sinDeltaPhi)
];
}, rotation;
}
function rotation(rotate) {
function forward(coordinates) {
return coordinates = rotate(coordinates[0] * radians$1, coordinates[1] * radians$1), coordinates[0] *= degrees$2, coordinates[1] *= degrees$2, coordinates;
}
return rotate = rotateRadians(rotate[0] * radians$1, rotate[1] * radians$1, rotate.length > 2 ? rotate[2] * radians$1 : 0), forward.invert = function(coordinates) {
return coordinates = rotate.invert(coordinates[0] * radians$1, coordinates[1] * radians$1), coordinates[0] *= degrees$2, coordinates[1] *= degrees$2, coordinates;
}, forward;
}
// Generates a circle centered at [0°, 0°], with a given radius and precision.
function circleStream(stream, radius, delta, direction, t0, t1) {
if (delta) {
var cosRadius = cos$1(radius), sinRadius = sin$1(radius), step = direction * delta;
null == t0 ? (t0 = radius + direction * tau$4, t1 = radius - step / 2) : (t0 = circleRadius(cosRadius, t0), t1 = circleRadius(cosRadius, t1), (direction > 0 ? t0 < t1 : t0 > t1) && (t0 += direction * tau$4));
for(var point, t = t0; direction > 0 ? t > t1 : t < t1; t -= step)point = spherical([
cosRadius,
-sinRadius * cos$1(t),
-sinRadius * sin$1(t)
]), stream.point(point[0], point[1]);
}
}
// Returns the signed angle of a cartesian point relative to [cosRadius, 0, 0].
function circleRadius(cosRadius, point) {
point = cartesian(point), point[0] -= cosRadius, cartesianNormalizeInPlace(point);
var radius = acos(-point[1]);
return ((0 > -point[2] ? -radius : radius) + tau$4 - 1e-6) % tau$4;
}
function clipBuffer() {
var line, lines = [];
return {
point: function(x, y, m) {
line.push([
x,
y,
m
]);
},
lineStart: function() {
lines.push(line = []);
},
lineEnd: noop$2,
rejoin: function() {
lines.length > 1 && lines.push(lines.pop().concat(lines.shift()));
},
result: function() {
var result = lines;
return lines = [], line = null, result;
}
};
}
function pointEqual(a, b) {
return 1e-6 > abs$2(a[0] - b[0]) && 1e-6 > abs$2(a[1] - b[1]);
}
function Intersection(point, points, other, entry) {
this.x = point, this.z = points, this.o = other, this.e = entry, this.v = !1, this.n = this.p = null;
}
// A generalized polygon clipping algorithm: given a polygon that has been cut
// into its visible line segments, and rejoins the segments by interpolating
// along the clip edge.
function clipRejoin(segments, compareIntersection, startInside, interpolate, stream) {
var i, n, subject = [], clip = [];
if (segments.forEach(function(segment) {
if (!((n = segment.length - 1) <= 0)) {
var n, x, p0 = segment[0], p1 = segment[n];
if (pointEqual(p0, p1)) {
if (!p0[2] && !p1[2]) {
for(stream.lineStart(), i = 0; i < n; ++i)stream.point((p0 = segment[i])[0], p0[1]);
stream.lineEnd();
return;
}
// handle degenerate cases by moving the point
p1[0] += 0.000002;
}
subject.push(x = new Intersection(p0, segment, null, !0)), clip.push(x.o = new Intersection(p0, null, x, !1)), subject.push(x = new Intersection(p1, segment, null, !1)), clip.push(x.o = new Intersection(p1, null, x, !0));
}
}), subject.length) {
for(clip.sort(compareIntersection), link$1(subject), link$1(clip), i = 0, n = clip.length; i < n; ++i)clip[i].e = startInside = !startInside;
for(var points, point, start = subject[0];;){
for(// Find first unvisited intersection.
var current = start, isSubject = !0; current.v;)if ((current = current.n) === start) return;
points = current.z, stream.lineStart();
do {
if (current.v = current.o.v = !0, current.e) {
if (isSubject) for(i = 0, n = points.length; i < n; ++i)stream.point((point = points[i])[0], point[1]);
else interpolate(current.x, current.n.x, 1, stream);
current = current.n;
} else {
if (isSubject) for(i = (points = current.p.z).length - 1; i >= 0; --i)stream.point((point = points[i])[0], point[1]);
else interpolate(current.x, current.p.x, -1, stream);
current = current.p;
}
points = (current = current.o).z, isSubject = !isSubject;
}while (!current.v)
stream.lineEnd();
}
}
}
function link$1(array) {
if (n = array.length) {
for(var n, b, i = 0, a = array[0]; ++i < n;)a.n = b = array[i], b.p = a, a = b;
a.n = b = array[0], b.p = a;
}
}
function longitude(point) {
return abs$2(point[0]) <= pi$3 ? point[0] : sign(point[0]) * ((abs$2(point[0]) + pi$3) % tau$4 - pi$3);
}
function polygonContains(polygon, point) {
var lambda = longitude(point), phi = point[1], sinPhi = sin$1(phi), normal = [
sin$1(lambda),
-cos$1(lambda),
0
], angle = 0, winding = 0, sum = new Adder();
1 === sinPhi ? phi = halfPi$2 + 1e-6 : -1 === sinPhi && (phi = -halfPi$2 - 1e-6);
for(var i = 0, n = polygon.length; i < n; ++i)if (m = (ring = polygon[i]).length) for(var ring, m, point0 = ring[m - 1], lambda0 = longitude(point0), phi0 = point0[1] / 2 + quarterPi, sinPhi0 = sin$1(phi0), cosPhi0 = cos$1(phi0), j = 0; j < m; ++j, lambda0 = lambda1, sinPhi0 = sinPhi1, cosPhi0 = cosPhi1, point0 = point1){
var point1 = ring[j], lambda1 = longitude(point1), phi1 = point1[1] / 2 + quarterPi, sinPhi1 = sin$1(phi1), cosPhi1 = cos$1(phi1), delta = lambda1 - lambda0, sign = delta >= 0 ? 1 : -1, absDelta = sign * delta, antimeridian = absDelta > pi$3, k = sinPhi0 * sinPhi1;
// Are the longitudes either side of the point’s meridian (lambda),
// and are the latitudes smaller than the parallel (phi)?
if (sum.add(atan2(k * sign * sin$1(absDelta), cosPhi0 * cosPhi1 + k * cos$1(absDelta))), angle += antimeridian ? delta + sign * tau$4 : delta, antimeridian ^ lambda0 >= lambda ^ lambda1 >= lambda) {
var arc = cartesianCross(cartesian(point0), cartesian(point1));
cartesianNormalizeInPlace(arc);
var intersection = cartesianCross(normal, arc);
cartesianNormalizeInPlace(intersection);
var phiArc = (antimeridian ^ delta >= 0 ? -1 : 1) * asin(intersection[2]);
(phi > phiArc || phi === phiArc && (arc[0] || arc[1])) && (winding += antimeridian ^ delta >= 0 ? 1 : -1);
}
}
// First, determine whether the South pole is inside or outside:
//
// It is inside if:
// * the polygon winds around it in a clockwise direction.
// * the polygon does not (cumulatively) wind around it, but has a negative
// (counter-clockwise) area.
//
// Second, count the (signed) number of times a segment crosses a lambda
// from the point to the South pole. If it is zero, then the point is the
// same side as the South pole.
return (angle < -0.000001 || angle < 1e-6 && sum < -0.000000000001) ^ 1 & winding;
}
function clip(pointVisible, clipLine, interpolate, start) {
return function(sink) {
var polygon, segments, ring, line = clipLine(sink), ringBuffer = clipBuffer(), ringSink = clipLine(ringBuffer), polygonStarted = !1, clip = {
point: point,
lineStart: lineStart,
lineEnd: lineEnd,
polygonStart: function() {
clip.point = pointRing, clip.lineStart = ringStart, clip.lineEnd = ringEnd, segments = [], polygon = [];
},
polygonEnd: function() {
clip.point = point, clip.lineStart = lineStart, clip.lineEnd = lineEnd, segments = merge(segments);
var startInside = polygonContains(polygon, start);
segments.length ? (polygonStarted || (sink.polygonStart(), polygonStarted = !0), clipRejoin(segments, compareIntersection, startInside, interpolate, sink)) : startInside && (polygonStarted || (sink.polygonStart(), polygonStarted = !0), sink.lineStart(), interpolate(null, null, 1, sink), sink.lineEnd()), polygonStarted && (sink.polygonEnd(), polygonStarted = !1), segments = polygon = null;
},
sphere: function() {
sink.polygonStart(), sink.lineStart(), interpolate(null, null, 1, sink), sink.lineEnd(), sink.polygonEnd();
}
};
function point(lambda, phi) {
pointVisible(lambda, phi) && sink.point(lambda, phi);
}
function pointLine(lambda, phi) {
line.point(lambda, phi);
}
function lineStart() {
clip.point = pointLine, line.lineStart();
}
function lineEnd() {
clip.point = point, line.lineEnd();
}
function pointRing(lambda, phi) {
ring.push([
lambda,
phi
]), ringSink.point(lambda, phi);
}
function ringStart() {
ringSink.lineStart(), ring = [];
}
function ringEnd() {
pointRing(ring[0][0], ring[0][1]), ringSink.lineEnd();
var i, m, segment, point, clean = ringSink.clean(), ringSegments = ringBuffer.result(), n = ringSegments.length;
if (ring.pop(), polygon.push(ring), ring = null, n) {
// No intersections.
if (1 & clean) {
if ((m = (segment = ringSegments[0]).length - 1) > 0) {
for(polygonStarted || (sink.polygonStart(), polygonStarted = !0), sink.lineStart(), i = 0; i < m; ++i)sink.point((point = segment[i])[0], point[1]);
sink.lineEnd();
}
return;
}
n > 1 && 2 & clean && ringSegments.push(ringSegments.pop().concat(ringSegments.shift())), segments.push(ringSegments.filter(validSegment));
}
}
return clip;
};
}
function validSegment(segment) {
return segment.length > 1;
}
// Intersections are sorted along the clip edge. For both antimeridian cutting
// and circle clipping, the same comparison is used.
function compareIntersection(a, b) {
return ((a = a.x)[0] < 0 ? a[1] - halfPi$2 - 1e-6 : halfPi$2 - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfPi$2 - 1e-6 : halfPi$2 - b[1]);
}
rotationIdentity.invert = rotationIdentity;
var clipAntimeridian = clip(function() {
return !0;
}, // Takes a line and cuts into visible segments. Return values: 0 - there were
// intersections or the line was empty; 1 - no intersections; 2 - there were
// intersections, and the first and last segments should be rejoined.
function(stream) {
var clean, lambda0 = NaN, phi0 = NaN, sign0 = NaN; // no intersections
return {
lineStart: function() {
stream.lineStart(), clean = 1;
},
point: function(lambda1, phi1) {
var lambda01, phi01, lambda11, cosPhi0, cosPhi1, sinLambda0Lambda1, sign1 = lambda1 > 0 ? pi$3 : -pi$3, delta = abs$2(lambda1 - lambda0);
1e-6 > abs$2(delta - pi$3) ? (stream.point(lambda0, phi0 = (phi0 + phi1) / 2 > 0 ? halfPi$2 : -halfPi$2), stream.point(sign0, phi0), stream.lineEnd(), stream.lineStart(), stream.point(sign1, phi0), stream.point(lambda1, phi0), clean = 0) : sign0 !== sign1 && delta >= pi$3 && (1e-6 > abs$2(lambda0 - sign0) && (lambda0 -= 1e-6 * sign0), 1e-6 > abs$2(lambda1 - sign1) && (lambda1 -= 1e-6 * sign1), lambda01 = lambda0, phi01 = phi0, phi0 = abs$2(sinLambda0Lambda1 = sin$1(lambda01 - (lambda11 = lambda1))) > 1e-6 ? atan((sin$1(phi01) * (cosPhi1 = cos$1(phi1)) * sin$1(lambda11) - sin$1(phi1) * (cosPhi0 = cos$1(phi01)) * sin$1(lambda01)) / (cosPhi0 * cosPhi1 * sinLambda0Lambda1)) : (phi01 + phi1) / 2, stream.point(sign0, phi0), stream.lineEnd(), stream.lineStart(), stream.point(sign1, phi0), clean = 0), stream.point(lambda0 = lambda1, phi0 = phi1), sign0 = sign1;
},
lineEnd: function() {
stream.lineEnd(), lambda0 = phi0 = NaN;
},
clean: function() {
return 2 - clean; // if intersections, rejoin first and last segments
}
};
}, function(from, to, direction, stream) {
var phi;
if (null == from) phi = direction * halfPi$2, stream.point(-pi$3, phi), stream.point(0, phi), stream.point(pi$3, phi), stream.point(pi$3, 0), stream.point(pi$3, -phi), stream.point(0, -phi), stream.point(-pi$3, -phi), stream.point(-pi$3, 0), stream.point(-pi$3, phi);
else if (abs$2(from[0] - to[0]) > 1e-6) {
var lambda = from[0] < to[0] ? pi$3 : -pi$3;
phi = direction * lambda / 2, stream.point(-lambda, phi), stream.point(0, phi), stream.point(lambda, phi);
} else stream.point(to[0], to[1]);
}, [
-pi$3,
-halfPi$2
]);
function clipCircle(radius) {
var cr = cos$1(radius), delta = 6 * radians$1, smallRadius = cr > 0, notHemisphere = abs$2(cr) > 1e-6; // TODO optimise for this common case
function visible(lambda, phi) {
return cos$1(lambda) * cos$1(phi) > cr;
}
// Intersects the great circle between a and b with the clip circle.
function intersect(a, b, two) {
var pa = cartesian(a), pb = cartesian(b), n1 = [
1,
0,
0
], n2 = cartesianCross(pa, pb), n2n2 = cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2;
// Two polar points.
if (!determinant) return !two && a;
var n1xn2 = cartesianCross(n1, n2), A = cartesianScale(n1, cr * n2n2 / determinant);
cartesianAddInPlace(A, cartesianScale(n2, -cr * n1n2 / determinant));
// Solve |p(t)|^2 = 1.
var w = cartesianDot(A, n1xn2), uu = cartesianDot(n1xn2, n1xn2), t2 = w * w - uu * (cartesianDot(A, A) - 1);
if (!(t2 < 0)) {
var t = sqrt(t2), q = cartesianScale(n1xn2, (-w - t) / uu);
if (cartesianAddInPlace(q, A), q = spherical(q), !two) return q;
// Two intersection points.
var z, lambda0 = a[0], lambda1 = b[0], phi0 = a[1], phi1 = b[1];
lambda1 < lambda0 && (z = lambda0, lambda0 = lambda1, lambda1 = z);
var delta = lambda1 - lambda0, polar = 1e-6 > abs$2(delta - pi$3);
// Check that the first point is between a and b.
if (!polar && phi1 < phi0 && (z = phi0, phi0 = phi1, phi1 = z), polar || delta < 1e-6 ? polar ? phi0 + phi1 > 0 ^ q[1] < (1e-6 > abs$2(q[0] - lambda0) ? phi0 : phi1) : phi0 <= q[1] && q[1] <= phi1 : delta > pi$3 ^ (lambda0 <= q[0] && q[0] <= lambda1)) {
var q1 = cartesianScale(n1xn2, (-w + t) / uu);
return cartesianAddInPlace(q1, A), [
q,
spherical(q1)
];
}
}
}
// Generates a 4-bit vector representing the location of a point relative to
// the small circle's bounding box.
function code(lambda, phi) {
var r = smallRadius ? radius : pi$3 - radius, code = 0;
return lambda < -r ? code |= 1 : lambda > r && (code |= 2), phi < -r ? code |= 4 : phi > r && (code |= 8), code;
}
return clip(visible, // Takes a line and cuts into visible segments. Return values used for polygon
// clipping: 0 - there were intersections or the line was empty; 1 - no
// intersections 2 - there were intersections, and the first and last segments
// should be rejoined.
function(stream) {
var point0, c0, v0, v00, clean; // no intersections
return {
lineStart: function() {
v00 = v0 = !1, clean = 1;
},
point: function(lambda, phi) {
var t, point2, point1 = [
lambda,
phi
], v = visible(lambda, phi), c = smallRadius ? v ? 0 : code(lambda, phi) : v ? code(lambda + (lambda < 0 ? pi$3 : -pi$3), phi) : 0;
!point0 && (v00 = v0 = v) && stream.lineStart(), v !== v0 && (!(point2 = intersect(point0, point1)) || pointEqual(point0, point2) || pointEqual(point1, point2)) && (point1[2] = 1), v !== v0 ? (clean = 0, v ? (// outside going in
stream.lineStart(), point2 = intersect(point1, point0), stream.point(point2[0], point2[1])) : (// inside going out
point2 = intersect(point0, point1), stream.point(point2[0], point2[1], 2), stream.lineEnd()), point0 = point2) : notHemisphere && point0 && smallRadius ^ v && !(c & c0) && (t = intersect(point1, point0, !0)) && (clean = 0, smallRadius ? (stream.lineStart(), stream.point(t[0][0], t[0][1]), stream.point(t[1][0], t[1][1]), stream.lineEnd()) : (stream.point(t[1][0], t[1][1]), stream.lineEnd(), stream.lineStart(), stream.point(t[0][0], t[0][1], 3))), !v || point0 && pointEqual(point0, point1) || stream.point(point1[0], point1[1]), point0 = point1, v0 = v, c0 = c;
},
lineEnd: function() {
v0 && stream.lineEnd(), point0 = null;
},
// Rejoin first and last segments if there were intersections and the first
// and last points were visible.
clean: function() {
return clean | (v00 && v0) << 1;
}
};
}, function(from, to, direction, stream) {
circleStream(stream, radius, delta, direction, from, to);
}, smallRadius ? [
0,
-radius
] : [
-pi$3,
radius - pi$3
]);
}
// TODO Use d3-polygon’s polygonContains here for the ring check?
// TODO Eliminate duplicate buffering in clipBuffer and polygon.push?
function clipRectangle(x0, y0, x1, y1) {
function visible(x, y) {
return x0 <= x && x <= x1 && y0 <= y && y <= y1;
}
function interpolate(from, to, direction, stream) {
var a = 0, a1 = 0;
if (null == from || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || 0 > comparePoint(from, to) ^ direction > 0) do stream.point(0 === a || 3 === a ? x0 : x1, a > 1 ? y1 : y0);
while ((a = (a + direction + 4) % 4) !== a1)
else stream.point(to[0], to[1]);
}
function corner(p, direction) {
return 1e-6 > abs$2(p[0] - x0) ? direction > 0 ? 0 : 3 : 1e-6 > abs$2(p[0] - x1) ? direction > 0 ? 2 : 1 : 1e-6 > abs$2(p[1] - y0) ? +(direction > 0) : direction > 0 ? 3 : 2; // abs(p[1] - y1) < epsilon
}
function compareIntersection(a, b) {
return comparePoint(a.x, b.x);
}
function comparePoint(a, b) {
var ca = corner(a, 1), cb = corner(b, 1);
return ca !== cb ? ca - cb : 0 === ca ? b[1] - a[1] : 1 === ca ? a[0] - b[0] : 2 === ca ? a[1] - b[1] : b[0] - a[0];
}
return function(stream) {
var segments, polygon, ring, x__, y__, v__, x_, y_, v_, first, clean, activeStream = stream, bufferStream = clipBuffer(), clipStream = {
point: point,
lineStart: function() {
clipStream.point = linePoint, polygon && polygon.push(ring = []), first = !0, v_ = !1, x_ = y_ = NaN;
},
lineEnd: // TODO rather than special-case polygons, simply handle them separately.
// Ideally, coincident intersection points should be jittered to avoid
// clipping issues.
function() {
segments && (linePoint(x__, y__), v__ && v_ && bufferStream.rejoin(), segments.push(bufferStream.result())), clipStream.point = point, v_ && activeStream.lineEnd();
},
polygonStart: // Buffer geometry within a polygon and then clip it en masse.
function() {
activeStream = bufferStream, segments = [], polygon = [], clean = !0;
},
polygonEnd: function() {
var startInside = function() {
for(var winding = 0, i = 0, n = polygon.length; i < n; ++i)for(var a0, a1, ring = polygon[i], j = 1, m = ring.length, point = ring[0], b0 = point[0], b1 = point[1]; j < m; ++j)a0 = b0, a1 = b1, b0 = (point = ring[j])[0], b1 = point[1], a1 <= y1 ? b1 > y1 && (b0 - a0) * (y1 - a1) > (b1 - a1) * (x0 - a0) && ++winding : b1 <= y1 && (b0 - a0) * (y1 - a1) < (b1 - a1) * (x0 - a0) && --winding;
return winding;
}(), cleanInside = clean && startInside, visible = (segments = merge(segments)).length;
(cleanInside || visible) && (stream.polygonStart(), cleanInside && (stream.lineStart(), interpolate(null, null, 1, stream), stream.lineEnd()), visible && clipRejoin(segments, compareIntersection, startInside, interpolate, stream), stream.polygonEnd()), activeStream = stream, segments = polygon = ring = null;
}
};
function point(x, y) {
visible(x, y) && activeStream.point(x, y);
}
function linePoint(x, y) {
var v = visible(x, y);
if (polygon && ring.push([
x,
y
]), first) x__ = x, y__ = y, v__ = v, first = !1, v && (activeStream.lineStart(), activeStream.point(x, y));
else if (v && v_) activeStream.point(x, y);
else {
var a = [
x_ = Math.max(-1000000000, Math.min(1e9, x_)),
y_ = Math.max(-1000000000, Math.min(1e9, y_))
], b = [
x = Math.max(-1000000000, Math.min(1e9, x)),
y = Math.max(-1000000000, Math.min(1e9, y))
];
!function(a, b, x0, y0, x1, y1) {
var r, ax = a[0], ay = a[1], bx = b[0], by = b[1], t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay;
if (r = x0 - ax, dx || !(r > 0)) {
if (r /= dx, dx < 0) {
if (r < t0) return;
r < t1 && (t1 = r);
} else if (dx > 0) {
if (r > t1) return;
r > t0 && (t0 = r);
}
if (r = x1 - ax, dx || !(r < 0)) {
if (r /= dx, dx < 0) {
if (r > t1) return;
r > t0 && (t0 = r);
} else if (dx > 0) {
if (r < t0) return;
r < t1 && (t1 = r);
}
if (r = y0 - ay, dy || !(r > 0)) {
if (r /= dy, dy < 0) {
if (r < t0) return;
r < t1 && (t1 = r);
} else if (dy > 0) {
if (r > t1) return;
r > t0 && (t0 = r);
}
if (r = y1 - ay, dy || !(r < 0)) {
if (r /= dy, dy < 0) {
if (r > t1) return;
r > t0 && (t0 = r);
} else if (dy > 0) {
if (r < t0) return;
r < t1 && (t1 = r);
}
return t0 > 0 && (a[0] = ax + t0 * dx, a[1] = ay + t0 * dy), t1 < 1 && (b[0] = ax + t1 * dx, b[1] = ay + t1 * dy), !0;
}
}
}
}
}(a, b, x0, y0, x1, y1) ? v && (activeStream.lineStart(), activeStream.point(x, y), clean = !1) : (v_ || (activeStream.lineStart(), activeStream.point(a[0], a[1])), activeStream.point(b[0], b[1]), v || activeStream.lineEnd(), clean = !1);
}
x_ = x, y_ = y, v_ = v;
}
return clipStream;
};
}
var lengthStream = {
sphere: noop$2,
point: noop$2,
lineStart: function() {
lengthStream.point = lengthPointFirst, lengthStream.lineEnd = lengthLineEnd;
},
lineEnd: noop$2,
polygonStart: noop$2,
polygonEnd: noop$2
};
function lengthLineEnd() {
lengthStream.point = lengthStream.lineEnd = noop$2;
}
function lengthPointFirst(lambda, phi) {
lambda *= radians$1, phi *= radians$1, lambda0$2 = lambda, sinPhi0$1 = sin$1(phi), cosPhi0$1 = cos$1(phi), lengthStream.point = lengthPoint;
}
function lengthPoint(lambda, phi) {
lambda *= radians$1;
var sinPhi = sin$1(phi *= radians$1), cosPhi = cos$1(phi), delta = abs$2(lambda - lambda0$2), cosDelta = cos$1(delta), x = cosPhi * sin$1(delta), y = cosPhi0$1 * sinPhi - sinPhi0$1 * cosPhi * cosDelta, z = sinPhi0$1 * sinPhi + cosPhi0$1 * cosPhi * cosDelta;
lengthSum.add(atan2(sqrt(x * x + y * y), z)), lambda0$2 = lambda, sinPhi0$1 = sinPhi, cosPhi0$1 = cosPhi;
}
function length$2(object) {
return lengthSum = new Adder(), geoStream(object, lengthStream), +lengthSum;
}
var coordinates = [
null,
null
], object$1 = {
type: "LineString",
coordinates: coordinates
};
function distance(a, b) {
return coordinates[0] = a, coordinates[1] = b, length$2(object$1);
}
var containsObjectType = {
Feature: function(object, point) {
return containsGeometry(object.geometry, point);
},
FeatureCollection: function(object, point) {
for(var features = object.features, i = -1, n = features.length; ++i < n;)if (containsGeometry(features[i].geometry, point)) return !0;
return !1;
}
}, containsGeometryType = {
Sphere: function() {
return !0;
},
Point: function(object, point) {
return 0 === distance(object.coordinates, point);
},
MultiPoint: function(object, point) {
for(var coordinates = object.coordinates, i = -1, n = coordinates.length; ++i < n;)if (0 === distance(coordinates[i], point)) return !0;
return !1;
},
LineString: function(object, point) {
return containsLine(object.coordinates, point);
},
MultiLineString: function(object, point) {
for(var coordinates = object.coordinates, i = -1, n = coordinates.length; ++i < n;)if (containsLine(coordinates[i], point)) return !0;
return !1;
},
Polygon: function(object, point) {
return containsPolygon(object.coordinates, point);
},
MultiPolygon: function(object, point) {
for(var coordinates = object.coordinates, i = -1, n = coordinates.length; ++i < n;)if (containsPolygon(coordinates[i], point)) return !0;
return !1;
},
GeometryCollection: function(object, point) {
for(var geometries = object.geometries, i = -1, n = geometries.length; ++i < n;)if (containsGeometry(geometries[i], point)) return !0;
return !1;
}
};
function containsGeometry(geometry, point) {
return !!(geometry && containsGeometryType.hasOwnProperty(geometry.type)) && containsGeometryType[geometry.type](geometry, point);
}
function containsLine(coordinates, point) {
for(var ao, bo, ab, i = 0, n = coordinates.length; i < n; i++){
if (0 === (bo = distance(coordinates[i], point)) || i > 0 && (ab = distance(coordinates[i], coordinates[i - 1])) > 0 && ao <= ab && bo <= ab && (ao + bo - ab) * (1 - Math.pow((ao - bo) / ab, 2)) < 1e-12 * ab) return !0;
ao = bo;
}
return !1;
}
function containsPolygon(coordinates, point) {
return !!polygonContains(coordinates.map(ringRadians), pointRadians(point));
}
function ringRadians(ring) {
return (ring = ring.map(pointRadians)).pop(), ring;
}
function pointRadians(point) {
return [
point[0] * radians$1,
point[1] * radians$1
];
}
function graticuleX(y0, y1, dy) {
var y = sequence(y0, y1 - 1e-6, dy).concat(y1);
return function(x) {
return y.map(function(y) {
return [
x,
y
];
});
};
}
function graticuleY(x0, x1, dx) {
var x = sequence(x0, x1 - 1e-6, dx).concat(x1);
return function(y) {
return x.map(function(x) {
return [
x,
y
];
});
};
}
function graticule() {
var x1, x0, X1, X0, y1, y0, Y1, Y0, x, y, X, Y, dx = 10, dy = 10, DX = 90, DY = 360, precision = 2.5;
function graticule() {
return {
type: "MultiLineString",
coordinates: lines()
};
}
function lines() {
return sequence(ceil(X0 / DX) * DX, X1, DX).map(X).concat(sequence(ceil(Y0 / DY) * DY, Y1, DY).map(Y)).concat(sequence(ceil(x0 / dx) * dx, x1, dx).filter(function(x) {
return abs$2(x % DX) > 1e-6;
}).map(x)).concat(sequence(ceil(y0 / dy) * dy, y1, dy).filter(function(y) {
return abs$2(y % DY) > 1e-6;
}).map(y));
}
return graticule.lines = function() {
return lines().map(function(coordinates) {
return {
type: "LineString",
coordinates: coordinates
};
});
}, graticule.outline = function() {
return {
type: "Polygon",
coordinates: [
X(X0).concat(Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1))
]
};
}, graticule.extent = function(_) {
return arguments.length ? graticule.extentMajor(_).extentMinor(_) : graticule.extentMinor();
}, graticule.extentMajor = function(_) {
return arguments.length ? (X0 = +_[0][0], X1 = +_[1][0], Y0 = +_[0][1], Y1 = +_[1][1], X0 > X1 && (_ = X0, X0 = X1, X1 = _), Y0 > Y1 && (_ = Y0, Y0 = Y1, Y1 = _), graticule.precision(precision)) : [
[
X0,
Y0
],
[
X1,
Y1
]
];
}, graticule.extentMinor = function(_) {
return arguments.length ? (x0 = +_[0][0], x1 = +_[1][0], y0 = +_[0][1], y1 = +_[1][1], x0 > x1 && (_ = x0, x0 = x1, x1 = _), y0 > y1 && (_ = y0, y0 = y1, y1 = _), graticule.precision(precision)) : [
[
x0,
y0
],
[
x1,
y1
]
];
}, graticule.step = function(_) {
return arguments.length ? graticule.stepMajor(_).stepMinor(_) : graticule.stepMinor();
}, graticule.stepMajor = function(_) {
return arguments.length ? (DX = +_[0], DY = +_[1], graticule) : [
DX,
DY
];
}, graticule.stepMinor = function(_) {
return arguments.length ? (dx = +_[0], dy = +_[1], graticule) : [
dx,
dy
];
}, graticule.precision = function(_) {
return arguments.length ? (precision = +_, x = graticuleX(y0, y1, 90), y = graticuleY(x0, x1, precision), X = graticuleX(Y0, Y1, 90), Y = graticuleY(X0, X1, precision), graticule) : precision;
}, graticule.extentMajor([
[
-180,
-89.999999
],
[
180,
89.999999
]
]).extentMinor([
[
-180,
-80.000001
],
[
180,
80.000001
]
]);
}
var lambda0$1, phi0, lambda1, phi1, lambda2, lambda00$1, phi00$1, p0, deltaSum, ranges, range$1, W0, W1, X0, Y0, Z0, X1, Y1, Z1, X2, Y2, Z2, lambda00$2, phi00$2, x0, y0, z0, lengthSum, lambda0$2, sinPhi0$1, cosPhi0$1, x00, y00, x0$1, y0$1, identity$4 = (x)=>x, areaSum$1 = new Adder(), areaRingSum$1 = new Adder(), areaStream$1 = {
point: noop$2,
lineStart: noop$2,
lineEnd: noop$2,
polygonStart: function() {
areaStream$1.lineStart = areaRingStart$1, areaStream$1.lineEnd = areaRingEnd$1;
},
polygonEnd: function() {
areaStream$1.lineStart = areaStream$1.lineEnd = areaStream$1.point = noop$2, areaSum$1.add(abs$2(areaRingSum$1)), areaRingSum$1 = new Adder();
},
result: function() {
var area = areaSum$1 / 2;
return areaSum$1 = new Adder(), area;
}
};
function areaRingStart$1() {
areaStream$1.point = areaPointFirst$1;
}
function areaPointFirst$1(x, y) {
areaStream$1.point = areaPoint$1, x00 = x0$1 = x, y00 = y0$1 = y;
}
function areaPoint$1(x, y) {
areaRingSum$1.add(y0$1 * x - x0$1 * y), x0$1 = x, y0$1 = y;
}
function areaRingEnd$1() {
areaPoint$1(x00, y00);
}
var x00$1, y00$1, x0$3, y0$3, x0$2 = 1 / 0, y0$2 = 1 / 0, x1 = -1 / 0, y1 = x1, boundsStream$1 = {
point: function(x, y) {
x < x0$2 && (x0$2 = x), x > x1 && (x1 = x), y < y0$2 && (y0$2 = y), y > y1 && (y1 = y);
},
lineStart: noop$2,
lineEnd: noop$2,
polygonStart: noop$2,
polygonEnd: noop$2,
result: function() {
var bounds = [
[
x0$2,
y0$2
],
[
x1,
y1
]
];
return x1 = y1 = -(y0$2 = x0$2 = 1 / 0), bounds;
}
}, X0$1 = 0, Y0$1 = 0, Z0$1 = 0, X1$1 = 0, Y1$1 = 0, Z1$1 = 0, X2$1 = 0, Y2$1 = 0, Z2$1 = 0, centroidStream$1 = {
point: centroidPoint$1,
lineStart: centroidLineStart$1,
lineEnd: centroidLineEnd$1,
polygonStart: function() {
centroidStream$1.lineStart = centroidRingStart$1, centroidStream$1.lineEnd = centroidRingEnd$1;
},
polygonEnd: function() {
centroidStream$1.point = centroidPoint$1, centroidStream$1.lineStart = centroidLineStart$1, centroidStream$1.lineEnd = centroidLineEnd$1;
},
result: function() {
var centroid = Z2$1 ? [
X2$1 / Z2$1,
Y2$1 / Z2$1
] : Z1$1 ? [
X1$1 / Z1$1,
Y1$1 / Z1$1
] : Z0$1 ? [
X0$1 / Z0$1,
Y0$1 / Z0$1
] : [
NaN,
NaN
];
return X0$1 = Y0$1 = Z0$1 = X1$1 = Y1$1 = Z1$1 = X2$1 = Y2$1 = Z2$1 = 0, centroid;
}
};
function centroidPoint$1(x, y) {
X0$1 += x, Y0$1 += y, ++Z0$1;
}
function centroidLineStart$1() {
centroidStream$1.point = centroidPointFirstLine;
}
function centroidPointFirstLine(x, y) {
centroidStream$1.point = centroidPointLine, centroidPoint$1(x0$3 = x, y0$3 = y);
}
function centroidPointLine(x, y) {
var dx = x - x0$3, dy = y - y0$3, z = sqrt(dx * dx + dy * dy);
X1$1 += z * (x0$3 + x) / 2, Y1$1 += z * (y0$3 + y) / 2, Z1$1 += z, centroidPoint$1(x0$3 = x, y0$3 = y);
}
function centroidLineEnd$1() {
centroidStream$1.point = centroidPoint$1;
}
function centroidRingStart$1() {
centroidStream$1.point = centroidPointFirstRing;
}
function centroidRingEnd$1() {
centroidPointRing(x00$1, y00$1);
}
function centroidPointFirstRing(x, y) {
centroidStream$1.point = centroidPointRing, centroidPoint$1(x00$1 = x0$3 = x, y00$1 = y0$3 = y);
}
function centroidPointRing(x, y) {
var dx = x - x0$3, dy = y - y0$3, z = sqrt(dx * dx + dy * dy);
X1$1 += z * (x0$3 + x) / 2, Y1$1 += z * (y0$3 + y) / 2, Z1$1 += z, X2$1 += (z = y0$3 * x - x0$3 * y) * (x0$3 + x), Y2$1 += z * (y0$3 + y), Z2$1 += 3 * z, centroidPoint$1(x0$3 = x, y0$3 = y);
}
function PathContext(context) {
this._context = context;
}
PathContext.prototype = {
_radius: 4.5,
pointRadius: function(_) {
return this._radius = _, this;
},
polygonStart: function() {
this._line = 0;
},
polygonEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._point = 0;
},
lineEnd: function() {
0 === this._line && this._context.closePath(), this._point = NaN;
},
point: function(x, y) {
switch(this._point){
case 0:
this._context.moveTo(x, y), this._point = 1;
break;
case 1:
this._context.lineTo(x, y);
break;
default:
this._context.moveTo(x + this._radius, y), this._context.arc(x, y, this._radius, 0, tau$4);
}
},
result: noop$2
};
var lengthRing, x00$2, y00$2, x0$4, y0$4, lengthSum$1 = new Adder(), lengthStream$1 = {
point: noop$2,
lineStart: function() {
lengthStream$1.point = lengthPointFirst$1;
},
lineEnd: function() {
lengthRing && lengthPoint$1(x00$2, y00$2), lengthStream$1.point = noop$2;
},
polygonStart: function() {
lengthRing = !0;
},
polygonEnd: function() {
lengthRing = null;
},
result: function() {
var length = +lengthSum$1;
return lengthSum$1 = new Adder(), length;
}
};
function lengthPointFirst$1(x, y) {
lengthStream$1.point = lengthPoint$1, x00$2 = x0$4 = x, y00$2 = y0$4 = y;
}
function lengthPoint$1(x, y) {
x0$4 -= x, y0$4 -= y, lengthSum$1.add(sqrt(x0$4 * x0$4 + y0$4 * y0$4)), x0$4 = x, y0$4 = y;
}
function PathString() {
this._string = [];
}
function circle$1(radius) {
return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius + "z";
}
function transformer(methods) {
return function(stream) {
var s = new TransformStream;
for(var key in methods)s[key] = methods[key];
return s.stream = stream, s;
};
}
function TransformStream() {}
function fit(projection, fitBounds, object) {
var clip = projection.clipExtent && projection.clipExtent();
return projection.scale(150).translate([
0,
0
]), null != clip && projection.clipExtent(null), geoStream(object, projection.stream(boundsStream$1)), fitBounds(boundsStream$1.result()), null != clip && projection.clipExtent(clip), projection;
}
function fitExtent(projection, extent, object) {
return fit(projection, function(b) {
var w = extent[1][0] - extent[0][0], h = extent[1][1] - extent[0][1], k = Math.min(w / (b[1][0] - b[0][0]), h / (b[1][1] - b[0][1])), x = +extent[0][0] + (w - k * (b[1][0] + b[0][0])) / 2, y = +extent[0][1] + (h - k * (b[1][1] + b[0][1])) / 2;
projection.scale(150 * k).translate([
x,
y
]);
}, object);
}
function fitSize(projection, size, object) {
return fitExtent(projection, [
[
0,
0
],
size
], object);
}
function fitWidth(projection, width, object) {
return fit(projection, function(b) {
var w = +width, k = w / (b[1][0] - b[0][0]), x = (w - k * (b[1][0] + b[0][0])) / 2, y = -k * b[0][1];
projection.scale(150 * k).translate([
x,
y
]);
}, object);
}
function fitHeight(projection, height, object) {
return fit(projection, function(b) {
var h = +height, k = h / (b[1][1] - b[0][1]), x = -k * b[0][0], y = (h - k * (b[1][1] + b[0][1])) / 2;
projection.scale(150 * k).translate([
x,
y
]);
}, object);
}
PathString.prototype = {
_radius: 4.5,
_circle: circle$1(4.5),
pointRadius: function(_) {
return (_ *= 1) !== this._radius && (this._radius = _, this._circle = null), this;
},
polygonStart: function() {
this._line = 0;
},
polygonEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._point = 0;
},
lineEnd: function() {
0 === this._line && this._string.push("Z"), this._point = NaN;
},
point: function(x, y) {
switch(this._point){
case 0:
this._string.push("M", x, ",", y), this._point = 1;
break;
case 1:
this._string.push("L", x, ",", y);
break;
default:
null == this._circle && (this._circle = circle$1(this._radius)), this._string.push("M", x, ",", y, this._circle);
}
},
result: function() {
if (!this._string.length) return null;
var result = this._string.join("");
return this._string = [], result;
}
}, TransformStream.prototype = {
constructor: TransformStream,
point: function(x, y) {
this.stream.point(x, y);
},
sphere: function() {
this.stream.sphere();
},
lineStart: function() {
this.stream.lineStart();
},
lineEnd: function() {
this.stream.lineEnd();
},
polygonStart: function() {
this.stream.polygonStart();
},
polygonEnd: function() {
this.stream.polygonEnd();
}
};
var cosMinDistance = cos$1(30 * radians$1); // cos(minimum angular distance)
function resample(project, delta2) {
return +delta2 ? function(project, delta2) {
function resampleLineTo(x0, y0, lambda0, a0, b0, c0, x1, y1, lambda1, a1, b1, c1, depth, stream) {
var dx = x1 - x0, dy = y1 - y0, d2 = dx * dx + dy * dy;
if (d2 > 4 * delta2 && depth--) {
var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = sqrt(a * a + b * b + c * c), phi2 = asin(c /= m), lambda2 = 1e-6 > abs$2(abs$2(c) - 1) || 1e-6 > abs$2(lambda0 - lambda1) ? (lambda0 + lambda1) / 2 : atan2(b, a), p = project(lambda2, phi2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2;
(dz * dz / d2 > delta2 // perpendicular projected distance
|| abs$2((dx * dx2 + dy * dy2) / d2 - 0.5) > 0.3 // midpoint close to an end
|| a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) && (resampleLineTo(x0, y0, lambda0, a0, b0, c0, x2, y2, lambda2, a /= m, b /= m, c, depth, stream), stream.point(x2, y2), resampleLineTo(x2, y2, lambda2, a, b, c, x1, y1, lambda1, a1, b1, c1, depth, stream));
}
}
return function(stream) {
var lambda00, x00, y00, a00, b00, c00, lambda0, x0, y0, a0, b0, c0, resampleStream = {
point: point,
lineStart: lineStart,
lineEnd: lineEnd,
polygonStart: function() {
stream.polygonStart(), resampleStream.lineStart = ringStart;
},
polygonEnd: function() {
stream.polygonEnd(), resampleStream.lineStart = lineStart;
}
};
function point(x, y) {
x = project(x, y), stream.point(x[0], x[1]);
}
function lineStart() {
x0 = NaN, resampleStream.point = linePoint, stream.lineStart();
}
function linePoint(lambda, phi) {
var c = cartesian([
lambda,
phi
]), p = project(lambda, phi);
resampleLineTo(x0, y0, lambda0, a0, b0, c0, x0 = p[0], y0 = p[1], lambda0 = lambda, a0 = c[0], b0 = c[1], c0 = c[2], 16, stream), stream.point(x0, y0);
}
function lineEnd() {
resampleStream.point = point, stream.lineEnd();
}
function ringStart() {
lineStart(), resampleStream.point = ringPoint, resampleStream.lineEnd = ringEnd;
}
function ringPoint(lambda, phi) {
linePoint(lambda00 = lambda, phi), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0, resampleStream.point = linePoint;
}
function ringEnd() {
resampleLineTo(x0, y0, lambda0, a0, b0, c0, x00, y00, lambda00, a00, b00, c00, 16, stream), resampleStream.lineEnd = lineEnd, lineEnd();
}
return resampleStream;
};
}(project, delta2) : transformer({
point: function(x, y) {
x = project(x, y), this.stream.point(x[0], x[1]);
}
});
}
var transformRadians = transformer({
point: function(x, y) {
this.stream.point(x * radians$1, y * radians$1);
}
});
function scaleTranslateRotate(k, dx, dy, sx, sy, alpha) {
if (!alpha) return function(k, dx, dy, sx, sy) {
function transform(x, y) {
return [
dx + k * (x *= sx),
dy - k * (y *= sy)
];
}
return transform.invert = function(x, y) {
return [
(x - dx) / k * sx,
(dy - y) / k * sy
];
}, transform;
}(k, dx, dy, sx, sy);
var cosAlpha = cos$1(alpha), sinAlpha = sin$1(alpha), a = cosAlpha * k, b = sinAlpha * k, ai = cosAlpha / k, bi = sinAlpha / k, ci = (sinAlpha * dy - cosAlpha * dx) / k, fi = (sinAlpha * dx + cosAlpha * dy) / k;
function transform(x, y) {
return [
a * (x *= sx) - b * (y *= sy) + dx,
dy - b * x - a * y
];
}
return transform.invert = function(x, y) {
return [
sx * (ai * x - bi * y + ci),
sy * (fi - bi * x - ai * y)
];
}, transform;
}
function projection(project) {
return projectionMutator(function() {
return project;
})();
}
function projectionMutator(projectAt) {
var project, rotate, y0, x1, y1, projectResample, projectTransform, projectRotateTransform, cache, cacheStream, k = 150, x = 480, y = 250, lambda = 0, phi = 0, deltaLambda = 0, deltaPhi = 0, deltaGamma = 0, alpha = 0, sx = 1, sy = 1, theta = null, preclip = clipAntimeridian, x0 = null, postclip = identity$4, delta2 = 0.5;
function projection(point) {
return projectRotateTransform(point[0] * radians$1, point[1] * radians$1);
}
function invert(point) {
return (point = projectRotateTransform.invert(point[0], point[1])) && [
point[0] * degrees$2,
point[1] * degrees$2
];
}
function recenter() {
var center = scaleTranslateRotate(k, 0, 0, sx, sy, alpha).apply(null, project(lambda, phi)), transform = scaleTranslateRotate(k, x - center[0], y - center[1], sx, sy, alpha);
return rotate = rotateRadians(deltaLambda, deltaPhi, deltaGamma), projectTransform = compose(project, transform), projectRotateTransform = compose(rotate, projectTransform), projectResample = resample(projectTransform, delta2), reset();
}
function reset() {
return cache = cacheStream = null, projection;
}
return projection.stream = function(stream) {
var rotate1;
return cache && cacheStream === stream ? cache : cache = transformRadians((rotate1 = rotate, transformer({
point: function(x, y) {
var r = rotate1(x, y);
return this.stream.point(r[0], r[1]);
}
}))(preclip(projectResample(postclip(cacheStream = stream)))));
}, projection.preclip = function(_) {
return arguments.length ? (preclip = _, theta = void 0, reset()) : preclip;
}, projection.postclip = function(_) {
return arguments.length ? (postclip = _, x0 = y0 = x1 = y1 = null, reset()) : postclip;
}, projection.clipAngle = function(_) {
return arguments.length ? (preclip = +_ ? clipCircle(theta = _ * radians$1) : (theta = null, clipAntimeridian), reset()) : theta * degrees$2;
}, projection.clipExtent = function(_) {
return arguments.length ? (postclip = null == _ ? (x0 = y0 = x1 = y1 = null, identity$4) : clipRectangle(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]), reset()) : null == x0 ? null : [
[
x0,
y0
],
[
x1,
y1
]
];
}, projection.scale = function(_) {
return arguments.length ? (k = +_, recenter()) : k;
}, projection.translate = function(_) {
return arguments.length ? (x = +_[0], y = +_[1], recenter()) : [
x,
y
];
}, projection.center = function(_) {
return arguments.length ? (lambda = _[0] % 360 * radians$1, phi = _[1] % 360 * radians$1, recenter()) : [
lambda * degrees$2,
phi * degrees$2
];
}, projection.rotate = function(_) {
return arguments.length ? (deltaLambda = _[0] % 360 * radians$1, deltaPhi = _[1] % 360 * radians$1, deltaGamma = _.length > 2 ? _[2] % 360 * radians$1 : 0, recenter()) : [
deltaLambda * degrees$2,
deltaPhi * degrees$2,
deltaGamma * degrees$2
];
}, projection.angle = function(_) {
return arguments.length ? (alpha = _ % 360 * radians$1, recenter()) : alpha * degrees$2;
}, projection.reflectX = function(_) {
return arguments.length ? (sx = _ ? -1 : 1, recenter()) : sx < 0;
}, projection.reflectY = function(_) {
return arguments.length ? (sy = _ ? -1 : 1, recenter()) : sy < 0;
}, projection.precision = function(_) {
return arguments.length ? (projectResample = resample(projectTransform, delta2 = _ * _), reset()) : sqrt(delta2);
}, projection.fitExtent = function(extent, object) {
return fitExtent(projection, extent, object);
}, projection.fitSize = function(size, object) {
return fitSize(projection, size, object);
}, projection.fitWidth = function(width, object) {
return fitWidth(projection, width, object);
}, projection.fitHeight = function(height, object) {
return fitHeight(projection, height, object);
}, function() {
return project = projectAt.apply(this, arguments), projection.invert = project.invert && invert, recenter();
};
}
function conicProjection(projectAt) {
var phi0 = 0, phi1 = pi$3 / 3, m = projectionMutator(projectAt), p = m(phi0, phi1);
return p.parallels = function(_) {
return arguments.length ? m(phi0 = _[0] * radians$1, phi1 = _[1] * radians$1) : [
phi0 * degrees$2,
phi1 * degrees$2
];
}, p;
}
function conicEqualAreaRaw(y0, y1) {
var sy0 = sin$1(y0), n = (sy0 + sin$1(y1)) / 2;
// Are the parallels symmetrical around the Equator?
if (1e-6 > abs$2(n)) return function(phi0) {
var cosPhi0 = cos$1(phi0);
function forward(lambda, phi) {
return [
lambda * cosPhi0,
sin$1(phi) / cosPhi0
];
}
return forward.invert = function(x, y) {
return [
x / cosPhi0,
asin(y * cosPhi0)
];
}, forward;
}(y0);
var c = 1 + sy0 * (2 * n - sy0), r0 = sqrt(c) / n;
function project(x, y) {
var r = sqrt(c - 2 * n * sin$1(y)) / n;
return [
r * sin$1(x *= n),
r0 - r * cos$1(x)
];
}
return project.invert = function(x, y) {
var r0y = r0 - y, l = atan2(x, abs$2(r0y)) * sign(r0y);
return r0y * n < 0 && (l -= pi$3 * sign(x) * sign(r0y)), [
l / n,
asin((c - (x * x + r0y * r0y) * n * n) / (2 * n))
];
}, project;
}
function conicEqualArea() {
return conicProjection(conicEqualAreaRaw).scale(155.424).center([
0,
33.6442
]);
}
function albers() {
return conicEqualArea().parallels([
29.5,
45.5
]).scale(1070).translate([
480,
250
]).rotate([
96,
0
]).center([
-0.6,
38.7
]);
}
function azimuthalRaw(scale) {
return function(x, y) {
var cx = cos$1(x), cy = cos$1(y), k = scale(cx * cy);
return k === 1 / 0 ? [
2,
0
] : [
k * cy * sin$1(x),
k * sin$1(y)
];
};
}
function azimuthalInvert(angle) {
return function(x, y) {
var z = sqrt(x * x + y * y), c = angle(z), sc = sin$1(c);
return [
atan2(x * sc, z * cos$1(c)),
asin(z && y * sc / z)
];
};
}
var azimuthalEqualAreaRaw = azimuthalRaw(function(cxcy) {
return sqrt(2 / (1 + cxcy));
});
azimuthalEqualAreaRaw.invert = azimuthalInvert(function(z) {
return 2 * asin(z / 2);
});
var azimuthalEquidistantRaw = azimuthalRaw(function(c) {
return (c = acos(c)) && c / sin$1(c);
});
function mercatorRaw(lambda, phi) {
return [
lambda,
log(tan((halfPi$2 + phi) / 2))
];
}
function mercatorProjection(project) {
var y0, x1, y1, m = projection(project), center = m.center, scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, x0 = null; // clip extent
function reclip() {
var k = pi$3 * scale(), t = m(rotation(m.rotate()).invert([
0,
0
]));
return clipExtent(null == x0 ? [
[
t[0] - k,
t[1] - k
],
[
t[0] + k,
t[1] + k
]
] : project === mercatorRaw ? [
[
Math.max(t[0] - k, x0),
y0
],
[
Math.min(t[0] + k, x1),
y1
]
] : [
[
x0,
Math.max(t[1] - k, y0)
],
[
x1,
Math.min(t[1] + k, y1)
]
]);
}
return m.scale = function(_) {
return arguments.length ? (scale(_), reclip()) : scale();
}, m.translate = function(_) {
return arguments.length ? (translate(_), reclip()) : translate();
}, m.center = function(_) {
return arguments.length ? (center(_), reclip()) : center();
}, m.clipExtent = function(_) {
return arguments.length ? (null == _ ? x0 = y0 = x1 = y1 = null : (x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]), reclip()) : null == x0 ? null : [
[
x0,
y0
],
[
x1,
y1
]
];
}, reclip();
}
function tany(y) {
return tan((halfPi$2 + y) / 2);
}
function conicConformalRaw(y0, y1) {
var cy0 = cos$1(y0), n = y0 === y1 ? sin$1(y0) : log(cy0 / cos$1(y1)) / log(tany(y1) / tany(y0)), f = cy0 * pow$1(tany(y0), n) / n;
if (!n) return mercatorRaw;
function project(x, y) {
f > 0 ? y < -halfPi$2 + 1e-6 && (y = -halfPi$2 + 1e-6) : y > halfPi$2 - 1e-6 && (y = halfPi$2 - 1e-6);
var r = f / pow$1(tany(y), n);
return [
r * sin$1(n * x),
f - r * cos$1(n * x)
];
}
return project.invert = function(x, y) {
var fy = f - y, r = sign(n) * sqrt(x * x + fy * fy), l = atan2(x, abs$2(fy)) * sign(fy);
return fy * n < 0 && (l -= pi$3 * sign(x) * sign(fy)), [
l / n,
2 * atan(pow$1(f / r, 1 / n)) - halfPi$2
];
}, project;
}
function equirectangularRaw(lambda, phi) {
return [
lambda,
phi
];
}
function conicEquidistantRaw(y0, y1) {
var cy0 = cos$1(y0), n = y0 === y1 ? sin$1(y0) : (cy0 - cos$1(y1)) / (y1 - y0), g = cy0 / n + y0;
if (1e-6 > abs$2(n)) return equirectangularRaw;
function project(x, y) {
var gy = g - y, nx = n * x;
return [
gy * sin$1(nx),
g - gy * cos$1(nx)
];
}
return project.invert = function(x, y) {
var gy = g - y, l = atan2(x, abs$2(gy)) * sign(gy);
return gy * n < 0 && (l -= pi$3 * sign(x) * sign(gy)), [
l / n,
g - sign(n) * sqrt(x * x + gy * gy)
];
}, project;
}
azimuthalEquidistantRaw.invert = azimuthalInvert(function(z) {
return z;
}), mercatorRaw.invert = function(x, y) {
return [
x,
2 * atan(exp(y)) - halfPi$2
];
}, equirectangularRaw.invert = equirectangularRaw;
var M = sqrt(3) / 2;
function equalEarthRaw(lambda, phi) {
var l = asin(M * sin$1(phi)), l2 = l * l, l6 = l2 * l2 * l2;
return [
lambda * cos$1(l) / (M * (1.340264 + -0.24331799999999998 * l2 + l6 * (0.0062510000000000005 + 0.034164 * l2))),
l * (1.340264 + -0.081106 * l2 + l6 * (0.000893 + 0.003796 * l2))
];
}
function gnomonicRaw(x, y) {
var cy = cos$1(y), k = cos$1(x) * cy;
return [
cy * sin$1(x) / k,
sin$1(y) / k
];
}
function naturalEarth1Raw(lambda, phi) {
var phi2 = phi * phi, phi4 = phi2 * phi2;
return [
lambda * (0.8707 - 0.131979 * phi2 + phi4 * (-0.013791 + phi4 * (0.003971 * phi2 - 0.001529 * phi4))),
phi * (1.007226 + phi2 * (0.015085 + phi4 * (-0.044475 + 0.028874 * phi2 - 0.005916 * phi4)))
];
}
function orthographicRaw(x, y) {
return [
cos$1(y) * sin$1(x),
sin$1(y)
];
}
function stereographicRaw(x, y) {
var cy = cos$1(y), k = 1 + cos$1(x) * cy;
return [
cy * sin$1(x) / k,
sin$1(y) / k
];
}
function transverseMercatorRaw(lambda, phi) {
return [
log(tan((halfPi$2 + phi) / 2)),
-lambda
];
}
function defaultSeparation(a, b) {
return a.parent === b.parent ? 1 : 2;
}
function meanXReduce(x, c) {
return x + c.x;
}
function maxYReduce(y, c) {
return Math.max(y, c.y);
}
function count$1(node) {
var sum = 0, children = node.children, i = children && children.length;
if (i) for(; --i >= 0;)sum += children[i].value;
else sum = 1;
node.value = sum;
}
function hierarchy(data, children) {
data instanceof Map ? (data = [
void 0,
data
], void 0 === children && (children = mapChildren)) : void 0 === children && (children = objectChildren);
for(var node, child, childs, i, n, root = new Node(data), nodes = [
root
]; node = nodes.pop();)if ((childs = children(node.data)) && (n = (childs = Array.from(childs)).length)) for(node.children = childs, i = n - 1; i >= 0; --i)nodes.push(child = childs[i] = new Node(childs[i])), child.parent = node, child.depth = node.depth + 1;
return root.eachBefore(computeHeight);
}
function objectChildren(d) {
return d.children;
}
function mapChildren(d) {
return Array.isArray(d) ? d[1] : null;
}
function copyData(node) {
void 0 !== node.data.value && (node.value = node.data.value), node.data = node.data.data;
}
function computeHeight(node) {
var height = 0;
do node.height = height;
while ((node = node.parent) && node.height < ++height)
}
function Node(data) {
this.data = data, this.depth = this.height = 0, this.parent = null;
}
function enclose(circles) {
for(var p, e, i = 0, n = (circles = function(array) {
for(var t, i, m = array.length; m;)i = Math.random() * m-- | 0, t = array[m], array[m] = array[i], array[i] = t;
return array;
}(Array.from(circles))).length, B = []; i < n;)p = circles[i], e && enclosesWeak(e, p) ? ++i : (e = function(B) {
switch(B.length){
case 1:
var a;
return {
x: (a = B[0]).x,
y: a.y,
r: a.r
};
case 2:
return encloseBasis2(B[0], B[1]);
case 3:
return encloseBasis3(B[0], B[1], B[2]);
}
}(B = function(B, p) {
var i, j;
if (enclosesWeakAll(p, B)) return [
p
];
// If we get here then B must have at least one element.
for(i = 0; i < B.length; ++i)if (enclosesNot(p, B[i]) && enclosesWeakAll(encloseBasis2(B[i], p), B)) return [
B[i],
p
];
// If we get here then B must have at least two elements.
for(i = 0; i < B.length - 1; ++i)for(j = i + 1; j < B.length; ++j)if (enclosesNot(encloseBasis2(B[i], B[j]), p) && enclosesNot(encloseBasis2(B[i], p), B[j]) && enclosesNot(encloseBasis2(B[j], p), B[i]) && enclosesWeakAll(encloseBasis3(B[i], B[j], p), B)) return [
B[i],
B[j],
p
];
// If we get here then something is very wrong.
throw Error();
}(B, p)), i = 0);
return e;
}
function enclosesNot(a, b) {
var dr = a.r - b.r, dx = b.x - a.x, dy = b.y - a.y;
return dr < 0 || dr * dr < dx * dx + dy * dy;
}
function enclosesWeak(a, b) {
var dr = a.r - b.r + 1e-9 * Math.max(a.r, b.r, 1), dx = b.x - a.x, dy = b.y - a.y;
return dr > 0 && dr * dr > dx * dx + dy * dy;
}
function enclosesWeakAll(a, B) {
for(var i = 0; i < B.length; ++i)if (!enclosesWeak(a, B[i])) return !1;
return !0;
}
function encloseBasis2(a, b) {
var x1 = a.x, y1 = a.y, r1 = a.r, x2 = b.x, y2 = b.y, r2 = b.r, x21 = x2 - x1, y21 = y2 - y1, r21 = r2 - r1, l = Math.sqrt(x21 * x21 + y21 * y21);
return {
x: (x1 + x2 + x21 / l * r21) / 2,
y: (y1 + y2 + y21 / l * r21) / 2,
r: (l + r1 + r2) / 2
};
}
function encloseBasis3(a, b, c) {
var x1 = a.x, y1 = a.y, r1 = a.r, x2 = b.x, y2 = b.y, r2 = b.r, x3 = c.x, y3 = c.y, r3 = c.r, a2 = x1 - x2, a3 = x1 - x3, b2 = y1 - y2, b3 = y1 - y3, c2 = r2 - r1, c3 = r3 - r1, d1 = x1 * x1 + y1 * y1 - r1 * r1, d2 = d1 - x2 * x2 - y2 * y2 + r2 * r2, d3 = d1 - x3 * x3 - y3 * y3 + r3 * r3, ab = a3 * b2 - a2 * b3, xa = (b2 * d3 - b3 * d2) / (2 * ab) - x1, xb = (b3 * c2 - b2 * c3) / ab, ya = (a3 * d2 - a2 * d3) / (2 * ab) - y1, yb = (a2 * c3 - a3 * c2) / ab, A = xb * xb + yb * yb - 1, B = 2 * (r1 + xa * xb + ya * yb), C = xa * xa + ya * ya - r1 * r1, r = -(A ? (B + Math.sqrt(B * B - 4 * A * C)) / (2 * A) : C / B);
return {
x: x1 + xa + xb * r,
y: y1 + ya + yb * r,
r: r
};
}
function place(b, a, c) {
var x, a2, y, b2, dx = b.x - a.x, dy = b.y - a.y, d2 = dx * dx + dy * dy;
d2 ? (a2 = a.r + c.r, a2 *= a2, b2 = b.r + c.r, a2 > (b2 *= b2) ? (x = (d2 + b2 - a2) / (2 * d2), y = Math.sqrt(Math.max(0, b2 / d2 - x * x)), c.x = b.x - x * dx - y * dy, c.y = b.y - x * dy + y * dx) : (x = (d2 + a2 - b2) / (2 * d2), y = Math.sqrt(Math.max(0, a2 / d2 - x * x)), c.x = a.x + x * dx - y * dy, c.y = a.y + x * dy + y * dx)) : (c.x = a.x + c.r, c.y = a.y);
}
function intersects(a, b) {
var dr = a.r + b.r - 1e-6, dx = b.x - a.x, dy = b.y - a.y;
return dr > 0 && dr * dr > dx * dx + dy * dy;
}
function score(node) {
var a = node._, b = node.next._, ab = a.r + b.r, dx = (a.x * b.r + b.x * a.r) / ab, dy = (a.y * b.r + b.y * a.r) / ab;
return dx * dx + dy * dy;
}
function Node$1(circle) {
this._ = circle, this.next = null, this.previous = null;
}
function packEnclose(circles) {
var a, b, c, n, aa, ca, i, j, k, sj, sk, x;
if (!(n = (circles = "object" == typeof (x = circles) && "length" in x ? x // Array, TypedArray, NodeList, array-like
: Array.from(x)).length)) return 0;
if (// Place the first circle.
(a = circles[0]).x = 0, a.y = 0, !(n > 1)) return a.r;
if (// Place the second circle.
b = circles[1], a.x = -b.r, b.x = a.r, b.y = 0, !(n > 2)) return a.r + b.r;
// Place the third circle.
place(b, a, c = circles[2]), // Initialize the front-chain using the first three circles a, b and c.
a = new Node$1(a), b = new Node$1(b), c = new Node$1(c), a.next = c.previous = b, b.next = a.previous = c, c.next = b.previous = a;
// Attempt to place each remaining circle…
pack: for(i = 3; i < n; ++i){
place(a._, b._, c = circles[i]), c = new Node$1(c), // Find the closest intersecting circle on the front-chain, if any.
// “Closeness” is determined by linear distance along the front-chain.
// “Ahead” or “behind” is likewise determined by linear distance.
j = b.next, k = a.previous, sj = b._.r, sk = a._.r;
do if (sj <= sk) {
if (intersects(j._, c._)) {
b = j, a.next = b, b.previous = a, --i;
continue pack;
}
sj += j._.r, j = j.next;
} else {
if (intersects(k._, c._)) {
(a = k).next = b, b.previous = a, --i;
continue pack;
}
sk += k._.r, k = k.previous;
}
while (j !== k.next)
for(// Success! Insert the new circle c between a and b.
c.previous = a, c.next = b, a.next = b.previous = b = c, // Compute the new closest circle pair to the centroid.
aa = score(a); (c = c.next) !== b;)(ca = score(c)) < aa && (a = c, aa = ca);
b = a.next;
}
for(// Compute the enclosing circle of the front chain.
a = [
b._
], c = b; (c = c.next) !== b;)a.push(c._);
// Translate the circles to put the enclosing circle around the origin.
for(i = 0, c = enclose(a); i < n; ++i)a = circles[i], a.x -= c.x, a.y -= c.y;
return c.r;
}
function required(f) {
if ("function" != typeof f) throw Error();
return f;
}
function constantZero() {
return 0;
}
function constant$9(x) {
return function() {
return x;
};
}
function defaultRadius$1(d) {
return Math.sqrt(d.value);
}
function radiusLeaf(radius) {
return function(node) {
node.children || (node.r = Math.max(0, +radius(node) || 0));
};
}
function packChildren(padding, k) {
return function(node) {
if (children = node.children) {
var children, i, e, n = children.length, r = padding(node) * k || 0;
if (r) for(i = 0; i < n; ++i)children[i].r += r;
if (e = packEnclose(children), r) for(i = 0; i < n; ++i)children[i].r -= r;
node.r = e + r;
}
};
}
function translateChild(k) {
return function(node) {
var parent = node.parent;
node.r *= k, parent && (node.x = parent.x + k * node.x, node.y = parent.y + k * node.y);
};
}
function roundNode(node) {
node.x0 = Math.round(node.x0), node.y0 = Math.round(node.y0), node.x1 = Math.round(node.x1), node.y1 = Math.round(node.y1);
}
function treemapDice(parent, x0, y0, x1, y1) {
for(var node, nodes = parent.children, i = -1, n = nodes.length, k = parent.value && (x1 - x0) / parent.value; ++i < n;)(node = nodes[i]).y0 = y0, node.y1 = y1, node.x0 = x0, node.x1 = x0 += node.value * k;
}
equalEarthRaw.invert = function(x, y) {
for(var delta, fy, l = y, l2 = l * l, l6 = l2 * l2 * l2, i = 0; i < 12 && (fy = l * (1.340264 + -0.081106 * l2 + l6 * (0.000893 + 0.003796 * l2)) - y, l -= delta = fy / (1.340264 + -0.24331799999999998 * l2 + l6 * (0.0062510000000000005 + 0.034164 * l2)), l6 = (l2 = l * l) * l2 * l2, !(1e-12 > abs$2(delta))); ++i);
return [
M * x * (1.340264 + -0.24331799999999998 * l2 + l6 * (0.0062510000000000005 + 0.034164 * l2)) / cos$1(l),
asin(sin$1(l) / M)
];
}, gnomonicRaw.invert = azimuthalInvert(atan), naturalEarth1Raw.invert = function(x, y) {
var delta, phi = y, i = 25;
do {
var phi2 = phi * phi, phi4 = phi2 * phi2;
phi -= delta = (phi * (1.007226 + phi2 * (0.015085 + phi4 * (-0.044475 + 0.028874 * phi2 - 0.005916 * phi4))) - y) / (1.007226 + phi2 * (0.045255 + phi4 * (-0.311325 + 0.259866 * phi2 - 0.005916 * 11 * phi4)));
}while (abs$2(delta) > 1e-6 && --i > 0)
return [
x / (0.8707 + (phi2 = phi * phi) * (-0.131979 + phi2 * (-0.013791 + phi2 * phi2 * phi2 * (0.003971 - 0.001529 * phi2)))),
phi
];
}, orthographicRaw.invert = azimuthalInvert(asin), stereographicRaw.invert = azimuthalInvert(function(z) {
return 2 * atan(z);
}), transverseMercatorRaw.invert = function(x, y) {
return [
-y,
2 * atan(exp(x)) - halfPi$2
];
}, Node.prototype = hierarchy.prototype = {
constructor: Node,
count: function() {
return this.eachAfter(count$1);
},
each: function(callback, that) {
let index = -1;
for (const node of this)callback.call(that, node, ++index, this);
return this;
},
eachAfter: function(callback, that) {
for(var children, i, n, node = this, nodes = [
node
], next = [], index = -1; node = nodes.pop();)if (next.push(node), children = node.children) for(i = 0, n = children.length; i < n; ++i)nodes.push(children[i]);
for(; node = next.pop();)callback.call(that, node, ++index, this);
return this;
},
eachBefore: function(callback, that) {
for(var children, i, node = this, nodes = [
node
], index = -1; node = nodes.pop();)if (callback.call(that, node, ++index, this), children = node.children) for(i = children.length - 1; i >= 0; --i)nodes.push(children[i]);
return this;
},
find: function(callback, that) {
let index = -1;
for (const node of this)if (callback.call(that, node, ++index, this)) return node;
},
sum: function(value) {
return this.eachAfter(function(node) {
for(var sum = +value(node.data) || 0, children = node.children, i = children && children.length; --i >= 0;)sum += children[i].value;
node.value = sum;
});
},
sort: function(compare) {
return this.eachBefore(function(node) {
node.children && node.children.sort(compare);
});
},
path: function(end) {
for(var start = this, ancestor = function(a, b) {
if (a === b) return a;
var aNodes = a.ancestors(), bNodes = b.ancestors(), c = null;
for(a = aNodes.pop(), b = bNodes.pop(); a === b;)c = a, a = aNodes.pop(), b = bNodes.pop();
return c;
}(start, end), nodes = [
start
]; start !== ancestor;)nodes.push(start = start.parent);
for(var k = nodes.length; end !== ancestor;)nodes.splice(k, 0, end), end = end.parent;
return nodes;
},
ancestors: function() {
for(var node = this, nodes = [
node
]; node = node.parent;)nodes.push(node);
return nodes;
},
descendants: function() {
return Array.from(this);
},
leaves: function() {
var leaves = [];
return this.eachBefore(function(node) {
node.children || leaves.push(node);
}), leaves;
},
links: function() {
var root = this, links = [];
return root.each(function(node) {
node !== root && links.push({
source: node.parent,
target: node
});
}), links;
},
copy: function() {
return hierarchy(this).eachBefore(copyData);
},
[Symbol.iterator]: function*() {
var current, children, i, n, node = this, next = [
node
];
do for(current = next.reverse(), next = []; node = current.pop();)if (yield node, children = node.children) for(i = 0, n = children.length; i < n; ++i)next.push(children[i]);
while (next.length)
}
};
var preroot = {
depth: -1
}, ambiguous = {};
function defaultId(d) {
return d.id;
}
function defaultParentId(d) {
return d.parentId;
}
function defaultSeparation$1(a, b) {
return a.parent === b.parent ? 1 : 2;
}
// function radialSeparation(a, b) {
// return (a.parent === b.parent ? 1 : 2) / a.depth;
// }
// This function is used to traverse the left contour of a subtree (or
// subforest). It returns the successor of v on this contour. This successor is
// either given by the leftmost child of v or by the thread of v. The function
// returns null if and only if v is on the highest level of its subtree.
function nextLeft(v) {
var children = v.children;
return children ? children[0] : v.t;
}
// This function works analogously to nextLeft.
function nextRight(v) {
var children = v.children;
return children ? children[children.length - 1] : v.t;
}
function TreeNode(node, i) {
this._ = node, this.parent = null, this.children = null, this.A = null, this.a = this, this.z = 0, this.m = 0, this.c = 0, this.s = 0, this.t = null, this.i = i;
}
function treemapSlice(parent, x0, y0, x1, y1) {
for(var node, nodes = parent.children, i = -1, n = nodes.length, k = parent.value && (y1 - y0) / parent.value; ++i < n;)(node = nodes[i]).x0 = x0, node.x1 = x1, node.y0 = y0, node.y1 = y0 += node.value * k;
}
TreeNode.prototype = Object.create(Node.prototype);
var phi = (1 + Math.sqrt(5)) / 2;
function squarifyRatio(ratio, parent, x0, y0, x1, y1) {
for(var row, nodeValue, dx, dy, sumValue, minValue, maxValue, newRatio, minRatio, alpha, beta, rows = [], nodes = parent.children, i0 = 0, i1 = 0, n = nodes.length, value = parent.value; i0 < n;){
dx = x1 - x0, dy = y1 - y0;
// Find the next non-empty node.
do sumValue = nodes[i1++].value;
while (!sumValue && i1 < n)
// Keep adding nodes while the aspect ratio maintains or improves.
for(minValue = maxValue = sumValue, minRatio = Math.max(maxValue / (beta = sumValue * sumValue * (alpha = Math.max(dy / dx, dx / dy) / (value * ratio))), beta / minValue); i1 < n; ++i1){
if (sumValue += nodeValue = nodes[i1].value, nodeValue < minValue && (minValue = nodeValue), nodeValue > maxValue && (maxValue = nodeValue), (newRatio = Math.max(maxValue / (beta = sumValue * sumValue * alpha), beta / minValue)) > minRatio) {
sumValue -= nodeValue;
break;
}
minRatio = newRatio;
}
// Position and record the row orientation.
rows.push(row = {
value: sumValue,
dice: dx < dy,
children: nodes.slice(i0, i1)
}), row.dice ? treemapDice(row, x0, y0, x1, value ? y0 += dy * sumValue / value : y1) : treemapSlice(row, x0, y0, value ? x0 += dx * sumValue / value : x1, y1), value -= sumValue, i0 = i1;
}
return rows;
}
var squarify = function custom(ratio) {
function squarify(parent, x0, y0, x1, y1) {
squarifyRatio(ratio, parent, x0, y0, x1, y1);
}
return squarify.ratio = function(x) {
return custom((x *= 1) > 1 ? x : 1);
}, squarify;
}(phi), resquarify = function custom(ratio) {
function resquarify(parent, x0, y0, x1, y1) {
if ((rows = parent._squarify) && rows.ratio === ratio) for(var rows, row, nodes, i, n, j = -1, m = rows.length, value = parent.value; ++j < m;){
for(nodes = (row = rows[j]).children, i = row.value = 0, n = nodes.length; i < n; ++i)row.value += nodes[i].value;
row.dice ? treemapDice(row, x0, y0, x1, value ? y0 += (y1 - y0) * row.value / value : y1) : treemapSlice(row, x0, y0, value ? x0 += (x1 - x0) * row.value / value : x1, y1), value -= row.value;
}
else parent._squarify = rows = squarifyRatio(ratio, parent, x0, y0, x1, y1), rows.ratio = ratio;
}
return resquarify.ratio = function(x) {
return custom((x *= 1) > 1 ? x : 1);
}, resquarify;
}(phi);
function lexicographicOrder(a, b) {
return a[0] - b[0] || a[1] - b[1];
}
// Computes the upper convex hull per the monotone chain algorithm.
// Assumes points.length >= 3, is sorted by x, unique in y.
// Returns an array of indices into points in left-to-right order.
function computeUpperHullIndexes(points) {
const n = points.length, indexes = [
0,
1
];
let size = 2, i;
for(i = 2; i < n; ++i){
for(var a, b, c; size > 1 && 0 >= (a = points[indexes[size - 2]], b = points[indexes[size - 1]], c = points[i], (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]));)--size;
indexes[size++] = i;
}
return indexes.slice(0, size); // remove popped points
}
var defaultSource$1 = Math.random, uniform = function sourceRandomUniform(source) {
function randomUniform(min, max) {
return min = null == min ? 0 : +min, max = null == max ? 1 : +max, 1 == arguments.length ? (max = min, min = 0) : max -= min, function() {
return source() * max + min;
};
}
return randomUniform.source = sourceRandomUniform, randomUniform;
}(defaultSource$1), int = function sourceRandomInt(source) {
function randomInt(min, max) {
return arguments.length < 2 && (max = min, min = 0), max = Math.floor(max) - (min = Math.floor(min)), function() {
return Math.floor(source() * max + min);
};
}
return randomInt.source = sourceRandomInt, randomInt;
}(defaultSource$1), normal = function sourceRandomNormal(source) {
function randomNormal(mu, sigma) {
var x, r;
return mu = null == mu ? 0 : +mu, sigma = null == sigma ? 1 : +sigma, function() {
var y;
// If available, use the second previously-generated uniform random.
if (null != x) y = x, x = null;
else do x = 2 * source() - 1, y = 2 * source() - 1, r = x * x + y * y;
while (!r || r > 1)
return mu + sigma * y * Math.sqrt(-2 * Math.log(r) / r);
};
}
return randomNormal.source = sourceRandomNormal, randomNormal;
}(defaultSource$1), logNormal = function sourceRandomLogNormal(source) {
var N = normal.source(source);
function randomLogNormal() {
var randomNormal = N.apply(this, arguments);
return function() {
return Math.exp(randomNormal());
};
}
return randomLogNormal.source = sourceRandomLogNormal, randomLogNormal;
}(defaultSource$1), irwinHall = function sourceRandomIrwinHall(source) {
function randomIrwinHall(n) {
return (n *= 1) <= 0 ? ()=>0 : function() {
for(var sum = 0, i = n; i > 1; --i)sum += source();
return sum + i * source();
};
}
return randomIrwinHall.source = sourceRandomIrwinHall, randomIrwinHall;
}(defaultSource$1), bates = function sourceRandomBates(source) {
var I = irwinHall.source(source);
function randomBates(n) {
// use limiting distribution at n === 0
if (0 == (n *= 1)) return source;
var randomIrwinHall = I(n);
return function() {
return randomIrwinHall() / n;
};
}
return randomBates.source = sourceRandomBates, randomBates;
}(defaultSource$1), exponential$1 = function sourceRandomExponential(source) {
function randomExponential(lambda) {
return function() {
return -Math.log1p(-source()) / lambda;
};
}
return randomExponential.source = sourceRandomExponential, randomExponential;
}(defaultSource$1), pareto = function sourceRandomPareto(source) {
function randomPareto(alpha) {
if ((alpha *= 1) < 0) throw RangeError("invalid alpha");
return alpha = -(1 / alpha), function() {
return Math.pow(1 - source(), alpha);
};
}
return randomPareto.source = sourceRandomPareto, randomPareto;
}(defaultSource$1), bernoulli = function sourceRandomBernoulli(source) {
function randomBernoulli(p) {
if ((p *= 1) < 0 || p > 1) throw RangeError("invalid p");
return function() {
return Math.floor(source() + p);
};
}
return randomBernoulli.source = sourceRandomBernoulli, randomBernoulli;
}(defaultSource$1), geometric = function sourceRandomGeometric(source) {
function randomGeometric(p) {
if ((p *= 1) < 0 || p > 1) throw RangeError("invalid p");
return 0 === p ? ()=>1 / 0 : 1 === p ? ()=>1 : (p = Math.log1p(-p), function() {
return 1 + Math.floor(Math.log1p(-source()) / p);
});
}
return randomGeometric.source = sourceRandomGeometric, randomGeometric;
}(defaultSource$1), gamma$1 = function sourceRandomGamma(source) {
var randomNormal = normal.source(source)();
function randomGamma(k, theta) {
if ((k *= 1) < 0) throw RangeError("invalid k");
// degenerate distribution if k === 0
if (0 === k) return ()=>0;
// exponential distribution if k === 1
if (theta = null == theta ? 1 : +theta, 1 === k) return ()=>-Math.log1p(-source()) * theta;
var d = (k < 1 ? k + 1 : k) - 1 / 3, c = 1 / (3 * Math.sqrt(d)), multiplier = k < 1 ? ()=>Math.pow(source(), 1 / k) : ()=>1;
return function() {
do {
do var x = randomNormal(), v = 1 + c * x;
while (v <= 0)
v *= v * v;
var u = 1 - source();
}while (u >= 1 - 0.0331 * x * x * x * x && Math.log(u) >= 0.5 * x * x + d * (1 - v + Math.log(v)))
return d * v * multiplier() * theta;
};
}
return randomGamma.source = sourceRandomGamma, randomGamma;
}(defaultSource$1), beta = function sourceRandomBeta(source) {
var G = gamma$1.source(source);
function randomBeta(alpha, beta) {
var X = G(alpha), Y = G(beta);
return function() {
var x = X();
return 0 === x ? 0 : x / (x + Y());
};
}
return randomBeta.source = sourceRandomBeta, randomBeta;
}(defaultSource$1), binomial = function sourceRandomBinomial(source) {
var G = geometric.source(source), B = beta.source(source);
function randomBinomial(n, p) {
return (n *= 1, (p *= 1) >= 1) ? ()=>n : p <= 0 ? ()=>0 : function() {
for(var acc = 0, nn = n, pp = p; nn * pp > 16 && nn * (1 - pp) > 16;){
var i = Math.floor((nn + 1) * pp), y = B(i, nn - i + 1)();
y <= pp ? (acc += i, nn -= i, pp = (pp - y) / (1 - y)) : (nn = i - 1, pp /= y);
}
for(var sign = pp < 0.5, g = G(sign ? pp : 1 - pp), s = g(), k = 0; s <= nn; ++k)s += g();
return acc + (sign ? k : nn - k);
};
}
return randomBinomial.source = sourceRandomBinomial, randomBinomial;
}(defaultSource$1), weibull = function sourceRandomWeibull(source) {
function randomWeibull(k, a, b) {
var outerFunc;
return 0 == (k *= 1) ? outerFunc = (x)=>-Math.log(x) : (k = 1 / k, outerFunc = (x)=>Math.pow(x, k)), a = null == a ? 0 : +a, b = null == b ? 1 : +b, function() {
return a + b * outerFunc(-Math.log1p(-source()));
};
}
return randomWeibull.source = sourceRandomWeibull, randomWeibull;
}(defaultSource$1), cauchy = function sourceRandomCauchy(source) {
function randomCauchy(a, b) {
return a = null == a ? 0 : +a, b = null == b ? 1 : +b, function() {
return a + b * Math.tan(Math.PI * source());
};
}
return randomCauchy.source = sourceRandomCauchy, randomCauchy;
}(defaultSource$1), logistic = function sourceRandomLogistic(source) {
function randomLogistic(a, b) {
return a = null == a ? 0 : +a, b = null == b ? 1 : +b, function() {
var u = source();
return a + b * Math.log(u / (1 - u));
};
}
return randomLogistic.source = sourceRandomLogistic, randomLogistic;
}(defaultSource$1), poisson = function sourceRandomPoisson(source) {
var G = gamma$1.source(source), B = binomial.source(source);
function randomPoisson(lambda) {
return function() {
for(var acc = 0, l = lambda; l > 16;){
var n = Math.floor(0.875 * l), t = G(n)();
if (t > l) return acc + B(n - 1, l / t)();
acc += n, l -= t;
}
for(var s = -Math.log1p(-source()), k = 0; s <= l; ++k)s -= Math.log1p(-source());
return acc + k;
};
}
return randomPoisson.source = sourceRandomPoisson, randomPoisson;
}(defaultSource$1);
const eps = 1 / 0x100000000;
function initRange(domain, range) {
switch(arguments.length){
case 0:
break;
case 1:
this.range(domain);
break;
default:
this.range(range).domain(domain);
}
return this;
}
function initInterpolator(domain, interpolator) {
switch(arguments.length){
case 0:
break;
case 1:
"function" == typeof domain ? this.interpolator(domain) : this.range(domain);
break;
default:
this.domain(domain), "function" == typeof interpolator ? this.interpolator(interpolator) : this.range(interpolator);
}
return this;
}
const implicit = Symbol("implicit");
function ordinal() {
var index = new Map(), domain = [], range = [], unknown = implicit;
function scale(d) {
var key = d + "", i = index.get(key);
if (!i) {
if (unknown !== implicit) return unknown;
index.set(key, i = domain.push(d));
}
return range[(i - 1) % range.length];
}
return scale.domain = function(_) {
if (!arguments.length) return domain.slice();
for (const value of (domain = [], index = new Map(), _)){
const key = value + "";
index.has(key) || index.set(key, domain.push(value));
}
return scale;
}, scale.range = function(_) {
return arguments.length ? (range = Array.from(_), scale) : range.slice();
}, scale.unknown = function(_) {
return arguments.length ? (unknown = _, scale) : unknown;
}, scale.copy = function() {
return ordinal(domain, range).unknown(unknown);
}, initRange.apply(scale, arguments), scale;
}
function band() {
var step, bandwidth, scale = ordinal().unknown(void 0), domain = scale.domain, ordinalRange = scale.range, r0 = 0, r1 = 1, round = !1, paddingInner = 0, paddingOuter = 0, align = 0.5;
function rescale() {
var n = domain().length, reverse = r1 < r0, start = reverse ? r1 : r0, stop = reverse ? r0 : r1;
step = (stop - start) / Math.max(1, n - paddingInner + 2 * paddingOuter), round && (step = Math.floor(step)), start += (stop - start - step * (n - paddingInner)) * align, bandwidth = step * (1 - paddingInner), round && (start = Math.round(start), bandwidth = Math.round(bandwidth));
var values = sequence(n).map(function(i) {
return start + step * i;
});
return ordinalRange(reverse ? values.reverse() : values);
}
return delete scale.unknown, scale.domain = function(_) {
return arguments.length ? (domain(_), rescale()) : domain();
}, scale.range = function(_) {
return arguments.length ? ([r0, r1] = _, r0 *= 1, r1 *= 1, rescale()) : [
r0,
r1
];
}, scale.rangeRound = function(_) {
return [r0, r1] = _, r0 *= 1, r1 *= 1, round = !0, rescale();
}, scale.bandwidth = function() {
return bandwidth;
}, scale.step = function() {
return step;
}, scale.round = function(_) {
return arguments.length ? (round = !!_, rescale()) : round;
}, scale.padding = function(_) {
return arguments.length ? (paddingInner = Math.min(1, paddingOuter = +_), rescale()) : paddingInner;
}, scale.paddingInner = function(_) {
return arguments.length ? (paddingInner = Math.min(1, _), rescale()) : paddingInner;
}, scale.paddingOuter = function(_) {
return arguments.length ? (paddingOuter = +_, rescale()) : paddingOuter;
}, scale.align = function(_) {
return arguments.length ? (align = Math.max(0, Math.min(1, _)), rescale()) : align;
}, scale.copy = function() {
return band(domain(), [
r0,
r1
]).round(round).paddingInner(paddingInner).paddingOuter(paddingOuter).align(align);
}, initRange.apply(rescale(), arguments);
}
function number$2(x) {
return +x;
}
var unit = [
0,
1
];
function identity$6(x) {
return x;
}
function normalize(a, b) {
var x;
return (b -= a *= 1) ? function(x) {
return (x - a) / b;
} : (x = isNaN(b) ? NaN : 0.5, function() {
return x;
});
}
// normalize(a, b)(x) takes a domain value x in [a,b] and returns the corresponding parameter t in [0,1].
// interpolate(a, b)(t) takes a parameter t in [0,1] and returns the corresponding range value x in [a,b].
function bimap(domain, range, interpolate) {
var d0 = domain[0], d1 = domain[1], r0 = range[0], r1 = range[1];
return d1 < d0 ? (d0 = normalize(d1, d0), r0 = interpolate(r1, r0)) : (d0 = normalize(d0, d1), r0 = interpolate(r0, r1)), function(x) {
return r0(d0(x));
};
}
function polymap(domain, range, interpolate) {
var j = Math.min(domain.length, range.length) - 1, d = Array(j), r = Array(j), i = -1;
for(domain[j] < domain[0] && (domain = domain.slice().reverse(), range = range.slice().reverse()); ++i < j;)d[i] = normalize(domain[i], domain[i + 1]), r[i] = interpolate(range[i], range[i + 1]);
return function(x) {
var i = bisectRight(domain, x, 1, j) - 1;
return r[i](d[i](x));
};
}
function copy(source, target) {
return target.domain(source.domain()).range(source.range()).interpolate(source.interpolate()).clamp(source.clamp()).unknown(source.unknown());
}
function transformer$1() {
var transform, untransform, unknown, piecewise, output, input, domain = unit, range = unit, interpolate$1 = interpolate, clamp = identity$6;
function rescale() {
var a, b, t, n = Math.min(domain.length, range.length);
return clamp !== identity$6 && (a = domain[0], b = domain[n - 1], a > b && (t = a, a = b, b = t), clamp = function(x) {
return Math.max(a, Math.min(b, x));
}), piecewise = n > 2 ? polymap : bimap, output = input = null, scale;
}
function scale(x) {
return isNaN(x *= 1) ? unknown : (output || (output = piecewise(domain.map(transform), range, interpolate$1)))(transform(clamp(x)));
}
return scale.invert = function(y) {
return clamp(untransform((input || (input = piecewise(range, domain.map(transform), interpolateNumber)))(y)));
}, scale.domain = function(_) {
return arguments.length ? (domain = Array.from(_, number$2), rescale()) : domain.slice();
}, scale.range = function(_) {
return arguments.length ? (range = Array.from(_), rescale()) : range.slice();
}, scale.rangeRound = function(_) {
return range = Array.from(_), interpolate$1 = interpolateRound, rescale();
}, scale.clamp = function(_) {
return arguments.length ? (clamp = !!_ || identity$6, rescale()) : clamp !== identity$6;
}, scale.interpolate = function(_) {
return arguments.length ? (interpolate$1 = _, rescale()) : interpolate$1;
}, scale.unknown = function(_) {
return arguments.length ? (unknown = _, scale) : unknown;
}, function(t, u) {
return transform = t, untransform = u, rescale();
};
}
function continuous() {
return transformer$1()(identity$6, identity$6);
}
function tickFormat(start, stop, count, specifier) {
var precision, step = tickStep(start, stop, count);
switch((specifier = formatSpecifier(null == specifier ? ",f" : specifier)).type){
case "s":
var value = Math.max(Math.abs(start), Math.abs(stop));
return null != specifier.precision || isNaN(precision = precisionPrefix(step, value)) || (specifier.precision = precision), exports1.formatPrefix(specifier, value);
case "":
case "e":
case "g":
case "p":
case "r":
null != specifier.precision || isNaN(precision = precisionRound(step, Math.max(Math.abs(start), Math.abs(stop)))) || (specifier.precision = precision - ("e" === specifier.type));
break;
case "f":
case "%":
null != specifier.precision || isNaN(precision = precisionFixed(step)) || (specifier.precision = precision - ("%" === specifier.type) * 2);
}
return exports1.format(specifier);
}
function linearish(scale) {
var domain = scale.domain;
return scale.ticks = function(count) {
var d = domain();
return ticks(d[0], d[d.length - 1], null == count ? 10 : count);
}, scale.tickFormat = function(count, specifier) {
var d = domain();
return tickFormat(d[0], d[d.length - 1], null == count ? 10 : count, specifier);
}, scale.nice = function(count) {
null == count && (count = 10);
var prestep, step, d = domain(), i0 = 0, i1 = d.length - 1, start = d[i0], stop = d[i1], maxIter = 10;
for(stop < start && (step = start, start = stop, stop = step, step = i0, i0 = i1, i1 = step); maxIter-- > 0;){
if ((step = tickIncrement(start, stop, count)) === prestep) return d[i0] = start, d[i1] = stop, domain(d);
if (step > 0) start = Math.floor(start / step) * step, stop = Math.ceil(stop / step) * step;
else if (step < 0) start = Math.ceil(start * step) / step, stop = Math.floor(stop * step) / step;
else break;
prestep = step;
}
return scale;
}, scale;
}
function nice$1(domain, interval) {
domain = domain.slice();
var t, i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1];
return x1 < x0 && (t = i0, i0 = i1, i1 = t, t = x0, x0 = x1, x1 = t), domain[i0] = interval.floor(x0), domain[i1] = interval.ceil(x1), domain;
}
function transformLog(x) {
return Math.log(x);
}
function transformExp(x) {
return Math.exp(x);
}
function transformLogn(x) {
return -Math.log(-x);
}
function transformExpn(x) {
return -Math.exp(-x);
}
function pow10(x) {
return isFinite(x) ? +("1e" + x) : x < 0 ? 0 : x;
}
function reflect(f) {
return function(x) {
return -f(-x);
};
}
function loggish(transform) {
var logs, pows, scale = transform(transformLog, transformExp), domain = scale.domain, base = 10;
function rescale() {
var base1, base2;
return logs = (base1 = base) === Math.E ? Math.log : 10 === base1 && Math.log10 || 2 === base1 && Math.log2 || (base1 = Math.log(base1), function(x) {
return Math.log(x) / base1;
}), pows = 10 === (base2 = base) ? pow10 : base2 === Math.E ? Math.exp : function(x) {
return Math.pow(base2, x);
}, domain()[0] < 0 ? (logs = reflect(logs), pows = reflect(pows), transform(transformLogn, transformExpn)) : transform(transformLog, transformExp), scale;
}
return scale.base = function(_) {
return arguments.length ? (base = +_, rescale()) : base;
}, scale.domain = function(_) {
return arguments.length ? (domain(_), rescale()) : domain();
}, scale.ticks = function(count) {
var r, d = domain(), u = d[0], v = d[d.length - 1];
(r = v < u) && (i = u, u = v, v = i);
var p, k, t, i = logs(u), j = logs(v), n = null == count ? 10 : +count, z = [];
if (!(base % 1) && j - i < n) {
if (i = Math.floor(i), j = Math.ceil(j), u > 0) {
for(; i <= j; ++i)for(k = 1, p = pows(i); k < base; ++k)if (!((t = p * k) < u)) {
if (t > v) break;
z.push(t);
}
} else for(; i <= j; ++i)for(k = base - 1, p = pows(i); k >= 1; --k)if (!((t = p * k) < u)) {
if (t > v) break;
z.push(t);
}
2 * z.length < n && (z = ticks(u, v, n));
} else z = ticks(i, j, Math.min(j - i, n)).map(pows);
return r ? z.reverse() : z;
}, scale.tickFormat = function(count, specifier) {
if (null == specifier && (specifier = 10 === base ? ".0e" : ","), "function" != typeof specifier && (specifier = exports1.format(specifier)), count === 1 / 0) return specifier;
null == count && (count = 10);
var k = Math.max(1, base * count / scale.ticks().length); // TODO fast estimate?
return function(d) {
var i = d / pows(Math.round(logs(d)));
return i * base < base - 0.5 && (i *= base), i <= k ? specifier(d) : "";
};
}, scale.nice = function() {
return domain(nice$1(domain(), {
floor: function(x) {
return pows(Math.floor(logs(x)));
},
ceil: function(x) {
return pows(Math.ceil(logs(x)));
}
}));
}, scale;
}
function transformSymlog(c) {
return function(x) {
return Math.sign(x) * Math.log1p(Math.abs(x / c));
};
}
function transformSymexp(c) {
return function(x) {
return Math.sign(x) * Math.expm1(Math.abs(x)) * c;
};
}
function symlogish(transform) {
var c = 1, scale = transform(transformSymlog(1), transformSymexp(c));
return scale.constant = function(_) {
return arguments.length ? transform(transformSymlog(c = +_), transformSymexp(c)) : c;
}, linearish(scale);
}
function transformPow(exponent) {
return function(x) {
return x < 0 ? -Math.pow(-x, exponent) : Math.pow(x, exponent);
};
}
function transformSqrt(x) {
return x < 0 ? -Math.sqrt(-x) : Math.sqrt(x);
}
function transformSquare(x) {
return x < 0 ? -x * x : x * x;
}
function powish(transform) {
var scale = transform(identity$6, identity$6), exponent = 1;
return scale.exponent = function(_) {
return arguments.length ? 1 == (exponent = +_) ? transform(identity$6, identity$6) : 0.5 === exponent ? transform(transformSqrt, transformSquare) : transform(transformPow(exponent), transformPow(1 / exponent)) : exponent;
}, linearish(scale);
}
function pow$2() {
var scale = powish(transformer$1());
return scale.copy = function() {
return copy(scale, pow$2()).exponent(scale.exponent());
}, initRange.apply(scale, arguments), scale;
}
function square(x) {
return Math.sign(x) * x * x;
}
var t0$1 = new Date, t1$1 = new Date;
function newInterval(floori, offseti, count, field) {
function interval(date) {
return floori(date = 0 == arguments.length ? new Date : new Date(+date)), date;
}
return interval.floor = function(date) {
return floori(date = new Date(+date)), date;
}, interval.ceil = function(date) {
return floori(date = new Date(date - 1)), offseti(date, 1), floori(date), date;
}, interval.round = function(date) {
var d0 = interval(date), d1 = interval.ceil(date);
return date - d0 < d1 - date ? d0 : d1;
}, interval.offset = function(date, step) {
return offseti(date = new Date(+date), null == step ? 1 : Math.floor(step)), date;
}, interval.range = function(start, stop, step) {
var previous, range = [];
if (start = interval.ceil(start), step = null == step ? 1 : Math.floor(step), !(start < stop) || !(step > 0)) return range; // also handles Invalid Date
do range.push(previous = new Date(+start)), offseti(start, step), floori(start);
while (previous < start && start < stop)
return range;
}, interval.filter = function(test) {
return newInterval(function(date) {
if (date >= date) for(; floori(date), !test(date);)date.setTime(date - 1);
}, function(date, step) {
if (date >= date) {
if (step < 0) for(; ++step <= 0;)for(; offseti(date, -1), !test(date););
// eslint-disable-line no-empty
else for(; --step >= 0;)for(; offseti(date, 1), !test(date););
// eslint-disable-line no-empty
}
});
}, count && (interval.count = function(start, end) {
return t0$1.setTime(+start), t1$1.setTime(+end), floori(t0$1), floori(t1$1), Math.floor(count(t0$1, t1$1));
}, interval.every = function(step) {
return isFinite(step = Math.floor(step)) && step > 0 ? step > 1 ? interval.filter(field ? function(d) {
return field(d) % step == 0;
} : function(d) {
return interval.count(0, d) % step == 0;
}) : interval : null;
}), interval;
}
var millisecond = newInterval(function() {
// noop
}, function(date, step) {
date.setTime(+date + step);
}, function(start, end) {
return end - start;
});
// An optimized implementation for this simple case.
millisecond.every = function(k) {
return isFinite(k = Math.floor(k)) && k > 0 ? k > 1 ? newInterval(function(date) {
date.setTime(Math.floor(date / k) * k);
}, function(date, step) {
date.setTime(+date + step * k);
}, function(start, end) {
return (end - start) / k;
}) : millisecond : null;
};
var milliseconds = millisecond.range, second = newInterval(function(date) {
date.setTime(date - date.getMilliseconds());
}, function(date, step) {
date.setTime(+date + 1e3 * step);
}, function(start, end) {
return (end - start) / 1e3;
}, function(date) {
return date.getUTCSeconds();
}), seconds = second.range, minute = newInterval(function(date) {
date.setTime(date - date.getMilliseconds() - 1e3 * date.getSeconds());
}, function(date, step) {
date.setTime(+date + 6e4 * step);
}, function(start, end) {
return (end - start) / 6e4;
}, function(date) {
return date.getMinutes();
}), minutes = minute.range, hour = newInterval(function(date) {
date.setTime(date - date.getMilliseconds() - 1e3 * date.getSeconds() - 6e4 * date.getMinutes());
}, function(date, step) {
date.setTime(+date + 36e5 * step);
}, function(start, end) {
return (end - start) / 36e5;
}, function(date) {
return date.getHours();
}), hours = hour.range, day = newInterval((date)=>date.setHours(0, 0, 0, 0), (date, step)=>date.setDate(date.getDate() + step), (start, end)=>(end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * 6e4) / 864e5, (date)=>date.getDate() - 1), days = day.range;
function weekday(i) {
return newInterval(function(date) {
date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7), date.setHours(0, 0, 0, 0);
}, function(date, step) {
date.setDate(date.getDate() + 7 * step);
}, function(start, end) {
return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * 6e4) / 6048e5;
});
}
var sunday = weekday(0), monday = weekday(1), tuesday = weekday(2), wednesday = weekday(3), thursday = weekday(4), friday = weekday(5), saturday = weekday(6), sundays = sunday.range, mondays = monday.range, tuesdays = tuesday.range, wednesdays = wednesday.range, thursdays = thursday.range, fridays = friday.range, saturdays = saturday.range, month = newInterval(function(date) {
date.setDate(1), date.setHours(0, 0, 0, 0);
}, function(date, step) {
date.setMonth(date.getMonth() + step);
}, function(start, end) {
return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12;
}, function(date) {
return date.getMonth();
}), months = month.range, year = newInterval(function(date) {
date.setMonth(0, 1), date.setHours(0, 0, 0, 0);
}, function(date, step) {
date.setFullYear(date.getFullYear() + step);
}, function(start, end) {
return end.getFullYear() - start.getFullYear();
}, function(date) {
return date.getFullYear();
});
// An optimized implementation for this simple case.
year.every = function(k) {
return isFinite(k = Math.floor(k)) && k > 0 ? newInterval(function(date) {
date.setFullYear(Math.floor(date.getFullYear() / k) * k), date.setMonth(0, 1), date.setHours(0, 0, 0, 0);
}, function(date, step) {
date.setFullYear(date.getFullYear() + step * k);
}) : null;
};
var years = year.range, utcMinute = newInterval(function(date) {
date.setUTCSeconds(0, 0);
}, function(date, step) {
date.setTime(+date + 6e4 * step);
}, function(start, end) {
return (end - start) / 6e4;
}, function(date) {
return date.getUTCMinutes();
}), utcMinutes = utcMinute.range, utcHour = newInterval(function(date) {
date.setUTCMinutes(0, 0, 0);
}, function(date, step) {
date.setTime(+date + 36e5 * step);
}, function(start, end) {
return (end - start) / 36e5;
}, function(date) {
return date.getUTCHours();
}), utcHours = utcHour.range, utcDay = newInterval(function(date) {
date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCDate(date.getUTCDate() + step);
}, function(start, end) {
return (end - start) / 864e5;
}, function(date) {
return date.getUTCDate() - 1;
}), utcDays = utcDay.range;
function utcWeekday(i) {
return newInterval(function(date) {
date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 7 - i) % 7), date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCDate(date.getUTCDate() + 7 * step);
}, function(start, end) {
return (end - start) / 6048e5;
});
}
var utcSunday = utcWeekday(0), utcMonday = utcWeekday(1), utcTuesday = utcWeekday(2), utcWednesday = utcWeekday(3), utcThursday = utcWeekday(4), utcFriday = utcWeekday(5), utcSaturday = utcWeekday(6), utcSundays = utcSunday.range, utcMondays = utcMonday.range, utcTuesdays = utcTuesday.range, utcWednesdays = utcWednesday.range, utcThursdays = utcThursday.range, utcFridays = utcFriday.range, utcSaturdays = utcSaturday.range, utcMonth = newInterval(function(date) {
date.setUTCDate(1), date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCMonth(date.getUTCMonth() + step);
}, function(start, end) {
return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12;
}, function(date) {
return date.getUTCMonth();
}), utcMonths = utcMonth.range, utcYear = newInterval(function(date) {
date.setUTCMonth(0, 1), date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCFullYear(date.getUTCFullYear() + step);
}, function(start, end) {
return end.getUTCFullYear() - start.getUTCFullYear();
}, function(date) {
return date.getUTCFullYear();
});
// An optimized implementation for this simple case.
utcYear.every = function(k) {
return isFinite(k = Math.floor(k)) && k > 0 ? newInterval(function(date) {
date.setUTCFullYear(Math.floor(date.getUTCFullYear() / k) * k), date.setUTCMonth(0, 1), date.setUTCHours(0, 0, 0, 0);
}, function(date, step) {
date.setUTCFullYear(date.getUTCFullYear() + step * k);
}) : null;
};
var utcYears = utcYear.range;
function localDate(d) {
if (0 <= d.y && d.y < 100) {
var date = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);
return date.setFullYear(d.y), date;
}
return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L);
}
function utcDate(d) {
if (0 <= d.y && d.y < 100) {
var date = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));
return date.setUTCFullYear(d.y), date;
}
return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));
}
function newDate(y, m, d) {
return {
y: y,
m: m,
d: d,
H: 0,
M: 0,
S: 0,
L: 0
};
}
function formatLocale$1(locale) {
var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_weekdays = locale.days, locale_shortWeekdays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths, periodRe = formatRe(locale_periods), periodLookup = formatLookup(locale_periods), weekdayRe = formatRe(locale_weekdays), weekdayLookup = formatLookup(locale_weekdays), shortWeekdayRe = formatRe(locale_shortWeekdays), shortWeekdayLookup = formatLookup(locale_shortWeekdays), monthRe = formatRe(locale_months), monthLookup = formatLookup(locale_months), shortMonthRe = formatRe(locale_shortMonths), shortMonthLookup = formatLookup(locale_shortMonths), formats = {
a: function(d) {
return locale_shortWeekdays[d.getDay()];
},
A: function(d) {
return locale_weekdays[d.getDay()];
},
b: function(d) {
return locale_shortMonths[d.getMonth()];
},
B: function(d) {
return locale_months[d.getMonth()];
},
c: null,
d: formatDayOfMonth,
e: formatDayOfMonth,
f: formatMicroseconds,
g: formatYearISO,
G: formatFullYearISO,
H: formatHour24,
I: formatHour12,
j: formatDayOfYear,
L: formatMilliseconds,
m: formatMonthNumber,
M: formatMinutes,
p: function(d) {
return locale_periods[+(d.getHours() >= 12)];
},
q: function(d) {
return 1 + ~~(d.getMonth() / 3);
},
Q: formatUnixTimestamp,
s: formatUnixTimestampSeconds,
S: formatSeconds,
u: formatWeekdayNumberMonday,
U: formatWeekNumberSunday,
V: formatWeekNumberISO,
w: formatWeekdayNumberSunday,
W: formatWeekNumberMonday,
x: null,
X: null,
y: formatYear$1,
Y: formatFullYear,
Z: formatZone,
"%": formatLiteralPercent
}, utcFormats = {
a: function(d) {
return locale_shortWeekdays[d.getUTCDay()];
},
A: function(d) {
return locale_weekdays[d.getUTCDay()];
},
b: function(d) {
return locale_shortMonths[d.getUTCMonth()];
},
B: function(d) {
return locale_months[d.getUTCMonth()];
},
c: null,
d: formatUTCDayOfMonth,
e: formatUTCDayOfMonth,
f: formatUTCMicroseconds,
g: formatUTCYearISO,
G: formatUTCFullYearISO,
H: formatUTCHour24,
I: formatUTCHour12,
j: formatUTCDayOfYear,
L: formatUTCMilliseconds,
m: formatUTCMonthNumber,
M: formatUTCMinutes,
p: function(d) {
return locale_periods[+(d.getUTCHours() >= 12)];
},
q: function(d) {
return 1 + ~~(d.getUTCMonth() / 3);
},
Q: formatUnixTimestamp,
s: formatUnixTimestampSeconds,
S: formatUTCSeconds,
u: formatUTCWeekdayNumberMonday,
U: formatUTCWeekNumberSunday,
V: formatUTCWeekNumberISO,
w: formatUTCWeekdayNumberSunday,
W: formatUTCWeekNumberMonday,
x: null,
X: null,
y: formatUTCYear,
Y: formatUTCFullYear,
Z: formatUTCZone,
"%": formatLiteralPercent
}, parses = {
a: function(d, string, i) {
var n = shortWeekdayRe.exec(string.slice(i));
return n ? (d.w = shortWeekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
},
A: function(d, string, i) {
var n = weekdayRe.exec(string.slice(i));
return n ? (d.w = weekdayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
},
b: function(d, string, i) {
var n = shortMonthRe.exec(string.slice(i));
return n ? (d.m = shortMonthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
},
B: function(d, string, i) {
var n = monthRe.exec(string.slice(i));
return n ? (d.m = monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
},
c: function(d, string, i) {
return parseSpecifier(d, locale_dateTime, string, i);
},
d: parseDayOfMonth,
e: parseDayOfMonth,
f: parseMicroseconds,
g: parseYear,
G: parseFullYear,
H: parseHour24,
I: parseHour24,
j: parseDayOfYear,
L: parseMilliseconds,
m: parseMonthNumber,
M: parseMinutes,
p: function(d, string, i) {
var n = periodRe.exec(string.slice(i));
return n ? (d.p = periodLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
},
q: parseQuarter,
Q: parseUnixTimestamp,
s: parseUnixTimestampSeconds,
S: parseSeconds,
u: parseWeekdayNumberMonday,
U: parseWeekNumberSunday,
V: parseWeekNumberISO,
w: parseWeekdayNumberSunday,
W: parseWeekNumberMonday,
x: function(d, string, i) {
return parseSpecifier(d, locale_date, string, i);
},
X: function(d, string, i) {
return parseSpecifier(d, locale_time, string, i);
},
y: parseYear,
Y: parseFullYear,
Z: parseZone,
"%": parseLiteralPercent
};
function newFormat(specifier, formats) {
return function(date) {
var c, pad, format, string = [], i = -1, j = 0, n = specifier.length;
for(date instanceof Date || (date = new Date(+date)); ++i < n;)37 === specifier.charCodeAt(i) && (string.push(specifier.slice(j, i)), null != (pad = pads[c = specifier.charAt(++i)]) ? c = specifier.charAt(++i) : pad = "e" === c ? " " : "0", (format = formats[c]) && (c = format(date, pad)), string.push(c), j = i + 1);
return string.push(specifier.slice(j, i)), string.join("");
};
}
function newParse(specifier, Z) {
return function(string) {
var week, day$1, d = newDate(1900, void 0, 1);
if (parseSpecifier(d, specifier, string += "", 0) != string.length) return null;
// If a UNIX timestamp is specified, return it.
if ("Q" in d) return new Date(d.Q);
if ("s" in d) return new Date(1000 * d.s + ("L" in d ? d.L : 0));
// Convert day-of-week and week-of-year to day-of-year.
if (!Z || "Z" in d || (d.Z = 0), "p" in d && (d.H = d.H % 12 + 12 * d.p), void 0 === d.m && (d.m = "q" in d ? d.q : 0), "V" in d) {
if (d.V < 1 || d.V > 53) return null;
"w" in d || (d.w = 1), "Z" in d ? (week = (day$1 = (week = utcDate(newDate(d.y, 0, 1))).getUTCDay()) > 4 || 0 === day$1 ? utcMonday.ceil(week) : utcMonday(week), week = utcDay.offset(week, (d.V - 1) * 7), d.y = week.getUTCFullYear(), d.m = week.getUTCMonth(), d.d = week.getUTCDate() + (d.w + 6) % 7) : (week = (day$1 = (week = localDate(newDate(d.y, 0, 1))).getDay()) > 4 || 0 === day$1 ? monday.ceil(week) : monday(week), week = day.offset(week, (d.V - 1) * 7), d.y = week.getFullYear(), d.m = week.getMonth(), d.d = week.getDate() + (d.w + 6) % 7);
} else ("W" in d || "U" in d) && ("w" in d || (d.w = "u" in d ? d.u % 7 : +("W" in d)), day$1 = "Z" in d ? utcDate(newDate(d.y, 0, 1)).getUTCDay() : localDate(newDate(d.y, 0, 1)).getDay(), d.m = 0, d.d = "W" in d ? (d.w + 6) % 7 + 7 * d.W - (day$1 + 5) % 7 : d.w + 7 * d.U - (day$1 + 6) % 7);
return(// If a time zone is specified, all fields are interpreted as UTC and then
// offset according to the specified time zone.
"Z" in d ? (d.H += d.Z / 100 | 0, d.M += d.Z % 100, utcDate(d)) : localDate(d));
};
}
function parseSpecifier(d, specifier, string, j) {
for(var c, parse, i = 0, n = specifier.length, m = string.length; i < n;){
if (j >= m) return -1;
if (37 === (c = specifier.charCodeAt(i++))) {
if (!(parse = parses[(c = specifier.charAt(i++)) in pads ? specifier.charAt(i++) : c]) || (j = parse(d, string, j)) < 0) return -1;
} else if (c != string.charCodeAt(j++)) return -1;
}
return j;
}
return(// These recursive directive definitions must be deferred.
formats.x = newFormat(locale_date, formats), formats.X = newFormat(locale_time, formats), formats.c = newFormat(locale_dateTime, formats), utcFormats.x = newFormat(locale_date, utcFormats), utcFormats.X = newFormat(locale_time, utcFormats), utcFormats.c = newFormat(locale_dateTime, utcFormats), {
format: function(specifier) {
var f = newFormat(specifier += "", formats);
return f.toString = function() {
return specifier;
}, f;
},
parse: function(specifier) {
var p = newParse(specifier += "", !1);
return p.toString = function() {
return specifier;
}, p;
},
utcFormat: function(specifier) {
var f = newFormat(specifier += "", utcFormats);
return f.toString = function() {
return specifier;
}, f;
},
utcParse: function(specifier) {
var p = newParse(specifier += "", !0);
return p.toString = function() {
return specifier;
}, p;
}
});
}
var pads = {
"-": "",
_: " ",
0: "0"
}, numberRe = /^\s*\d+/, percentRe = /^%/, requoteRe = /[\\^$*+?|[\]().{}]/g;
function pad$1(value, fill, width) {
var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length;
return sign + (length < width ? Array(width - length + 1).join(fill) + string : string);
}
function requote(s) {
return s.replace(requoteRe, "\\$&");
}
function formatRe(names) {
return RegExp("^(?:" + names.map(requote).join("|") + ")", "i");
}
function formatLookup(names) {
return new Map(names.map((name, i)=>[
name.toLowerCase(),
i
]));
}
function parseWeekdayNumberSunday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 1));
return n ? (d.w = +n[0], i + n[0].length) : -1;
}
function parseWeekdayNumberMonday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 1));
return n ? (d.u = +n[0], i + n[0].length) : -1;
}
function parseWeekNumberSunday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.U = +n[0], i + n[0].length) : -1;
}
function parseWeekNumberISO(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.V = +n[0], i + n[0].length) : -1;
}
function parseWeekNumberMonday(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.W = +n[0], i + n[0].length) : -1;
}
function parseFullYear(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 4));
return n ? (d.y = +n[0], i + n[0].length) : -1;
}
function parseYear(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2000), i + n[0].length) : -1;
}
function parseZone(d, string, i) {
var n = /^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(string.slice(i, i + 6));
return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || "00")), i + n[0].length) : -1;
}
function parseQuarter(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 1));
return n ? (d.q = 3 * n[0] - 3, i + n[0].length) : -1;
}
function parseMonthNumber(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.m = n[0] - 1, i + n[0].length) : -1;
}
function parseDayOfMonth(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.d = +n[0], i + n[0].length) : -1;
}
function parseDayOfYear(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 3));
return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1;
}
function parseHour24(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.H = +n[0], i + n[0].length) : -1;
}
function parseMinutes(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.M = +n[0], i + n[0].length) : -1;
}
function parseSeconds(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 2));
return n ? (d.S = +n[0], i + n[0].length) : -1;
}
function parseMilliseconds(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 3));
return n ? (d.L = +n[0], i + n[0].length) : -1;
}
function parseMicroseconds(d, string, i) {
var n = numberRe.exec(string.slice(i, i + 6));
return n ? (d.L = Math.floor(n[0] / 1000), i + n[0].length) : -1;
}
function parseLiteralPercent(d, string, i) {
var n = percentRe.exec(string.slice(i, i + 1));
return n ? i + n[0].length : -1;
}
function parseUnixTimestamp(d, string, i) {
var n = numberRe.exec(string.slice(i));
return n ? (d.Q = +n[0], i + n[0].length) : -1;
}
function parseUnixTimestampSeconds(d, string, i) {
var n = numberRe.exec(string.slice(i));
return n ? (d.s = +n[0], i + n[0].length) : -1;
}
function formatDayOfMonth(d, p) {
return pad$1(d.getDate(), p, 2);
}
function formatHour24(d, p) {
return pad$1(d.getHours(), p, 2);
}
function formatHour12(d, p) {
return pad$1(d.getHours() % 12 || 12, p, 2);
}
function formatDayOfYear(d, p) {
return pad$1(1 + day.count(year(d), d), p, 3);
}
function formatMilliseconds(d, p) {
return pad$1(d.getMilliseconds(), p, 3);
}
function formatMicroseconds(d, p) {
return formatMilliseconds(d, p) + "000";
}
function formatMonthNumber(d, p) {
return pad$1(d.getMonth() + 1, p, 2);
}
function formatMinutes(d, p) {
return pad$1(d.getMinutes(), p, 2);
}
function formatSeconds(d, p) {
return pad$1(d.getSeconds(), p, 2);
}
function formatWeekdayNumberMonday(d) {
var day = d.getDay();
return 0 === day ? 7 : day;
}
function formatWeekNumberSunday(d, p) {
return pad$1(sunday.count(year(d) - 1, d), p, 2);
}
function dISO(d) {
var day = d.getDay();
return day >= 4 || 0 === day ? thursday(d) : thursday.ceil(d);
}
function formatWeekNumberISO(d, p) {
return d = dISO(d), pad$1(thursday.count(year(d), d) + (4 === year(d).getDay()), p, 2);
}
function formatWeekdayNumberSunday(d) {
return d.getDay();
}
function formatWeekNumberMonday(d, p) {
return pad$1(monday.count(year(d) - 1, d), p, 2);
}
function formatYear$1(d, p) {
return pad$1(d.getFullYear() % 100, p, 2);
}
function formatYearISO(d, p) {
return pad$1((d = dISO(d)).getFullYear() % 100, p, 2);
}
function formatFullYear(d, p) {
return pad$1(d.getFullYear() % 10000, p, 4);
}
function formatFullYearISO(d, p) {
var day = d.getDay();
return pad$1((d = day >= 4 || 0 === day ? thursday(d) : thursday.ceil(d)).getFullYear() % 10000, p, 4);
}
function formatZone(d) {
var z = d.getTimezoneOffset();
return (z > 0 ? "-" : (z *= -1, "+")) + pad$1(z / 60 | 0, "0", 2) + pad$1(z % 60, "0", 2);
}
function formatUTCDayOfMonth(d, p) {
return pad$1(d.getUTCDate(), p, 2);
}
function formatUTCHour24(d, p) {
return pad$1(d.getUTCHours(), p, 2);
}
function formatUTCHour12(d, p) {
return pad$1(d.getUTCHours() % 12 || 12, p, 2);
}
function formatUTCDayOfYear(d, p) {
return pad$1(1 + utcDay.count(utcYear(d), d), p, 3);
}
function formatUTCMilliseconds(d, p) {
return pad$1(d.getUTCMilliseconds(), p, 3);
}
function formatUTCMicroseconds(d, p) {
return formatUTCMilliseconds(d, p) + "000";
}
function formatUTCMonthNumber(d, p) {
return pad$1(d.getUTCMonth() + 1, p, 2);
}
function formatUTCMinutes(d, p) {
return pad$1(d.getUTCMinutes(), p, 2);
}
function formatUTCSeconds(d, p) {
return pad$1(d.getUTCSeconds(), p, 2);
}
function formatUTCWeekdayNumberMonday(d) {
var dow = d.getUTCDay();
return 0 === dow ? 7 : dow;
}
function formatUTCWeekNumberSunday(d, p) {
return pad$1(utcSunday.count(utcYear(d) - 1, d), p, 2);
}
function UTCdISO(d) {
var day = d.getUTCDay();
return day >= 4 || 0 === day ? utcThursday(d) : utcThursday.ceil(d);
}
function formatUTCWeekNumberISO(d, p) {
return d = UTCdISO(d), pad$1(utcThursday.count(utcYear(d), d) + (4 === utcYear(d).getUTCDay()), p, 2);
}
function formatUTCWeekdayNumberSunday(d) {
return d.getUTCDay();
}
function formatUTCWeekNumberMonday(d, p) {
return pad$1(utcMonday.count(utcYear(d) - 1, d), p, 2);
}
function formatUTCYear(d, p) {
return pad$1(d.getUTCFullYear() % 100, p, 2);
}
function formatUTCYearISO(d, p) {
return pad$1((d = UTCdISO(d)).getUTCFullYear() % 100, p, 2);
}
function formatUTCFullYear(d, p) {
return pad$1(d.getUTCFullYear() % 10000, p, 4);
}
function formatUTCFullYearISO(d, p) {
var day = d.getUTCDay();
return pad$1((d = day >= 4 || 0 === day ? utcThursday(d) : utcThursday.ceil(d)).getUTCFullYear() % 10000, p, 4);
}
function formatUTCZone() {
return "+0000";
}
function formatLiteralPercent() {
return "%";
}
function formatUnixTimestamp(d) {
return +d;
}
function formatUnixTimestampSeconds(d) {
return Math.floor(+d / 1000);
}
function defaultLocale$1(definition) {
return exports1.timeFormat = (locale$1 = formatLocale$1(definition)).format, exports1.timeParse = locale$1.parse, exports1.utcFormat = locale$1.utcFormat, exports1.utcParse = locale$1.utcParse, locale$1;
}
defaultLocale$1({
dateTime: "%x, %X",
date: "%-m/%-d/%Y",
time: "%-I:%M:%S %p",
periods: [
"AM",
"PM"
],
days: [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
shortDays: [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
months: [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
shortMonths: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
]
});
var isoSpecifier = "%Y-%m-%dT%H:%M:%S.%LZ", formatIso = Date.prototype.toISOString ? function(date) {
return date.toISOString();
} : exports1.utcFormat(isoSpecifier), parseIso = +new Date("2000-01-01T00:00:00.000Z") ? function(string) {
var date = new Date(string);
return isNaN(date) ? null : date;
} : exports1.utcParse(isoSpecifier);
function date$1(t) {
return new Date(t);
}
function number$3(t) {
return t instanceof Date ? +t : +new Date(+t);
}
function calendar(year, month, week, day, hour, minute, second, millisecond, format) {
var scale = continuous(), invert = scale.invert, domain = scale.domain, formatMillisecond = format(".%L"), formatSecond = format(":%S"), formatMinute = format("%I:%M"), formatHour = format("%I %p"), formatDay = format("%a %d"), formatWeek = format("%b %d"), formatMonth = format("%B"), formatYear = format("%Y"), tickIntervals = [
[
second,
1,
1000
],
[
second,
5,
5000
],
[
second,
15,
15000
],
[
second,
30,
30000
],
[
minute,
1,
60000
],
[
minute,
5,
300000
],
[
minute,
15,
900000
],
[
minute,
30,
1800000
],
[
hour,
1,
3600000
],
[
hour,
3,
10800000
],
[
hour,
6,
21600000
],
[
hour,
12,
43200000
],
[
day,
1,
86400000
],
[
day,
2,
172800000
],
[
week,
1,
604800000
],
[
month,
1,
2592000000
],
[
month,
3,
7776000000
],
[
year,
1,
31536000000
]
];
function tickFormat(date) {
return (second(date) < date ? formatMillisecond : minute(date) < date ? formatSecond : hour(date) < date ? formatMinute : day(date) < date ? formatHour : month(date) < date ? week(date) < date ? formatDay : formatWeek : year(date) < date ? formatMonth : formatYear)(date);
}
function tickInterval(interval, start, stop) {
// If a desired tick count is specified, pick a reasonable tick interval
// based on the extent of the domain and a rough estimate of tick size.
// Otherwise, assume interval is already a time interval and use it.
if (null == interval && (interval = 10), "number" == typeof interval) {
var step, target = Math.abs(stop - start) / interval, i = bisector(function(i) {
return i[2];
}).right(tickIntervals, target);
return i === tickIntervals.length ? (step = tickStep(start / 31536000000, stop / 31536000000, interval), interval = year) : i ? (step = (i = tickIntervals[target / tickIntervals[i - 1][2] < tickIntervals[i][2] / target ? i - 1 : i])[1], interval = i[0]) : (step = Math.max(tickStep(start, stop, interval), 1), interval = millisecond), interval.every(step);
}
return interval;
}
return scale.invert = function(y) {
return new Date(invert(y));
}, scale.domain = function(_) {
return arguments.length ? domain(Array.from(_, number$3)) : domain().map(date$1);
}, scale.ticks = function(interval) {
var t, d = domain(), t0 = d[0], t1 = d[d.length - 1], r = t1 < t0;
return r && (t = t0, t0 = t1, t1 = t), t = (t = tickInterval(interval, t0, t1)) ? t.range(t0, t1 + 1) : [], r ? t.reverse() : t;
}, scale.tickFormat = function(count, specifier) {
return null == specifier ? tickFormat : format(specifier);
}, scale.nice = function(interval) {
var d = domain();
return (interval = tickInterval(interval, d[0], d[d.length - 1])) ? domain(nice$1(d, interval)) : scale;
}, scale.copy = function() {
return copy(scale, calendar(year, month, week, day, hour, minute, second, millisecond, format));
}, scale;
}
function transformer$2() {
var t0, t1, k10, transform, unknown, x0 = 0, x1 = 1, interpolator = identity$6, clamp = !1;
function scale(x) {
return isNaN(x *= 1) ? unknown : interpolator(0 === k10 ? 0.5 : (x = (transform(x) - t0) * k10, clamp ? Math.max(0, Math.min(1, x)) : x));
}
function range(interpolate) {
return function(_) {
var r0, r1;
return arguments.length ? ([r0, r1] = _, interpolator = interpolate(r0, r1), scale) : [
interpolator(0),
interpolator(1)
];
};
}
return scale.domain = function(_) {
return arguments.length ? ([x0, x1] = _, t0 = transform(x0 *= 1), t1 = transform(x1 *= 1), k10 = t0 === t1 ? 0 : 1 / (t1 - t0), scale) : [
x0,
x1
];
}, scale.clamp = function(_) {
return arguments.length ? (clamp = !!_, scale) : clamp;
}, scale.interpolator = function(_) {
return arguments.length ? (interpolator = _, scale) : interpolator;
}, scale.range = range(interpolate), scale.rangeRound = range(interpolateRound), scale.unknown = function(_) {
return arguments.length ? (unknown = _, scale) : unknown;
}, function(t) {
return transform = t, t0 = t(x0), t1 = t(x1), k10 = t0 === t1 ? 0 : 1 / (t1 - t0), scale;
};
}
function copy$1(source, target) {
return target.domain(source.domain()).interpolator(source.interpolator()).clamp(source.clamp()).unknown(source.unknown());
}
function sequentialPow() {
var scale = powish(transformer$2());
return scale.copy = function() {
return copy$1(scale, sequentialPow()).exponent(scale.exponent());
}, initInterpolator.apply(scale, arguments);
}
function transformer$3() {
var t0, t1, t2, k10, k21, transform, unknown, x0 = 0, x1 = 0.5, x2 = 1, s = 1, interpolator = identity$6, clamp = !1;
function scale(x) {
return isNaN(x *= 1) ? unknown : (x = 0.5 + ((x = +transform(x)) - t1) * (s * x < s * t1 ? k10 : k21), interpolator(clamp ? Math.max(0, Math.min(1, x)) : x));
}
function range(interpolate) {
return function(_) {
var r0, r1, r2;
return arguments.length ? ([r0, r1, r2] = _, interpolator = piecewise(interpolate, [
r0,
r1,
r2
]), scale) : [
interpolator(0),
interpolator(0.5),
interpolator(1)
];
};
}
return scale.domain = function(_) {
return arguments.length ? ([x0, x1, x2] = _, t0 = transform(x0 *= 1), t1 = transform(x1 *= 1), t2 = transform(x2 *= 1), k10 = t0 === t1 ? 0 : 0.5 / (t1 - t0), k21 = t1 === t2 ? 0 : 0.5 / (t2 - t1), s = t1 < t0 ? -1 : 1, scale) : [
x0,
x1,
x2
];
}, scale.clamp = function(_) {
return arguments.length ? (clamp = !!_, scale) : clamp;
}, scale.interpolator = function(_) {
return arguments.length ? (interpolator = _, scale) : interpolator;
}, scale.range = range(interpolate), scale.rangeRound = range(interpolateRound), scale.unknown = function(_) {
return arguments.length ? (unknown = _, scale) : unknown;
}, function(t) {
return transform = t, t0 = t(x0), t1 = t(x1), t2 = t(x2), k10 = t0 === t1 ? 0 : 0.5 / (t1 - t0), k21 = t1 === t2 ? 0 : 0.5 / (t2 - t1), s = t1 < t0 ? -1 : 1, scale;
};
}
function divergingPow() {
var scale = powish(transformer$3());
return scale.copy = function() {
return copy$1(scale, divergingPow()).exponent(scale.exponent());
}, initInterpolator.apply(scale, arguments);
}
function colors(specifier) {
for(var n = specifier.length / 6 | 0, colors = Array(n), i = 0; i < n;)colors[i] = "#" + specifier.slice(6 * i, 6 * ++i);
return colors;
}
var category10 = colors("1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf"), Accent = colors("7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666"), Dark2 = colors("1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666"), Paired = colors("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928"), Pastel1 = colors("fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2"), Pastel2 = colors("b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc"), Set1 = colors("e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999"), Set2 = colors("66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3"), Set3 = colors("8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f"), Tableau10 = colors("4e79a7f28e2ce1575976b7b259a14fedc949af7aa1ff9da79c755fbab0ab"), ramp = (scheme)=>rgbBasis(scheme[scheme.length - 1]), scheme = [
,
,
,
].concat("d8b365f5f5f55ab4ac", "a6611adfc27d80cdc1018571", "a6611adfc27df5f5f580cdc1018571", "8c510ad8b365f6e8c3c7eae55ab4ac01665e", "8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e", "8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e", "8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e", "5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30", "5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30").map(colors), BrBG = ramp(scheme), scheme$1 = [
,
,
,
].concat("af8dc3f7f7f77fbf7b", "7b3294c2a5cfa6dba0008837", "7b3294c2a5cff7f7f7a6dba0008837", "762a83af8dc3e7d4e8d9f0d37fbf7b1b7837", "762a83af8dc3e7d4e8f7f7f7d9f0d37fbf7b1b7837", "762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b7837", "762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b7837", "40004b762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b783700441b", "40004b762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b783700441b").map(colors), PRGn = ramp(scheme$1), scheme$2 = [
,
,
,
].concat("e9a3c9f7f7f7a1d76a", "d01c8bf1b6dab8e1864dac26", "d01c8bf1b6daf7f7f7b8e1864dac26", "c51b7de9a3c9fde0efe6f5d0a1d76a4d9221", "c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221", "c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221", "c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221", "8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419", "8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419").map(colors), PiYG = ramp(scheme$2), scheme$3 = [
,
,
,
].concat("998ec3f7f7f7f1a340", "5e3c99b2abd2fdb863e66101", "5e3c99b2abd2f7f7f7fdb863e66101", "542788998ec3d8daebfee0b6f1a340b35806", "542788998ec3d8daebf7f7f7fee0b6f1a340b35806", "5427888073acb2abd2d8daebfee0b6fdb863e08214b35806", "5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b35806", "2d004b5427888073acb2abd2d8daebfee0b6fdb863e08214b358067f3b08", "2d004b5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b358067f3b08").map(colors), PuOr = ramp(scheme$3), scheme$4 = [
,
,
,
].concat("ef8a62f7f7f767a9cf", "ca0020f4a58292c5de0571b0", "ca0020f4a582f7f7f792c5de0571b0", "b2182bef8a62fddbc7d1e5f067a9cf2166ac", "b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac", "b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac", "b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac", "67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061", "67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061").map(colors), RdBu = ramp(scheme$4), scheme$5 = [
,
,
,
].concat("ef8a62ffffff999999", "ca0020f4a582bababa404040", "ca0020f4a582ffffffbababa404040", "b2182bef8a62fddbc7e0e0e09999994d4d4d", "b2182bef8a62fddbc7ffffffe0e0e09999994d4d4d", "b2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d", "b2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d", "67001fb2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d1a1a1a", "67001fb2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d1a1a1a").map(colors), RdGy = ramp(scheme$5), scheme$6 = [
,
,
,
].concat("fc8d59ffffbf91bfdb", "d7191cfdae61abd9e92c7bb6", "d7191cfdae61ffffbfabd9e92c7bb6", "d73027fc8d59fee090e0f3f891bfdb4575b4", "d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4", "d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4", "d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4", "a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695", "a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695").map(colors), RdYlBu = ramp(scheme$6), scheme$7 = [
,
,
,
].concat("fc8d59ffffbf91cf60", "d7191cfdae61a6d96a1a9641", "d7191cfdae61ffffbfa6d96a1a9641", "d73027fc8d59fee08bd9ef8b91cf601a9850", "d73027fc8d59fee08bffffbfd9ef8b91cf601a9850", "d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850", "d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850", "a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837", "a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837").map(colors), RdYlGn = ramp(scheme$7), scheme$8 = [
,
,
,
].concat("fc8d59ffffbf99d594", "d7191cfdae61abdda42b83ba", "d7191cfdae61ffffbfabdda42b83ba", "d53e4ffc8d59fee08be6f59899d5943288bd", "d53e4ffc8d59fee08bffffbfe6f59899d5943288bd", "d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd", "d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd", "9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2", "9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2").map(colors), Spectral = ramp(scheme$8), scheme$9 = [
,
,
,
].concat("e5f5f999d8c92ca25f", "edf8fbb2e2e266c2a4238b45", "edf8fbb2e2e266c2a42ca25f006d2c", "edf8fbccece699d8c966c2a42ca25f006d2c", "edf8fbccece699d8c966c2a441ae76238b45005824", "f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824", "f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b").map(colors), BuGn = ramp(scheme$9), scheme$a = [
,
,
,
].concat("e0ecf49ebcda8856a7", "edf8fbb3cde38c96c688419d", "edf8fbb3cde38c96c68856a7810f7c", "edf8fbbfd3e69ebcda8c96c68856a7810f7c", "edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b", "f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b", "f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b").map(colors), BuPu = ramp(scheme$a), scheme$b = [
,
,
,
].concat("e0f3dba8ddb543a2ca", "f0f9e8bae4bc7bccc42b8cbe", "f0f9e8bae4bc7bccc443a2ca0868ac", "f0f9e8ccebc5a8ddb57bccc443a2ca0868ac", "f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e", "f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e", "f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081").map(colors), GnBu = ramp(scheme$b), scheme$c = [
,
,
,
].concat("fee8c8fdbb84e34a33", "fef0d9fdcc8afc8d59d7301f", "fef0d9fdcc8afc8d59e34a33b30000", "fef0d9fdd49efdbb84fc8d59e34a33b30000", "fef0d9fdd49efdbb84fc8d59ef6548d7301f990000", "fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000", "fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000").map(colors), OrRd = ramp(scheme$c), scheme$d = [
,
,
,
].concat("ece2f0a6bddb1c9099", "f6eff7bdc9e167a9cf02818a", "f6eff7bdc9e167a9cf1c9099016c59", "f6eff7d0d1e6a6bddb67a9cf1c9099016c59", "f6eff7d0d1e6a6bddb67a9cf3690c002818a016450", "fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450", "fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636").map(colors), PuBuGn = ramp(scheme$d), scheme$e = [
,
,
,
].concat("ece7f2a6bddb2b8cbe", "f1eef6bdc9e174a9cf0570b0", "f1eef6bdc9e174a9cf2b8cbe045a8d", "f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d", "f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b", "fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b", "fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858").map(colors), PuBu = ramp(scheme$e), scheme$f = [
,
,
,
].concat("e7e1efc994c7dd1c77", "f1eef6d7b5d8df65b0ce1256", "f1eef6d7b5d8df65b0dd1c77980043", "f1eef6d4b9dac994c7df65b0dd1c77980043", "f1eef6d4b9dac994c7df65b0e7298ace125691003f", "f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f", "f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f").map(colors), PuRd = ramp(scheme$f), scheme$g = [
,
,
,
].concat("fde0ddfa9fb5c51b8a", "feebe2fbb4b9f768a1ae017e", "feebe2fbb4b9f768a1c51b8a7a0177", "feebe2fcc5c0fa9fb5f768a1c51b8a7a0177", "feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177", "fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177", "fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a").map(colors), RdPu = ramp(scheme$g), scheme$h = [
,
,
,
].concat("edf8b17fcdbb2c7fb8", "ffffcca1dab441b6c4225ea8", "ffffcca1dab441b6c42c7fb8253494", "ffffccc7e9b47fcdbb41b6c42c7fb8253494", "ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84", "ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84", "ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58").map(colors), YlGnBu = ramp(scheme$h), scheme$i = [
,
,
,
].concat("f7fcb9addd8e31a354", "ffffccc2e69978c679238443", "ffffccc2e69978c67931a354006837", "ffffccd9f0a3addd8e78c67931a354006837", "ffffccd9f0a3addd8e78c67941ab5d238443005a32", "ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32", "ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529").map(colors), YlGn = ramp(scheme$i), scheme$j = [
,
,
,
].concat("fff7bcfec44fd95f0e", "ffffd4fed98efe9929cc4c02", "ffffd4fed98efe9929d95f0e993404", "ffffd4fee391fec44ffe9929d95f0e993404", "ffffd4fee391fec44ffe9929ec7014cc4c028c2d04", "ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04", "ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506").map(colors), YlOrBr = ramp(scheme$j), scheme$k = [
,
,
,
].concat("ffeda0feb24cf03b20", "ffffb2fecc5cfd8d3ce31a1c", "ffffb2fecc5cfd8d3cf03b20bd0026", "ffffb2fed976feb24cfd8d3cf03b20bd0026", "ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026", "ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026", "ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026").map(colors), YlOrRd = ramp(scheme$k), scheme$l = [
,
,
,
].concat("deebf79ecae13182bd", "eff3ffbdd7e76baed62171b5", "eff3ffbdd7e76baed63182bd08519c", "eff3ffc6dbef9ecae16baed63182bd08519c", "eff3ffc6dbef9ecae16baed64292c62171b5084594", "f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594", "f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b").map(colors), Blues = ramp(scheme$l), scheme$m = [
,
,
,
].concat("e5f5e0a1d99b31a354", "edf8e9bae4b374c476238b45", "edf8e9bae4b374c47631a354006d2c", "edf8e9c7e9c0a1d99b74c47631a354006d2c", "edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32", "f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32", "f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b").map(colors), Greens = ramp(scheme$m), scheme$n = [
,
,
,
].concat("f0f0f0bdbdbd636363", "f7f7f7cccccc969696525252", "f7f7f7cccccc969696636363252525", "f7f7f7d9d9d9bdbdbd969696636363252525", "f7f7f7d9d9d9bdbdbd969696737373525252252525", "fffffff0f0f0d9d9d9bdbdbd969696737373525252252525", "fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000").map(colors), Greys = ramp(scheme$n), scheme$o = [
,
,
,
].concat("efedf5bcbddc756bb1", "f2f0f7cbc9e29e9ac86a51a3", "f2f0f7cbc9e29e9ac8756bb154278f", "f2f0f7dadaebbcbddc9e9ac8756bb154278f", "f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486", "fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486", "fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d").map(colors), Purples = ramp(scheme$o), scheme$p = [
,
,
,
].concat("fee0d2fc9272de2d26", "fee5d9fcae91fb6a4acb181d", "fee5d9fcae91fb6a4ade2d26a50f15", "fee5d9fcbba1fc9272fb6a4ade2d26a50f15", "fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d", "fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d", "fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d").map(colors), Reds = ramp(scheme$p), scheme$q = [
,
,
,
].concat("fee6cefdae6be6550d", "feeddefdbe85fd8d3cd94701", "feeddefdbe85fd8d3ce6550da63603", "feeddefdd0a2fdae6bfd8d3ce6550da63603", "feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04", "fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04", "fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704").map(colors), Oranges = ramp(scheme$q), cubehelix$3 = cubehelixLong(cubehelix(300, 0.5, 0.0), cubehelix(-240, 0.5, 1.0)), warm = cubehelixLong(cubehelix(-100, 0.75, 0.35), cubehelix(80, 1.50, 0.8)), cool = cubehelixLong(cubehelix(260, 0.75, 0.35), cubehelix(80, 1.50, 0.8)), c$1 = cubehelix(), c$2 = rgb(), pi_1_3 = Math.PI / 3, pi_2_3 = 2 * Math.PI / 3;
function ramp$1(range) {
var n = range.length;
return function(t) {
return range[Math.max(0, Math.min(n - 1, Math.floor(t * n)))];
};
}
var viridis = ramp$1(colors("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725")), magma = ramp$1(colors("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")), inferno = ramp$1(colors("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")), plasma = ramp$1(colors("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));
function constant$a(x) {
return function() {
return x;
};
}
var abs$3 = Math.abs, atan2$1 = Math.atan2, cos$2 = Math.cos, max$3 = Math.max, min$2 = Math.min, sin$2 = Math.sin, sqrt$2 = Math.sqrt, pi$4 = Math.PI, halfPi$3 = pi$4 / 2, tau$5 = 2 * pi$4;
function asin$1(x) {
return x >= 1 ? halfPi$3 : x <= -1 ? -halfPi$3 : Math.asin(x);
}
function arcInnerRadius(d) {
return d.innerRadius;
}
function arcOuterRadius(d) {
return d.outerRadius;
}
function arcStartAngle(d) {
return d.startAngle;
}
function arcEndAngle(d) {
return d.endAngle;
}
function arcPadAngle(d) {
return d && d.padAngle; // Note: optional!
}
// Compute perpendicular offset line of length rc.
// http://mathworld.wolfram.com/Circle-LineIntersection.html
function cornerTangents(x0, y0, x1, y1, r1, rc, cw) {
var x01 = x0 - x1, y01 = y0 - y1, lo = (cw ? rc : -rc) / sqrt$2(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x11 = x0 + ox, y11 = y0 + oy, x10 = x1 + ox, y10 = y1 + oy, x00 = (x11 + x10) / 2, y00 = (y11 + y10) / 2, dx = x10 - x11, dy = y10 - y11, d2 = dx * dx + dy * dy, r = r1 - rc, D = x11 * y10 - x10 * y11, d = (dy < 0 ? -1 : 1) * sqrt$2(max$3(0, r * r * d2 - D * D)), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x00, dy0 = cy0 - y00, dx1 = cx1 - x00, dy1 = cy1 - y00;
return dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1 && (cx0 = cx1, cy0 = cy1), {
cx: cx0,
cy: cy0,
x01: -ox,
y01: -oy,
x11: cx0 * (r1 / r - 1),
y11: cy0 * (r1 / r - 1)
};
}
var slice$4 = Array.prototype.slice;
function array$5(x) {
return "object" == typeof x && "length" in x ? x // Array, TypedArray, NodeList, array-like
: Array.from(x); // Map, Set, iterable, string, or anything else
}
function Linear(context) {
this._context = context;
}
function curveLinear(context) {
return new Linear(context);
}
function x$3(p) {
return p[0];
}
function y$3(p) {
return p[1];
}
function line(x, y) {
var defined = constant$a(!0), context = null, curve = curveLinear, output = null;
function line(data) {
var i, d, buffer, n = (data = array$5(data)).length, defined0 = !1;
for(null == context && (output = curve(buffer = path())), i = 0; i <= n; ++i)!(i < n && defined(d = data[i], i, data)) === defined0 && ((defined0 = !defined0) ? output.lineStart() : output.lineEnd()), defined0 && output.point(+x(d, i, data), +y(d, i, data));
if (buffer) return output = null, buffer + "" || null;
}
return x = "function" == typeof x ? x : void 0 === x ? x$3 : constant$a(x), y = "function" == typeof y ? y : void 0 === y ? y$3 : constant$a(y), line.x = function(_) {
return arguments.length ? (x = "function" == typeof _ ? _ : constant$a(+_), line) : x;
}, line.y = function(_) {
return arguments.length ? (y = "function" == typeof _ ? _ : constant$a(+_), line) : y;
}, line.defined = function(_) {
return arguments.length ? (defined = "function" == typeof _ ? _ : constant$a(!!_), line) : defined;
}, line.curve = function(_) {
return arguments.length ? (curve = _, null != context && (output = curve(context)), line) : curve;
}, line.context = function(_) {
return arguments.length ? (null == _ ? context = output = null : output = curve(context = _), line) : context;
}, line;
}
function area$3(x0, y0, y1) {
var x1 = null, defined = constant$a(!0), context = null, curve = curveLinear, output = null;
function area(data) {
var i, j, k, d, buffer, n = (data = array$5(data)).length, defined0 = !1, x0z = Array(n), y0z = Array(n);
for(null == context && (output = curve(buffer = path())), i = 0; i <= n; ++i){
if (!(i < n && defined(d = data[i], i, data)) === defined0) {
if (defined0 = !defined0) j = i, output.areaStart(), output.lineStart();
else {
for(output.lineEnd(), output.lineStart(), k = i - 1; k >= j; --k)output.point(x0z[k], y0z[k]);
output.lineEnd(), output.areaEnd();
}
}
defined0 && (x0z[i] = +x0(d, i, data), y0z[i] = +y0(d, i, data), output.point(x1 ? +x1(d, i, data) : x0z[i], y1 ? +y1(d, i, data) : y0z[i]));
}
if (buffer) return output = null, buffer + "" || null;
}
function arealine() {
return line().defined(defined).curve(curve).context(context);
}
return x0 = "function" == typeof x0 ? x0 : void 0 === x0 ? x$3 : constant$a(+x0), y0 = "function" == typeof y0 ? y0 : void 0 === y0 ? constant$a(0) : constant$a(+y0), y1 = "function" == typeof y1 ? y1 : void 0 === y1 ? y$3 : constant$a(+y1), area.x = function(_) {
return arguments.length ? (x0 = "function" == typeof _ ? _ : constant$a(+_), x1 = null, area) : x0;
}, area.x0 = function(_) {
return arguments.length ? (x0 = "function" == typeof _ ? _ : constant$a(+_), area) : x0;
}, area.x1 = function(_) {
return arguments.length ? (x1 = null == _ ? null : "function" == typeof _ ? _ : constant$a(+_), area) : x1;
}, area.y = function(_) {
return arguments.length ? (y0 = "function" == typeof _ ? _ : constant$a(+_), y1 = null, area) : y0;
}, area.y0 = function(_) {
return arguments.length ? (y0 = "function" == typeof _ ? _ : constant$a(+_), area) : y0;
}, area.y1 = function(_) {
return arguments.length ? (y1 = null == _ ? null : "function" == typeof _ ? _ : constant$a(+_), area) : y1;
}, area.lineX0 = area.lineY0 = function() {
return arealine().x(x0).y(y0);
}, area.lineY1 = function() {
return arealine().x(x0).y(y1);
}, area.lineX1 = function() {
return arealine().x(x1).y(y0);
}, area.defined = function(_) {
return arguments.length ? (defined = "function" == typeof _ ? _ : constant$a(!!_), area) : defined;
}, area.curve = function(_) {
return arguments.length ? (curve = _, null != context && (output = curve(context)), area) : curve;
}, area.context = function(_) {
return arguments.length ? (null == _ ? context = output = null : output = curve(context = _), area) : context;
}, area;
}
function descending$1(a, b) {
return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
}
function identity$8(d) {
return d;
}
Linear.prototype = {
areaStart: function() {
this._line = 0;
},
areaEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._point = 0;
},
lineEnd: function() {
(this._line || 0 !== this._line && 1 === this._point) && this._context.closePath(), this._line = 1 - this._line;
},
point: function(x, y) {
switch(x *= 1, y *= 1, this._point){
case 0:
this._point = 1, this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y);
break;
case 1:
this._point = 2; // proceed
default:
this._context.lineTo(x, y);
}
}
};
var curveRadialLinear = curveRadial(curveLinear);
function Radial(curve) {
this._curve = curve;
}
function curveRadial(curve) {
function radial(context) {
return new Radial(curve(context));
}
return radial._curve = curve, radial;
}
function lineRadial(l) {
var c = l.curve;
return l.angle = l.x, delete l.x, l.radius = l.y, delete l.y, l.curve = function(_) {
return arguments.length ? c(curveRadial(_)) : c()._curve;
}, l;
}
function lineRadial$1() {
return lineRadial(line().curve(curveRadialLinear));
}
function areaRadial() {
var a = area$3().curve(curveRadialLinear), c = a.curve, x0 = a.lineX0, x1 = a.lineX1, y0 = a.lineY0, y1 = a.lineY1;
return a.angle = a.x, delete a.x, a.startAngle = a.x0, delete a.x0, a.endAngle = a.x1, delete a.x1, a.radius = a.y, delete a.y, a.innerRadius = a.y0, delete a.y0, a.outerRadius = a.y1, delete a.y1, a.lineStartAngle = function() {
return lineRadial(x0());
}, delete a.lineX0, a.lineEndAngle = function() {
return lineRadial(x1());
}, delete a.lineX1, a.lineInnerRadius = function() {
return lineRadial(y0());
}, delete a.lineY0, a.lineOuterRadius = function() {
return lineRadial(y1());
}, delete a.lineY1, a.curve = function(_) {
return arguments.length ? c(curveRadial(_)) : c()._curve;
}, a;
}
function pointRadial(x, y) {
return [
(y *= 1) * Math.cos(x -= Math.PI / 2),
y * Math.sin(x)
];
}
function linkSource(d) {
return d.source;
}
function linkTarget(d) {
return d.target;
}
function link$2(curve) {
var source = linkSource, target = linkTarget, x = x$3, y = y$3, context = null;
function link() {
var buffer, argv = slice$4.call(arguments), s = source.apply(this, argv), t = target.apply(this, argv);
if (context || (context = buffer = path()), curve(context, +x.apply(this, (argv[0] = s, argv)), +y.apply(this, argv), +x.apply(this, (argv[0] = t, argv)), +y.apply(this, argv)), buffer) return context = null, buffer + "" || null;
}
return link.source = function(_) {
return arguments.length ? (source = _, link) : source;
}, link.target = function(_) {
return arguments.length ? (target = _, link) : target;
}, link.x = function(_) {
return arguments.length ? (x = "function" == typeof _ ? _ : constant$a(+_), link) : x;
}, link.y = function(_) {
return arguments.length ? (y = "function" == typeof _ ? _ : constant$a(+_), link) : y;
}, link.context = function(_) {
return arguments.length ? (context = null == _ ? null : _, link) : context;
}, link;
}
function curveHorizontal(context, x0, y0, x1, y1) {
context.moveTo(x0, y0), context.bezierCurveTo(x0 = (x0 + x1) / 2, y0, x0, y1, x1, y1);
}
function curveVertical(context, x0, y0, x1, y1) {
context.moveTo(x0, y0), context.bezierCurveTo(x0, y0 = (y0 + y1) / 2, x1, y0, x1, y1);
}
function curveRadial$1(context, x0, y0, x1, y1) {
var p0 = pointRadial(x0, y0), p1 = pointRadial(x0, y0 = (y0 + y1) / 2), p2 = pointRadial(x1, y0), p3 = pointRadial(x1, y1);
context.moveTo(p0[0], p0[1]), context.bezierCurveTo(p1[0], p1[1], p2[0], p2[1], p3[0], p3[1]);
}
Radial.prototype = {
areaStart: function() {
this._curve.areaStart();
},
areaEnd: function() {
this._curve.areaEnd();
},
lineStart: function() {
this._curve.lineStart();
},
lineEnd: function() {
this._curve.lineEnd();
},
point: function(a, r) {
this._curve.point(r * Math.sin(a), -(r * Math.cos(a)));
}
};
var circle$2 = {
draw: function(context, size) {
var r = Math.sqrt(size / pi$4);
context.moveTo(r, 0), context.arc(0, 0, r, 0, tau$5);
}
}, cross$2 = {
draw: function(context, size) {
var r = Math.sqrt(size / 5) / 2;
context.moveTo(-3 * r, -r), context.lineTo(-r, -r), context.lineTo(-r, -3 * r), context.lineTo(r, -3 * r), context.lineTo(r, -r), context.lineTo(3 * r, -r), context.lineTo(3 * r, r), context.lineTo(r, r), context.lineTo(r, 3 * r), context.lineTo(-r, 3 * r), context.lineTo(-r, r), context.lineTo(-3 * r, r), context.closePath();
}
}, tan30 = Math.sqrt(1 / 3), tan30_2 = 2 * tan30, diamond = {
draw: function(context, size) {
var y = Math.sqrt(size / tan30_2), x = y * tan30;
context.moveTo(0, -y), context.lineTo(x, 0), context.lineTo(0, y), context.lineTo(-x, 0), context.closePath();
}
}, kr = Math.sin(pi$4 / 10) / Math.sin(7 * pi$4 / 10), kx = Math.sin(tau$5 / 10) * kr, ky = -Math.cos(tau$5 / 10) * kr, star = {
draw: function(context, size) {
var r = Math.sqrt(0.89081309152928522810 * size), x = kx * r, y = ky * r;
context.moveTo(0, -r), context.lineTo(x, y);
for(var i = 1; i < 5; ++i){
var a = tau$5 * i / 5, c = Math.cos(a), s = Math.sin(a);
context.lineTo(s * r, -c * r), context.lineTo(c * x - s * y, s * x + c * y);
}
context.closePath();
}
}, square$1 = {
draw: function(context, size) {
var w = Math.sqrt(size), x = -w / 2;
context.rect(x, x, w, w);
}
}, sqrt3 = Math.sqrt(3), triangle = {
draw: function(context, size) {
var y = -Math.sqrt(size / (3 * sqrt3));
context.moveTo(0, 2 * y), context.lineTo(-sqrt3 * y, -y), context.lineTo(sqrt3 * y, -y), context.closePath();
}
}, s = Math.sqrt(3) / 2, k = 1 / Math.sqrt(12), a$1 = (k / 2 + 1) * 3, wye = {
draw: function(context, size) {
var r = Math.sqrt(size / a$1), x0 = r / 2, y0 = r * k, y1 = r * k + r, x2 = -x0;
context.moveTo(x0, y0), context.lineTo(x0, y1), context.lineTo(x2, y1), context.lineTo(-0.5 * x0 - s * y0, s * x0 + -0.5 * y0), context.lineTo(-0.5 * x0 - s * y1, s * x0 + -0.5 * y1), context.lineTo(-0.5 * x2 - s * y1, s * x2 + -0.5 * y1), context.lineTo(-0.5 * x0 + s * y0, -0.5 * y0 - s * x0), context.lineTo(-0.5 * x0 + s * y1, -0.5 * y1 - s * x0), context.lineTo(-0.5 * x2 + s * y1, -0.5 * y1 - s * x2), context.closePath();
}
}, symbols = [
circle$2,
cross$2,
diamond,
square$1,
star,
triangle,
wye
];
function noop$3() {}
function point$1(that, x, y) {
that._context.bezierCurveTo((2 * that._x0 + that._x1) / 3, (2 * that._y0 + that._y1) / 3, (that._x0 + 2 * that._x1) / 3, (that._y0 + 2 * that._y1) / 3, (that._x0 + 4 * that._x1 + x) / 6, (that._y0 + 4 * that._y1 + y) / 6);
}
function Basis(context) {
this._context = context;
}
function BasisClosed(context) {
this._context = context;
}
function BasisOpen(context) {
this._context = context;
}
function Bundle(context, beta) {
this._basis = new Basis(context), this._beta = beta;
}
Basis.prototype = {
areaStart: function() {
this._line = 0;
},
areaEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._x0 = this._x1 = this._y0 = this._y1 = NaN, this._point = 0;
},
lineEnd: function() {
switch(this._point){
case 3:
point$1(this, this._x1, this._y1); // proceed
case 2:
this._context.lineTo(this._x1, this._y1);
}
(this._line || 0 !== this._line && 1 === this._point) && this._context.closePath(), this._line = 1 - this._line;
},
point: function(x, y) {
switch(x *= 1, y *= 1, this._point){
case 0:
this._point = 1, this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y);
break;
case 1:
this._point = 2;
break;
case 2:
this._point = 3, this._context.lineTo((5 * this._x0 + this._x1) / 6, (5 * this._y0 + this._y1) / 6);
default:
point$1(this, x, y);
}
this._x0 = this._x1, this._x1 = x, this._y0 = this._y1, this._y1 = y;
}
}, BasisClosed.prototype = {
areaStart: noop$3,
areaEnd: noop$3,
lineStart: function() {
this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = NaN, this._point = 0;
},
lineEnd: function() {
switch(this._point){
case 1:
this._context.moveTo(this._x2, this._y2), this._context.closePath();
break;
case 2:
this._context.moveTo((this._x2 + 2 * this._x3) / 3, (this._y2 + 2 * this._y3) / 3), this._context.lineTo((this._x3 + 2 * this._x2) / 3, (this._y3 + 2 * this._y2) / 3), this._context.closePath();
break;
case 3:
this.point(this._x2, this._y2), this.point(this._x3, this._y3), this.point(this._x4, this._y4);
}
},
point: function(x, y) {
switch(x *= 1, y *= 1, this._point){
case 0:
this._point = 1, this._x2 = x, this._y2 = y;
break;
case 1:
this._point = 2, this._x3 = x, this._y3 = y;
break;
case 2:
this._point = 3, this._x4 = x, this._y4 = y, this._context.moveTo((this._x0 + 4 * this._x1 + x) / 6, (this._y0 + 4 * this._y1 + y) / 6);
break;
default:
point$1(this, x, y);
}
this._x0 = this._x1, this._x1 = x, this._y0 = this._y1, this._y1 = y;
}
}, BasisOpen.prototype = {
areaStart: function() {
this._line = 0;
},
areaEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._x0 = this._x1 = this._y0 = this._y1 = NaN, this._point = 0;
},
lineEnd: function() {
(this._line || 0 !== this._line && 3 === this._point) && this._context.closePath(), this._line = 1 - this._line;
},
point: function(x, y) {
switch(x *= 1, y *= 1, this._point){
case 0:
this._point = 1;
break;
case 1:
this._point = 2;
break;
case 2:
this._point = 3;
var x0 = (this._x0 + 4 * this._x1 + x) / 6, y0 = (this._y0 + 4 * this._y1 + y) / 6;
this._line ? this._context.lineTo(x0, y0) : this._context.moveTo(x0, y0);
break;
case 3:
this._point = 4; // proceed
default:
point$1(this, x, y);
}
this._x0 = this._x1, this._x1 = x, this._y0 = this._y1, this._y1 = y;
}
}, Bundle.prototype = {
lineStart: function() {
this._x = [], this._y = [], this._basis.lineStart();
},
lineEnd: function() {
var x = this._x, y = this._y, j = x.length - 1;
if (j > 0) for(var t, x0 = x[0], y0 = y[0], dx = x[j] - x0, dy = y[j] - y0, i = -1; ++i <= j;)t = i / j, this._basis.point(this._beta * x[i] + (1 - this._beta) * (x0 + t * dx), this._beta * y[i] + (1 - this._beta) * (y0 + t * dy));
this._x = this._y = null, this._basis.lineEnd();
},
point: function(x, y) {
this._x.push(+x), this._y.push(+y);
}
};
var bundle = function custom(beta) {
function bundle(context) {
return 1 === beta ? new Basis(context) : new Bundle(context, beta);
}
return bundle.beta = function(beta) {
return custom(+beta);
}, bundle;
}(0.85);
function point$2(that, x, y) {
that._context.bezierCurveTo(that._x1 + that._k * (that._x2 - that._x0), that._y1 + that._k * (that._y2 - that._y0), that._x2 + that._k * (that._x1 - x), that._y2 + that._k * (that._y1 - y), that._x2, that._y2);
}
function Cardinal(context, tension) {
this._context = context, this._k = (1 - tension) / 6;
}
Cardinal.prototype = {
areaStart: function() {
this._line = 0;
},
areaEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._x0 = this._x1 = this._x2 = this._y0 = this._y1 = this._y2 = NaN, this._point = 0;
},
lineEnd: function() {
switch(this._point){
case 2:
this._context.lineTo(this._x2, this._y2);
break;
case 3:
point$2(this, this._x1, this._y1);
}
(this._line || 0 !== this._line && 1 === this._point) && this._context.closePath(), this._line = 1 - this._line;
},
point: function(x, y) {
switch(x *= 1, y *= 1, this._point){
case 0:
this._point = 1, this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y);
break;
case 1:
this._point = 2, this._x1 = x, this._y1 = y;
break;
case 2:
this._point = 3; // proceed
default:
point$2(this, x, y);
}
this._x0 = this._x1, this._x1 = this._x2, this._x2 = x, this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
}
};
var cardinal = function custom(tension) {
function cardinal(context) {
return new Cardinal(context, tension);
}
return cardinal.tension = function(tension) {
return custom(+tension);
}, cardinal;
}(0);
function CardinalClosed(context, tension) {
this._context = context, this._k = (1 - tension) / 6;
}
CardinalClosed.prototype = {
areaStart: noop$3,
areaEnd: noop$3,
lineStart: function() {
this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._x5 = this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = this._y5 = NaN, this._point = 0;
},
lineEnd: function() {
switch(this._point){
case 1:
this._context.moveTo(this._x3, this._y3), this._context.closePath();
break;
case 2:
this._context.lineTo(this._x3, this._y3), this._context.closePath();
break;
case 3:
this.point(this._x3, this._y3), this.point(this._x4, this._y4), this.point(this._x5, this._y5);
}
},
point: function(x, y) {
switch(x *= 1, y *= 1, this._point){
case 0:
this._point = 1, this._x3 = x, this._y3 = y;
break;
case 1:
this._point = 2, this._context.moveTo(this._x4 = x, this._y4 = y);
break;
case 2:
this._point = 3, this._x5 = x, this._y5 = y;
break;
default:
point$2(this, x, y);
}
this._x0 = this._x1, this._x1 = this._x2, this._x2 = x, this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
}
};
var cardinalClosed = function custom(tension) {
function cardinal(context) {
return new CardinalClosed(context, tension);
}
return cardinal.tension = function(tension) {
return custom(+tension);
}, cardinal;
}(0);
function CardinalOpen(context, tension) {
this._context = context, this._k = (1 - tension) / 6;
}
CardinalOpen.prototype = {
areaStart: function() {
this._line = 0;
},
areaEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._x0 = this._x1 = this._x2 = this._y0 = this._y1 = this._y2 = NaN, this._point = 0;
},
lineEnd: function() {
(this._line || 0 !== this._line && 3 === this._point) && this._context.closePath(), this._line = 1 - this._line;
},
point: function(x, y) {
switch(x *= 1, y *= 1, this._point){
case 0:
this._point = 1;
break;
case 1:
this._point = 2;
break;
case 2:
this._point = 3, this._line ? this._context.lineTo(this._x2, this._y2) : this._context.moveTo(this._x2, this._y2);
break;
case 3:
this._point = 4; // proceed
default:
point$2(this, x, y);
}
this._x0 = this._x1, this._x1 = this._x2, this._x2 = x, this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
}
};
var cardinalOpen = function custom(tension) {
function cardinal(context) {
return new CardinalOpen(context, tension);
}
return cardinal.tension = function(tension) {
return custom(+tension);
}, cardinal;
}(0);
function point$3(that, x, y) {
var x1 = that._x1, y1 = that._y1, x2 = that._x2, y2 = that._y2;
if (that._l01_a > 1e-12) {
var a = 2 * that._l01_2a + 3 * that._l01_a * that._l12_a + that._l12_2a, n = 3 * that._l01_a * (that._l01_a + that._l12_a);
x1 = (x1 * a - that._x0 * that._l12_2a + that._x2 * that._l01_2a) / n, y1 = (y1 * a - that._y0 * that._l12_2a + that._y2 * that._l01_2a) / n;
}
if (that._l23_a > 1e-12) {
var b = 2 * that._l23_2a + 3 * that._l23_a * that._l12_a + that._l12_2a, m = 3 * that._l23_a * (that._l23_a + that._l12_a);
x2 = (x2 * b + that._x1 * that._l23_2a - x * that._l12_2a) / m, y2 = (y2 * b + that._y1 * that._l23_2a - y * that._l12_2a) / m;
}
that._context.bezierCurveTo(x1, y1, x2, y2, that._x2, that._y2);
}
function CatmullRom(context, alpha) {
this._context = context, this._alpha = alpha;
}
CatmullRom.prototype = {
areaStart: function() {
this._line = 0;
},
areaEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._x0 = this._x1 = this._x2 = this._y0 = this._y1 = this._y2 = NaN, this._l01_a = this._l12_a = this._l23_a = this._l01_2a = this._l12_2a = this._l23_2a = this._point = 0;
},
lineEnd: function() {
switch(this._point){
case 2:
this._context.lineTo(this._x2, this._y2);
break;
case 3:
this.point(this._x2, this._y2);
}
(this._line || 0 !== this._line && 1 === this._point) && this._context.closePath(), this._line = 1 - this._line;
},
point: function(x, y) {
if (x *= 1, y *= 1, this._point) {
var x23 = this._x2 - x, y23 = this._y2 - y;
this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));
}
switch(this._point){
case 0:
this._point = 1, this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y);
break;
case 1:
this._point = 2;
break;
case 2:
this._point = 3; // proceed
default:
point$3(this, x, y);
}
this._l01_a = this._l12_a, this._l12_a = this._l23_a, this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a, this._x0 = this._x1, this._x1 = this._x2, this._x2 = x, this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
}
};
var catmullRom = function custom(alpha) {
function catmullRom(context) {
return alpha ? new CatmullRom(context, alpha) : new Cardinal(context, 0);
}
return catmullRom.alpha = function(alpha) {
return custom(+alpha);
}, catmullRom;
}(0.5);
function CatmullRomClosed(context, alpha) {
this._context = context, this._alpha = alpha;
}
CatmullRomClosed.prototype = {
areaStart: noop$3,
areaEnd: noop$3,
lineStart: function() {
this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._x5 = this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = this._y5 = NaN, this._l01_a = this._l12_a = this._l23_a = this._l01_2a = this._l12_2a = this._l23_2a = this._point = 0;
},
lineEnd: function() {
switch(this._point){
case 1:
this._context.moveTo(this._x3, this._y3), this._context.closePath();
break;
case 2:
this._context.lineTo(this._x3, this._y3), this._context.closePath();
break;
case 3:
this.point(this._x3, this._y3), this.point(this._x4, this._y4), this.point(this._x5, this._y5);
}
},
point: function(x, y) {
if (x *= 1, y *= 1, this._point) {
var x23 = this._x2 - x, y23 = this._y2 - y;
this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));
}
switch(this._point){
case 0:
this._point = 1, this._x3 = x, this._y3 = y;
break;
case 1:
this._point = 2, this._context.moveTo(this._x4 = x, this._y4 = y);
break;
case 2:
this._point = 3, this._x5 = x, this._y5 = y;
break;
default:
point$3(this, x, y);
}
this._l01_a = this._l12_a, this._l12_a = this._l23_a, this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a, this._x0 = this._x1, this._x1 = this._x2, this._x2 = x, this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
}
};
var catmullRomClosed = function custom(alpha) {
function catmullRom(context) {
return alpha ? new CatmullRomClosed(context, alpha) : new CardinalClosed(context, 0);
}
return catmullRom.alpha = function(alpha) {
return custom(+alpha);
}, catmullRom;
}(0.5);
function CatmullRomOpen(context, alpha) {
this._context = context, this._alpha = alpha;
}
CatmullRomOpen.prototype = {
areaStart: function() {
this._line = 0;
},
areaEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._x0 = this._x1 = this._x2 = this._y0 = this._y1 = this._y2 = NaN, this._l01_a = this._l12_a = this._l23_a = this._l01_2a = this._l12_2a = this._l23_2a = this._point = 0;
},
lineEnd: function() {
(this._line || 0 !== this._line && 3 === this._point) && this._context.closePath(), this._line = 1 - this._line;
},
point: function(x, y) {
if (x *= 1, y *= 1, this._point) {
var x23 = this._x2 - x, y23 = this._y2 - y;
this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));
}
switch(this._point){
case 0:
this._point = 1;
break;
case 1:
this._point = 2;
break;
case 2:
this._point = 3, this._line ? this._context.lineTo(this._x2, this._y2) : this._context.moveTo(this._x2, this._y2);
break;
case 3:
this._point = 4; // proceed
default:
point$3(this, x, y);
}
this._l01_a = this._l12_a, this._l12_a = this._l23_a, this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a, this._x0 = this._x1, this._x1 = this._x2, this._x2 = x, this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;
}
};
var catmullRomOpen = function custom(alpha) {
function catmullRom(context) {
return alpha ? new CatmullRomOpen(context, alpha) : new CardinalOpen(context, 0);
}
return catmullRom.alpha = function(alpha) {
return custom(+alpha);
}, catmullRom;
}(0.5);
function LinearClosed(context) {
this._context = context;
}
// Calculate the slopes of the tangents (Hermite-type interpolation) based on
// the following paper: Steffen, M. 1990. A Simple Method for Monotonic
// Interpolation in One Dimension. Astronomy and Astrophysics, Vol. 239, NO.
// NOV(II), P. 443, 1990.
function slope3(that, x2, y2) {
var h0 = that._x1 - that._x0, h1 = x2 - that._x1, s0 = (that._y1 - that._y0) / (h0 || h1 < 0 && -0), s1 = (y2 - that._y1) / (h1 || h0 < 0 && -0);
return ((s0 < 0 ? -1 : 1) + (s1 < 0 ? -1 : 1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs((s0 * h1 + s1 * h0) / (h0 + h1))) || 0;
}
// Calculate a one-sided slope.
function slope2(that, t) {
var h = that._x1 - that._x0;
return h ? (3 * (that._y1 - that._y0) / h - t) / 2 : t;
}
// According to https://en.wikipedia.org/wiki/Cubic_Hermite_spline#Representations
// "you can express cubic Hermite interpolation in terms of cubic Bézier curves
// with respect to the four values p0, p0 + m0 / 3, p1 - m1 / 3, p1".
function point$4(that, t0, t1) {
var x0 = that._x0, y0 = that._y0, x1 = that._x1, y1 = that._y1, dx = (x1 - x0) / 3;
that._context.bezierCurveTo(x0 + dx, y0 + dx * t0, x1 - dx, y1 - dx * t1, x1, y1);
}
function MonotoneX(context) {
this._context = context;
}
function MonotoneY(context) {
this._context = new ReflectContext(context);
}
function ReflectContext(context) {
this._context = context;
}
function Natural(context) {
this._context = context;
}
// See https://www.particleincell.com/2012/bezier-splines/ for derivation.
function controlPoints(x) {
var i, m, n = x.length - 1, a = Array(n), b = Array(n), r = Array(n);
for(a[0] = 0, b[0] = 2, r[0] = x[0] + 2 * x[1], i = 1; i < n - 1; ++i)a[i] = 1, b[i] = 4, r[i] = 4 * x[i] + 2 * x[i + 1];
for(a[n - 1] = 2, b[n - 1] = 7, r[n - 1] = 8 * x[n - 1] + x[n], i = 1; i < n; ++i)m = a[i] / b[i - 1], b[i] -= m, r[i] -= m * r[i - 1];
for(a[n - 1] = r[n - 1] / b[n - 1], i = n - 2; i >= 0; --i)a[i] = (r[i] - a[i + 1]) / b[i];
for(i = 0, b[n - 1] = (x[n] + a[n - 1]) / 2; i < n - 1; ++i)b[i] = 2 * x[i + 1] - a[i + 1];
return [
a,
b
];
}
function Step(context, t) {
this._context = context, this._t = t;
}
function none$1(series, order) {
if ((n = series.length) > 1) for(var j, s0, n, i = 1, s1 = series[order[0]], m = s1.length; i < n; ++i)for(s0 = s1, s1 = series[order[i]], j = 0; j < m; ++j)s1[j][1] += s1[j][0] = isNaN(s0[j][1]) ? s0[j][0] : s0[j][1];
}
function none$2(series) {
for(var n = series.length, o = Array(n); --n >= 0;)o[n] = n;
return o;
}
function stackValue(d, key) {
return d[key];
}
function stackSeries(key) {
const series = [];
return series.key = key, series;
}
function appearance(series) {
var peaks = series.map(peak);
return none$2(series).sort(function(a, b) {
return peaks[a] - peaks[b];
});
}
function peak(series) {
for(var vi, i = -1, j = 0, n = series.length, vj = -1 / 0; ++i < n;)(vi = +series[i][1]) > vj && (vj = vi, j = i);
return j;
}
function ascending$3(series) {
var sums = series.map(sum$1);
return none$2(series).sort(function(a, b) {
return sums[a] - sums[b];
});
}
function sum$1(series) {
for(var v, s = 0, i = -1, n = series.length; ++i < n;)(v = +series[i][1]) && (s += v);
return s;
}
LinearClosed.prototype = {
areaStart: noop$3,
areaEnd: noop$3,
lineStart: function() {
this._point = 0;
},
lineEnd: function() {
this._point && this._context.closePath();
},
point: function(x, y) {
x *= 1, y *= 1, this._point ? this._context.lineTo(x, y) : (this._point = 1, this._context.moveTo(x, y));
}
}, MonotoneX.prototype = {
areaStart: function() {
this._line = 0;
},
areaEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._x0 = this._x1 = this._y0 = this._y1 = this._t0 = NaN, this._point = 0;
},
lineEnd: function() {
switch(this._point){
case 2:
this._context.lineTo(this._x1, this._y1);
break;
case 3:
point$4(this, this._t0, slope2(this, this._t0));
}
(this._line || 0 !== this._line && 1 === this._point) && this._context.closePath(), this._line = 1 - this._line;
},
point: function(x, y) {
var t1 = NaN;
if (y *= 1, (x *= 1) !== this._x1 || y !== this._y1) {
switch(this._point){
case 0:
this._point = 1, this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y);
break;
case 1:
this._point = 2;
break;
case 2:
this._point = 3, point$4(this, slope2(this, t1 = slope3(this, x, y)), t1);
break;
default:
point$4(this, this._t0, t1 = slope3(this, x, y));
}
this._x0 = this._x1, this._x1 = x, this._y0 = this._y1, this._y1 = y, this._t0 = t1;
} // Ignore coincident points.
}
}, (MonotoneY.prototype = Object.create(MonotoneX.prototype)).point = function(x, y) {
MonotoneX.prototype.point.call(this, y, x);
}, ReflectContext.prototype = {
moveTo: function(x, y) {
this._context.moveTo(y, x);
},
closePath: function() {
this._context.closePath();
},
lineTo: function(x, y) {
this._context.lineTo(y, x);
},
bezierCurveTo: function(x1, y1, x2, y2, x, y) {
this._context.bezierCurveTo(y1, x1, y2, x2, y, x);
}
}, Natural.prototype = {
areaStart: function() {
this._line = 0;
},
areaEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._x = [], this._y = [];
},
lineEnd: function() {
var x = this._x, y = this._y, n = x.length;
if (n) {
if (this._line ? this._context.lineTo(x[0], y[0]) : this._context.moveTo(x[0], y[0]), 2 === n) this._context.lineTo(x[1], y[1]);
else for(var px = controlPoints(x), py = controlPoints(y), i0 = 0, i1 = 1; i1 < n; ++i0, ++i1)this._context.bezierCurveTo(px[0][i0], py[0][i0], px[1][i0], py[1][i0], x[i1], y[i1]);
}
(this._line || 0 !== this._line && 1 === n) && this._context.closePath(), this._line = 1 - this._line, this._x = this._y = null;
},
point: function(x, y) {
this._x.push(+x), this._y.push(+y);
}
}, Step.prototype = {
areaStart: function() {
this._line = 0;
},
areaEnd: function() {
this._line = NaN;
},
lineStart: function() {
this._x = this._y = NaN, this._point = 0;
},
lineEnd: function() {
0 < this._t && this._t < 1 && 2 === this._point && this._context.lineTo(this._x, this._y), (this._line || 0 !== this._line && 1 === this._point) && this._context.closePath(), this._line >= 0 && (this._t = 1 - this._t, this._line = 1 - this._line);
},
point: function(x, y) {
switch(x *= 1, y *= 1, this._point){
case 0:
this._point = 1, this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y);
break;
case 1:
this._point = 2; // proceed
default:
if (this._t <= 0) this._context.lineTo(this._x, y), this._context.lineTo(x, y);
else {
var x1 = this._x * (1 - this._t) + x * this._t;
this._context.lineTo(x1, this._y), this._context.lineTo(x1, y);
}
}
this._x = x, this._y = y;
}
};
var constant$b = (x)=>()=>x;
function ZoomEvent(type, { sourceEvent, target, transform, dispatch }) {
Object.defineProperties(this, {
type: {
value: type,
enumerable: !0,
configurable: !0
},
sourceEvent: {
value: sourceEvent,
enumerable: !0,
configurable: !0
},
target: {
value: target,
enumerable: !0,
configurable: !0
},
transform: {
value: transform,
enumerable: !0,
configurable: !0
},
_: {
value: dispatch
}
});
}
function Transform(k, x, y) {
this.k = k, this.x = x, this.y = y;
}
Transform.prototype = {
constructor: Transform,
scale: function(k) {
return 1 === k ? this : new Transform(this.k * k, this.x, this.y);
},
translate: function(x, y) {
return 0 === x & 0 === y ? this : new Transform(this.k, this.x + this.k * x, this.y + this.k * y);
},
apply: function(point) {
return [
point[0] * this.k + this.x,
point[1] * this.k + this.y
];
},
applyX: function(x) {
return x * this.k + this.x;
},
applyY: function(y) {
return y * this.k + this.y;
},
invert: function(location) {
return [
(location[0] - this.x) / this.k,
(location[1] - this.y) / this.k
];
},
invertX: function(x) {
return (x - this.x) / this.k;
},
invertY: function(y) {
return (y - this.y) / this.k;
},
rescaleX: function(x) {
return x.copy().domain(x.range().map(this.invertX, this).map(x.invert, x));
},
rescaleY: function(y) {
return y.copy().domain(y.range().map(this.invertY, this).map(y.invert, y));
},
toString: function() {
return "translate(" + this.x + "," + this.y + ") scale(" + this.k + ")";
}
};
var identity$9 = new Transform(1, 0, 0);
function transform$1(node) {
for(; !node.__zoom;)if (!(node = node.parentNode)) return identity$9;
return node.__zoom;
}
function nopropagation$2(event) {
event.stopImmediatePropagation();
}
function noevent$2(event) {
event.preventDefault(), event.stopImmediatePropagation();
}
// Ignore right-click, since that should open the context menu.
// except for pinch-to-zoom, which is sent as a wheel+ctrlKey event
function defaultFilter$2(event) {
return (!event.ctrlKey || 'wheel' === event.type) && !event.button;
}
function defaultExtent$1() {
var e = this;
return e instanceof SVGElement ? (e = e.ownerSVGElement || e).hasAttribute("viewBox") ? [
[
(e = e.viewBox.baseVal).x,
e.y
],
[
e.x + e.width,
e.y + e.height
]
] : [
[
0,
0
],
[
e.width.baseVal.value,
e.height.baseVal.value
]
] : [
[
0,
0
],
[
e.clientWidth,
e.clientHeight
]
];
}
function defaultTransform() {
return this.__zoom || identity$9;
}
function defaultWheelDelta(event) {
return -event.deltaY * (1 === event.deltaMode ? 0.05 : event.deltaMode ? 1 : 0.002) * (event.ctrlKey ? 10 : 1);
}
function defaultTouchable$2() {
return navigator.maxTouchPoints || "ontouchstart" in this;
}
function defaultConstrain(transform, extent, translateExtent) {
var dx0 = transform.invertX(extent[0][0]) - translateExtent[0][0], dx1 = transform.invertX(extent[1][0]) - translateExtent[1][0], dy0 = transform.invertY(extent[0][1]) - translateExtent[0][1], dy1 = transform.invertY(extent[1][1]) - translateExtent[1][1];
return transform.translate(dx1 > dx0 ? (dx0 + dx1) / 2 : Math.min(0, dx0) || Math.max(0, dx1), dy1 > dy0 ? (dy0 + dy1) / 2 : Math.min(0, dy0) || Math.max(0, dy1));
}
transform$1.prototype = Transform.prototype, exports1.Adder = Adder, exports1.Delaunay = Delaunay, exports1.FormatSpecifier = FormatSpecifier, exports1.Voronoi = Voronoi, exports1.active = function(node, name) {
var schedule, i, schedules = node.__transition;
if (schedules) {
for(i in name = null == name ? null : name + "", schedules)if ((schedule = schedules[i]).state > 1 && schedule.name === name) return new Transition([
[
node
]
], root$1, name, +i);
}
return null;
}, exports1.arc = function() {
var innerRadius = arcInnerRadius, outerRadius = arcOuterRadius, cornerRadius = constant$a(0), padRadius = null, startAngle = arcStartAngle, endAngle = arcEndAngle, padAngle = arcPadAngle, context = null;
function arc() {
var buffer, r, r0 = +innerRadius.apply(this, arguments), r1 = +outerRadius.apply(this, arguments), a0 = startAngle.apply(this, arguments) - halfPi$3, a1 = endAngle.apply(this, arguments) - halfPi$3, da = abs$3(a1 - a0), cw = a1 > a0;
// Is it a point?
if (context || (context = buffer = path()), r1 < r0 && (r = r1, r1 = r0, r0 = r), r1 > 1e-12) {
if (da > tau$5 - 1e-12) context.moveTo(r1 * cos$2(a0), r1 * sin$2(a0)), context.arc(0, 0, r1, a0, a1, !cw), r0 > 1e-12 && (context.moveTo(r0 * cos$2(a1), r0 * sin$2(a1)), context.arc(0, 0, r0, a1, a0, cw));
else {
var t0, t1, a01 = a0, a11 = a1, a00 = a0, a10 = a1, da0 = da, da1 = da, ap = padAngle.apply(this, arguments) / 2, rp = ap > 1e-12 && (padRadius ? +padRadius.apply(this, arguments) : sqrt$2(r0 * r0 + r1 * r1)), rc = min$2(abs$3(r1 - r0) / 2, +cornerRadius.apply(this, arguments)), rc0 = rc, rc1 = rc;
// Apply padding? Note that since r1 ≥ r0, da1 ≥ da0.
if (rp > 1e-12) {
var p0 = asin$1(rp / r0 * sin$2(ap)), p1 = asin$1(rp / r1 * sin$2(ap));
(da0 -= 2 * p0) > 1e-12 ? (p0 *= cw ? 1 : -1, a00 += p0, a10 -= p0) : (da0 = 0, a00 = a10 = (a0 + a1) / 2), (da1 -= 2 * p1) > 1e-12 ? (p1 *= cw ? 1 : -1, a01 += p1, a11 -= p1) : (da1 = 0, a01 = a11 = (a0 + a1) / 2);
}
var x01 = r1 * cos$2(a01), y01 = r1 * sin$2(a01), x10 = r0 * cos$2(a10), y10 = r0 * sin$2(a10);
// Apply rounded corners?
if (rc > 1e-12) {
var oc, x11 = r1 * cos$2(a11), y11 = r1 * sin$2(a11), x00 = r0 * cos$2(a00), y00 = r0 * sin$2(a00);
// Restrict the corner radius according to the sector angle.
if (da < pi$4 && (oc = function(x0, y0, x1, y1, x2, y2, x3, y3) {
var x10 = x1 - x0, y10 = y1 - y0, x32 = x3 - x2, y32 = y3 - y2, t = y32 * x10 - x32 * y10;
if (!(t * t < 1e-12)) return t = (x32 * (y0 - y2) - y32 * (x0 - x2)) / t, [
x0 + t * x10,
y0 + t * y10
];
}(x01, y01, x00, y00, x11, y11, x10, y10))) {
var x, ax = x01 - oc[0], ay = y01 - oc[1], bx = x11 - oc[0], by = y11 - oc[1], kc = 1 / sin$2(((x = (ax * bx + ay * by) / (sqrt$2(ax * ax + ay * ay) * sqrt$2(bx * bx + by * by))) > 1 ? 0 : x < -1 ? pi$4 : Math.acos(x)) / 2), lc = sqrt$2(oc[0] * oc[0] + oc[1] * oc[1]);
rc0 = min$2(rc, (r0 - lc) / (kc - 1)), rc1 = min$2(rc, (r1 - lc) / (kc + 1));
}
}
da1 > 1e-12 ? rc1 > 1e-12 ? (t0 = cornerTangents(x00, y00, x01, y01, r1, rc1, cw), t1 = cornerTangents(x11, y11, x10, y10, r1, rc1, cw), context.moveTo(t0.cx + t0.x01, t0.cy + t0.y01), rc1 < rc ? context.arc(t0.cx, t0.cy, rc1, atan2$1(t0.y01, t0.x01), atan2$1(t1.y01, t1.x01), !cw) : (context.arc(t0.cx, t0.cy, rc1, atan2$1(t0.y01, t0.x01), atan2$1(t0.y11, t0.x11), !cw), context.arc(0, 0, r1, atan2$1(t0.cy + t0.y11, t0.cx + t0.x11), atan2$1(t1.cy + t1.y11, t1.cx + t1.x11), !cw), context.arc(t1.cx, t1.cy, rc1, atan2$1(t1.y11, t1.x11), atan2$1(t1.y01, t1.x01), !cw))) : (context.moveTo(x01, y01), context.arc(0, 0, r1, a01, a11, !cw)) : context.moveTo(x01, y01), r0 > 1e-12 && da0 > 1e-12 ? rc0 > 1e-12 ? (t0 = cornerTangents(x10, y10, x11, y11, r0, -rc0, cw), t1 = cornerTangents(x01, y01, x00, y00, r0, -rc0, cw), context.lineTo(t0.cx + t0.x01, t0.cy + t0.y01), rc0 < rc ? context.arc(t0.cx, t0.cy, rc0, atan2$1(t0.y01, t0.x01), atan2$1(t1.y01, t1.x01), !cw) : (context.arc(t0.cx, t0.cy, rc0, atan2$1(t0.y01, t0.x01), atan2$1(t0.y11, t0.x11), !cw), context.arc(0, 0, r0, atan2$1(t0.cy + t0.y11, t0.cx + t0.x11), atan2$1(t1.cy + t1.y11, t1.cx + t1.x11), cw), context.arc(t1.cx, t1.cy, rc0, atan2$1(t1.y11, t1.x11), atan2$1(t1.y01, t1.x01), !cw))) : context.arc(0, 0, r0, a10, a00, cw) : context.lineTo(x10, y10);
}
} else context.moveTo(0, 0);
if (context.closePath(), buffer) return context = null, buffer + "" || null;
}
return arc.centroid = function() {
var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - pi$4 / 2;
return [
cos$2(a) * r,
sin$2(a) * r
];
}, arc.innerRadius = function(_) {
return arguments.length ? (innerRadius = "function" == typeof _ ? _ : constant$a(+_), arc) : innerRadius;
}, arc.outerRadius = function(_) {
return arguments.length ? (outerRadius = "function" == typeof _ ? _ : constant$a(+_), arc) : outerRadius;
}, arc.cornerRadius = function(_) {
return arguments.length ? (cornerRadius = "function" == typeof _ ? _ : constant$a(+_), arc) : cornerRadius;
}, arc.padRadius = function(_) {
return arguments.length ? (padRadius = null == _ ? null : "function" == typeof _ ? _ : constant$a(+_), arc) : padRadius;
}, arc.startAngle = function(_) {
return arguments.length ? (startAngle = "function" == typeof _ ? _ : constant$a(+_), arc) : startAngle;
}, arc.endAngle = function(_) {
return arguments.length ? (endAngle = "function" == typeof _ ? _ : constant$a(+_), arc) : endAngle;
}, arc.padAngle = function(_) {
return arguments.length ? (padAngle = "function" == typeof _ ? _ : constant$a(+_), arc) : padAngle;
}, arc.context = function(_) {
return arguments.length ? (context = null == _ ? null : _, arc) : context;
}, arc;
}, exports1.area = area$3, exports1.areaRadial = areaRadial, exports1.ascending = ascending, exports1.autoType = function(object) {
for(var key in object){
var number, m, value = object[key].trim();
if (value) {
if ("true" === value) value = !0;
else if ("false" === value) value = !1;
else if ("NaN" === value) value = NaN;
else if (isNaN(number = +value)) {
if (!(m = value.match(/^([-+]\d{2})?\d{4}(-\d{2}(-\d{2})?)?(T\d{2}:\d{2}(:\d{2}(\.\d{3})?)?(Z|[-+]\d{2}:\d{2})?)?$/))) continue;
fixtz && m[4] && !m[7] && (value = value.replace(/-/g, "/").replace(/T/, " ")), value = new Date(value);
} else value = number;
} else value = null;
object[key] = value;
}
return object;
}, exports1.axisBottom = function(scale) {
return axis(3, scale);
}, exports1.axisLeft = function(scale) {
return axis(4, scale);
}, exports1.axisRight = function(scale) {
return axis(2, scale);
}, exports1.axisTop = function(scale) {
return axis(1, scale);
}, exports1.bin = bin, exports1.bisect = bisectRight, exports1.bisectCenter = bisectCenter, exports1.bisectLeft = bisectLeft, exports1.bisectRight = bisectRight, exports1.bisector = bisector, exports1.blob = function(input, init) {
return fetch(input, init).then(responseBlob);
}, exports1.brush = function() {
return brush$1(XY);
}, exports1.brushSelection = function(node) {
var state = node.__brush;
return state ? state.dim.output(state.selection) : null;
}, exports1.brushX = function() {
return brush$1(X);
}, exports1.brushY = function() {
return brush$1(Y);
}, exports1.buffer = function(input, init) {
return fetch(input, init).then(responseArrayBuffer);
}, exports1.chord = function() {
return chord$1(!1, !1);
}, exports1.chordDirected = function() {
return chord$1(!0, !1);
}, exports1.chordTranspose = function() {
return chord$1(!1, !0);
}, exports1.cluster = function() {
var separation = defaultSeparation, dx = 1, dy = 1, nodeSize = !1;
function cluster(root) {
var previousNode, x = 0;
// First walk, computing the initial x & y values.
root.eachAfter(function(node) {
var children = node.children;
children ? (node.x = children.reduce(meanXReduce, 0) / children.length, node.y = 1 + children.reduce(maxYReduce, 0)) : (node.x = previousNode ? x += separation(node, previousNode) : 0, node.y = 0, previousNode = node);
});
var left = function(node) {
for(var children; children = node.children;)node = children[0];
return node;
}(root), right = function(node) {
for(var children; children = node.children;)node = children[children.length - 1];
return node;
}(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2;
// Second walk, normalizing x & y to the desired size.
return root.eachAfter(nodeSize ? function(node) {
node.x = (node.x - root.x) * dx, node.y = (root.y - node.y) * dy;
} : function(node) {
node.x = (node.x - x0) / (x1 - x0) * dx, node.y = (1 - (root.y ? node.y / root.y : 1)) * dy;
});
}
return cluster.separation = function(x) {
return arguments.length ? (separation = x, cluster) : separation;
}, cluster.size = function(x) {
return arguments.length ? (nodeSize = !1, dx = +x[0], dy = +x[1], cluster) : nodeSize ? null : [
dx,
dy
];
}, cluster.nodeSize = function(x) {
return arguments.length ? (nodeSize = !0, dx = +x[0], dy = +x[1], cluster) : nodeSize ? [
dx,
dy
] : null;
}, cluster;
}, exports1.color = color, exports1.contourDensity = function() {
var x = defaultX, y = defaultY, weight = defaultWeight, dx = 960, dy = 500, r = 20, k = 2, o = 60, n = 270, m = 155, threshold = constant$6(20);
function density(data) {
var values0 = new Float32Array(n * m), values1 = new Float32Array(n * m);
data.forEach(function(d, i, data) {
var xi = +x(d, i, data) + o >> k, yi = +y(d, i, data) + o >> k, wi = +weight(d, i, data);
xi >= 0 && xi < n && yi >= 0 && yi < m && (values0[xi + yi * n] += wi);
}), // TODO Optimize.
blurX({
width: n,
height: m,
data: values0
}, {
width: n,
height: m,
data: values1
}, r >> k), blurY({
width: n,
height: m,
data: values1
}, {
width: n,
height: m,
data: values0
}, r >> k), blurX({
width: n,
height: m,
data: values0
}, {
width: n,
height: m,
data: values1
}, r >> k), blurY({
width: n,
height: m,
data: values1
}, {
width: n,
height: m,
data: values0
}, r >> k), blurX({
width: n,
height: m,
data: values0
}, {
width: n,
height: m,
data: values1
}, r >> k), blurY({
width: n,
height: m,
data: values1
}, {
width: n,
height: m,
data: values0
}, r >> k);
var tz = threshold(values0);
// Convert number of thresholds into uniform thresholds.
if (!Array.isArray(tz)) {
var stop = max(values0);
tz = tickStep(0, stop, tz), (tz = sequence(0, Math.floor(stop / tz) * tz, tz)).shift();
}
return contours().thresholds(tz).size([
n,
m
])(values0).map(transform);
}
function transform(geometry) {
return geometry.value *= Math.pow(2, -2 * k), geometry.coordinates.forEach(transformPolygon), geometry;
}
function transformPolygon(coordinates) {
coordinates.forEach(transformRing);
}
function transformRing(coordinates) {
coordinates.forEach(transformPoint);
}
// TODO Optimize.
function transformPoint(coordinates) {
coordinates[0] = coordinates[0] * Math.pow(2, k) - o, coordinates[1] = coordinates[1] * Math.pow(2, k) - o;
}
function resize() {
return n = dx + 2 * (o = 3 * r) >> k, m = dy + 2 * o >> k, density;
}
return density.x = function(_) {
return arguments.length ? (x = "function" == typeof _ ? _ : constant$6(+_), density) : x;
}, density.y = function(_) {
return arguments.length ? (y = "function" == typeof _ ? _ : constant$6(+_), density) : y;
}, density.weight = function(_) {
return arguments.length ? (weight = "function" == typeof _ ? _ : constant$6(+_), density) : weight;
}, density.size = function(_) {
if (!arguments.length) return [
dx,
dy
];
var _0 = +_[0], _1 = +_[1];
if (!(_0 >= 0 && _1 >= 0)) throw Error("invalid size");
return dx = _0, dy = _1, resize();
}, density.cellSize = function(_) {
if (!arguments.length) return 1 << k;
if (!((_ *= 1) >= 1)) throw Error("invalid cell size");
return k = Math.floor(Math.log(_) / Math.LN2), resize();
}, density.thresholds = function(_) {
return arguments.length ? (threshold = "function" == typeof _ ? _ : Array.isArray(_) ? constant$6(slice$3.call(_)) : constant$6(_), density) : threshold;
}, density.bandwidth = function(_) {
if (!arguments.length) return Math.sqrt(r * (r + 1));
if (!((_ *= 1) >= 0)) throw Error("invalid bandwidth");
return r = Math.round((Math.sqrt(4 * _ * _ + 1) - 1) / 2), resize();
}, density;
}, exports1.contours = contours, exports1.count = count, exports1.create = function(name) {
return select(creator(name).call(document.documentElement));
}, exports1.creator = creator, exports1.cross = function(...values) {
var reduce;
const reduce1 = "function" == typeof values[values.length - 1] && (reduce = values.pop(), (values)=>reduce(...values)), lengths = (values = values.map(arrayify)).map(length), j = values.length - 1, index = Array(j + 1).fill(0), product = [];
if (j < 0 || lengths.some(empty)) return product;
for(;;){
product.push(index.map((j, i)=>values[i][j]));
let i = j;
for(; ++index[i] === lengths[i];){
if (0 === i) return reduce1 ? product.map(reduce1) : product;
index[i--] = 0;
}
}
}, exports1.csv = csv$1, exports1.csvFormat = csvFormat, exports1.csvFormatBody = csvFormatBody, exports1.csvFormatRow = csvFormatRow, exports1.csvFormatRows = csvFormatRows, exports1.csvFormatValue = csvFormatValue, exports1.csvParse = csvParse, exports1.csvParseRows = csvParseRows, exports1.cubehelix = cubehelix, exports1.cumsum = function(values, valueof) {
var sum = 0, index = 0;
return Float64Array.from(values, void 0 === valueof ? (v)=>sum += +v || 0 : (v)=>sum += +valueof(v, index++, values) || 0);
}, exports1.curveBasis = function(context) {
return new Basis(context);
}, exports1.curveBasisClosed = function(context) {
return new BasisClosed(context);
}, exports1.curveBasisOpen = function(context) {
return new BasisOpen(context);
}, exports1.curveBundle = bundle, exports1.curveCardinal = cardinal, exports1.curveCardinalClosed = cardinalClosed, exports1.curveCardinalOpen = cardinalOpen, exports1.curveCatmullRom = catmullRom, exports1.curveCatmullRomClosed = catmullRomClosed, exports1.curveCatmullRomOpen = catmullRomOpen, exports1.curveLinear = curveLinear, exports1.curveLinearClosed = function(context) {
return new LinearClosed(context);
}, exports1.curveMonotoneX = function(context) {
return new MonotoneX(context);
}, exports1.curveMonotoneY = function(context) {
return new MonotoneY(context);
}, exports1.curveNatural = function(context) {
return new Natural(context);
}, exports1.curveStep = function(context) {
return new Step(context, 0.5);
}, exports1.curveStepAfter = function(context) {
return new Step(context, 1);
}, exports1.curveStepBefore = function(context) {
return new Step(context, 0);
}, exports1.descending = function(a, b) {
return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
}, exports1.deviation = deviation, exports1.difference = function(values, ...others) {
for (const other of (values = new Set(values), others))for (const value of other)values.delete(value);
return values;
}, exports1.disjoint = function(values, other) {
const iterator = other[Symbol.iterator](), set = new Set();
for (const v of values){
let value, done;
if (set.has(v)) return !1;
for(; ({ value, done } = iterator.next()) && !done;){
if (Object.is(v, value)) return !1;
set.add(value);
}
}
return !0;
}, exports1.dispatch = dispatch, exports1.drag = function() {
var mousedownx, mousedowny, mousemoving, touchending, filter = defaultFilter, container = defaultContainer, subject = defaultSubject, touchable = defaultTouchable, gestures = {}, listeners = dispatch("start", "drag", "end"), active = 0, clickDistance2 = 0;
function drag(selection) {
selection.on("mousedown.drag", mousedowned).filter(touchable).on("touchstart.drag", touchstarted).on("touchmove.drag", touchmoved).on("touchend.drag touchcancel.drag", touchended).style("touch-action", "none").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)");
}
function mousedowned(event, d) {
if (!touchending && filter.call(this, event, d)) {
var gesture = beforestart(this, container.call(this, event, d), event, d, "mouse");
gesture && (select(event.view).on("mousemove.drag", mousemoved, !0).on("mouseup.drag", mouseupped, !0), dragDisable(event.view), nopropagation(event), mousemoving = !1, mousedownx = event.clientX, mousedowny = event.clientY, gesture("start", event));
}
}
function mousemoved(event) {
if (noevent(event), !mousemoving) {
var dx = event.clientX - mousedownx, dy = event.clientY - mousedowny;
mousemoving = dx * dx + dy * dy > clickDistance2;
}
gestures.mouse("drag", event);
}
function mouseupped(event) {
select(event.view).on("mousemove.drag mouseup.drag", null), yesdrag(event.view, mousemoving), noevent(event), gestures.mouse("end", event);
}
function touchstarted(event, d) {
if (filter.call(this, event, d)) {
var i, gesture, touches = event.changedTouches, c = container.call(this, event, d), n = touches.length;
for(i = 0; i < n; ++i)(gesture = beforestart(this, c, event, d, touches[i].identifier, touches[i])) && (nopropagation(event), gesture("start", event, touches[i]));
}
}
function touchmoved(event) {
var i, gesture, touches = event.changedTouches, n = touches.length;
for(i = 0; i < n; ++i)(gesture = gestures[touches[i].identifier]) && (noevent(event), gesture("drag", event, touches[i]));
}
function touchended(event) {
var i, gesture, touches = event.changedTouches, n = touches.length;
for(touchending && clearTimeout(touchending), touchending = setTimeout(function() {
touchending = null;
}, 500), i = 0; i < n; ++i)(gesture = gestures[touches[i].identifier]) && (nopropagation(event), gesture("end", event, touches[i]));
}
function beforestart(that, container, event, d, identifier, touch) {
var dx, dy, s, dispatch = listeners.copy(), p = pointer(touch || event, container);
if (null != (s = subject.call(that, new DragEvent("beforestart", {
sourceEvent: event,
target: drag,
identifier,
active,
x: p[0],
y: p[1],
dx: 0,
dy: 0,
dispatch
}), d))) return dx = s.x - p[0] || 0, dy = s.y - p[1] || 0, function gesture(type, event, touch) {
var n, p0 = p;
switch(type){
case "start":
gestures[identifier] = gesture, n = active++;
break;
case "end":
delete gestures[identifier], --active; // nobreak
case "drag":
p = pointer(touch || event, container), n = active;
}
dispatch.call(type, that, new DragEvent(type, {
sourceEvent: event,
subject: s,
target: drag,
identifier,
active: n,
x: p[0] + dx,
y: p[1] + dy,
dx: p[0] - p0[0],
dy: p[1] - p0[1],
dispatch
}), d);
};
}
return drag.filter = function(_) {
return arguments.length ? (filter = "function" == typeof _ ? _ : constant$2(!!_), drag) : filter;
}, drag.container = function(_) {
return arguments.length ? (container = "function" == typeof _ ? _ : constant$2(_), drag) : container;
}, drag.subject = function(_) {
return arguments.length ? (subject = "function" == typeof _ ? _ : constant$2(_), drag) : subject;
}, drag.touchable = function(_) {
return arguments.length ? (touchable = "function" == typeof _ ? _ : constant$2(!!_), drag) : touchable;
}, drag.on = function() {
var value = listeners.on.apply(listeners, arguments);
return value === listeners ? drag : value;
}, drag.clickDistance = function(_) {
return arguments.length ? (clickDistance2 = (_ *= 1) * _, drag) : Math.sqrt(clickDistance2);
}, drag;
}, exports1.dragDisable = dragDisable, exports1.dragEnable = yesdrag, exports1.dsv = function(delimiter, input, init, row) {
3 == arguments.length && "function" == typeof init && (row = init, init = void 0);
var format = dsvFormat(delimiter);
return text(input, init).then(function(response) {
return format.parse(response, row);
});
}, exports1.dsvFormat = dsvFormat, exports1.easeBack = backInOut, exports1.easeBackIn = backIn, exports1.easeBackInOut = backInOut, exports1.easeBackOut = backOut, exports1.easeBounce = bounceOut, exports1.easeBounceIn = function(t) {
return 1 - bounceOut(1 - t);
}, exports1.easeBounceInOut = function(t) {
return ((t *= 2) <= 1 ? 1 - bounceOut(1 - t) : bounceOut(t - 1) + 1) / 2;
}, exports1.easeBounceOut = bounceOut, exports1.easeCircle = circleInOut, exports1.easeCircleIn = function(t) {
return 1 - Math.sqrt(1 - t * t);
}, exports1.easeCircleInOut = circleInOut, exports1.easeCircleOut = function(t) {
return Math.sqrt(1 - --t * t);
}, exports1.easeCubic = cubicInOut, exports1.easeCubicIn = function(t) {
return t * t * t;
}, exports1.easeCubicInOut = cubicInOut, exports1.easeCubicOut = function(t) {
return --t * t * t + 1;
}, exports1.easeElastic = elasticOut, exports1.easeElasticIn = elasticIn, exports1.easeElasticInOut = elasticInOut, exports1.easeElasticOut = elasticOut, exports1.easeExp = expInOut, exports1.easeExpIn = function(t) {
return tpmt(1 - +t);
}, exports1.easeExpInOut = expInOut, exports1.easeExpOut = function(t) {
return 1 - tpmt(t);
}, exports1.easeLinear = (t)=>+t, exports1.easePoly = polyInOut, exports1.easePolyIn = polyIn, exports1.easePolyInOut = polyInOut, exports1.easePolyOut = polyOut, exports1.easeQuad = quadInOut, exports1.easeQuadIn = function(t) {
return t * t;
}, exports1.easeQuadInOut = quadInOut, exports1.easeQuadOut = function(t) {
return t * (2 - t);
}, exports1.easeSin = sinInOut, exports1.easeSinIn = function(t) {
return 1 == +t ? 1 : 1 - Math.cos(t * halfPi);
}, exports1.easeSinInOut = sinInOut, exports1.easeSinOut = function(t) {
return Math.sin(t * halfPi);
}, exports1.every = function(values, test) {
if ("function" != typeof test) throw TypeError("test is not a function");
let index = -1;
for (const value of values)if (!test(value, ++index, values)) return !1;
return !0;
}, exports1.extent = extent, exports1.filter = function(values, test) {
if ("function" != typeof test) throw TypeError("test is not a function");
const array = [];
let index = -1;
for (const value of values)test(value, ++index, values) && array.push(value);
return array;
}, exports1.forceCenter = function(x, y) {
var nodes, strength = 1;
function force() {
var i, node, n = nodes.length, sx = 0, sy = 0;
for(i = 0; i < n; ++i)sx += (node = nodes[i]).x, sy += node.y;
for(sx = (sx / n - x) * strength, sy = (sy / n - y) * strength, i = 0; i < n; ++i)node = nodes[i], node.x -= sx, node.y -= sy;
}
return null == x && (x = 0), null == y && (y = 0), force.initialize = function(_) {
nodes = _;
}, force.x = function(_) {
return arguments.length ? (x = +_, force) : x;
}, force.y = function(_) {
return arguments.length ? (y = +_, force) : y;
}, force.strength = function(_) {
return arguments.length ? (strength = +_, force) : strength;
}, force;
}, exports1.forceCollide = function(radius) {
var nodes, radii, random, strength = 1, iterations = 1;
function force() {
for(var i, tree, node, xi, yi, ri, ri2, n = nodes.length, k = 0; k < iterations; ++k)for(i = 0, tree = quadtree(nodes, x, y).visitAfter(prepare); i < n; ++i)ri2 = (ri = radii[(node = nodes[i]).index]) * ri, xi = node.x + node.vx, yi = node.y + node.vy, tree.visit(apply);
function apply(quad, x0, y0, x1, y1) {
var data = quad.data, rj = quad.r, r = ri + rj;
if (data) {
if (data.index > node.index) {
var x = xi - data.x - data.vx, y = yi - data.y - data.vy, l = x * x + y * y;
l < r * r && (0 === x && (l += (x = jiggle(random)) * x), 0 === y && (l += (y = jiggle(random)) * y), l = (r - (l = Math.sqrt(l))) / l * strength, node.vx += (x *= l) * (r = (rj *= rj) / (ri2 + rj)), node.vy += (y *= l) * r, data.vx -= x * (r = 1 - r), data.vy -= y * r);
}
return;
}
return x0 > xi + r || x1 < xi - r || y0 > yi + r || y1 < yi - r;
}
}
function prepare(quad) {
if (quad.data) return quad.r = radii[quad.data.index];
for(var i = quad.r = 0; i < 4; ++i)quad[i] && quad[i].r > quad.r && (quad.r = quad[i].r);
}
function initialize() {
if (nodes) {
var i, node, n = nodes.length;
for(i = 0, radii = Array(n); i < n; ++i)radii[(node = nodes[i]).index] = +radius(node, i, nodes);
}
}
return "function" != typeof radius && (radius = constant$7(null == radius ? 1 : +radius)), force.initialize = function(_nodes, _random) {
nodes = _nodes, random = _random, initialize();
}, force.iterations = function(_) {
return arguments.length ? (iterations = +_, force) : iterations;
}, force.strength = function(_) {
return arguments.length ? (strength = +_, force) : strength;
}, force.radius = function(_) {
return arguments.length ? (radius = "function" == typeof _ ? _ : constant$7(+_), initialize(), force) : radius;
}, force;
}, exports1.forceLink = function(links) {
var strengths, distances, nodes, count, bias, random, id = index$1, strength = function(link) {
return 1 / Math.min(count[link.source.index], count[link.target.index]);
}, distance = constant$7(30), iterations = 1;
function force(alpha) {
for(var k = 0, n = links.length; k < iterations; ++k)for(var link, source, target, x, y, l, b, i = 0; i < n; ++i)source = (link = links[i]).source, l = ((l = Math.sqrt((x = (target = link.target).x + target.vx - source.x - source.vx || jiggle(random)) * x + (y = target.y + target.vy - source.y - source.vy || jiggle(random)) * y)) - distances[i]) / l * alpha * strengths[i], x *= l, y *= l, target.vx -= x * (b = bias[i]), target.vy -= y * b, source.vx += x * (b = 1 - b), source.vy += y * b;
}
function initialize() {
if (nodes) {
var i, link, n = nodes.length, m = links.length, nodeById = new Map(nodes.map((d, i)=>[
id(d, i, nodes),
d
]));
for(i = 0, count = Array(n); i < m; ++i)(link = links[i]).index = i, "object" != typeof link.source && (link.source = find$1(nodeById, link.source)), "object" != typeof link.target && (link.target = find$1(nodeById, link.target)), count[link.source.index] = (count[link.source.index] || 0) + 1, count[link.target.index] = (count[link.target.index] || 0) + 1;
for(i = 0, bias = Array(m); i < m; ++i)link = links[i], bias[i] = count[link.source.index] / (count[link.source.index] + count[link.target.index]);
strengths = Array(m), initializeStrength(), distances = Array(m), initializeDistance();
}
}
function initializeStrength() {
if (nodes) for(var i = 0, n = links.length; i < n; ++i)strengths[i] = +strength(links[i], i, links);
}
function initializeDistance() {
if (nodes) for(var i = 0, n = links.length; i < n; ++i)distances[i] = +distance(links[i], i, links);
}
return null == links && (links = []), force.initialize = function(_nodes, _random) {
nodes = _nodes, random = _random, initialize();
}, force.links = function(_) {
return arguments.length ? (links = _, initialize(), force) : links;
}, force.id = function(_) {
return arguments.length ? (id = _, force) : id;
}, force.iterations = function(_) {
return arguments.length ? (iterations = +_, force) : iterations;
}, force.strength = function(_) {
return arguments.length ? (strength = "function" == typeof _ ? _ : constant$7(+_), initializeStrength(), force) : strength;
}, force.distance = function(_) {
return arguments.length ? (distance = "function" == typeof _ ? _ : constant$7(+_), initializeDistance(), force) : distance;
}, force;
}, exports1.forceManyBody = function() {
var nodes, node, random, alpha, strengths, strength = constant$7(-30), distanceMin2 = 1, distanceMax2 = 1 / 0, theta2 = 0.81;
function force(_) {
var i, n = nodes.length, tree = quadtree(nodes, x$1, y$1).visitAfter(accumulate);
for(alpha = _, i = 0; i < n; ++i)node = nodes[i], tree.visit(apply);
}
function initialize() {
if (nodes) {
var i, node, n = nodes.length;
for(i = 0, strengths = Array(n); i < n; ++i)strengths[(node = nodes[i]).index] = +strength(node, i, nodes);
}
}
function accumulate(quad) {
var q, c, x, y, i, strength = 0, weight = 0;
// For internal nodes, accumulate forces from child quadrants.
if (quad.length) {
for(x = y = i = 0; i < 4; ++i)(q = quad[i]) && (c = Math.abs(q.value)) && (strength += q.value, weight += c, x += c * q.x, y += c * q.y);
quad.x = x / weight, quad.y = y / weight;
} else {
(q = quad).x = q.data.x, q.y = q.data.y;
do strength += strengths[q.data.index];
while (q = q.next)
}
quad.value = strength;
}
function apply(quad, x1, _, x2) {
if (!quad.value) return !0;
var x = quad.x - node.x, y = quad.y - node.y, w = x2 - x1, l = x * x + y * y;
// Apply the Barnes-Hut approximation if possible.
// Limit forces for very close nodes; randomize direction if coincident.
if (w * w / theta2 < l) return l < distanceMax2 && (0 === x && (l += (x = jiggle(random)) * x), 0 === y && (l += (y = jiggle(random)) * y), l < distanceMin2 && (l = Math.sqrt(distanceMin2 * l)), node.vx += x * quad.value * alpha / l, node.vy += y * quad.value * alpha / l), !0;
if (!quad.length && !(l >= distanceMax2)) {
// Limit forces for very close nodes; randomize direction if coincident.
(quad.data !== node || quad.next) && (0 === x && (l += (x = jiggle(random)) * x), 0 === y && (l += (y = jiggle(random)) * y), l < distanceMin2 && (l = Math.sqrt(distanceMin2 * l)));
do quad.data !== node && (w = strengths[quad.data.index] * alpha / l, node.vx += x * w, node.vy += y * w);
while (quad = quad.next)
}
}
return force.initialize = function(_nodes, _random) {
nodes = _nodes, random = _random, initialize();
}, force.strength = function(_) {
return arguments.length ? (strength = "function" == typeof _ ? _ : constant$7(+_), initialize(), force) : strength;
}, force.distanceMin = function(_) {
return arguments.length ? (distanceMin2 = _ * _, force) : Math.sqrt(distanceMin2);
}, force.distanceMax = function(_) {
return arguments.length ? (distanceMax2 = _ * _, force) : Math.sqrt(distanceMax2);
}, force.theta = function(_) {
return arguments.length ? (theta2 = _ * _, force) : Math.sqrt(theta2);
}, force;
}, exports1.forceRadial = function(radius, x, y) {
var nodes, strengths, radiuses, strength = constant$7(0.1);
function force(alpha) {
for(var i = 0, n = nodes.length; i < n; ++i){
var node = nodes[i], dx = node.x - x || 1e-6, dy = node.y - y || 1e-6, r = Math.sqrt(dx * dx + dy * dy), k = (radiuses[i] - r) * strengths[i] * alpha / r;
node.vx += dx * k, node.vy += dy * k;
}
}
function initialize() {
if (nodes) {
var i, n = nodes.length;
for(i = 0, strengths = Array(n), radiuses = Array(n); i < n; ++i)radiuses[i] = +radius(nodes[i], i, nodes), strengths[i] = isNaN(radiuses[i]) ? 0 : +strength(nodes[i], i, nodes);
}
}
return "function" != typeof radius && (radius = constant$7(+radius)), null == x && (x = 0), null == y && (y = 0), force.initialize = function(_) {
nodes = _, initialize();
}, force.strength = function(_) {
return arguments.length ? (strength = "function" == typeof _ ? _ : constant$7(+_), initialize(), force) : strength;
}, force.radius = function(_) {
return arguments.length ? (radius = "function" == typeof _ ? _ : constant$7(+_), initialize(), force) : radius;
}, force.x = function(_) {
return arguments.length ? (x = +_, force) : x;
}, force.y = function(_) {
return arguments.length ? (y = +_, force) : y;
}, force;
}, exports1.forceSimulation = function(nodes) {
let s;
var simulation, alpha = 1, alphaMin = 0.001, alphaDecay = 1 - Math.pow(0.001, 1 / 300), alphaTarget = 0, velocityDecay = 0.6, forces = new Map(), stepper = timer(step), event = dispatch("tick", "end"), random = (s = 1, ()=>(s = (1664525 * s + 1013904223) % 4294967296) / 4294967296);
function step() {
tick(), event.call("tick", simulation), alpha < alphaMin && (stepper.stop(), event.call("end", simulation));
}
function tick(iterations) {
var i, node, n = nodes.length;
void 0 === iterations && (iterations = 1);
for(var k = 0; k < iterations; ++k)for(alpha += (alphaTarget - alpha) * alphaDecay, forces.forEach(function(force) {
force(alpha);
}), i = 0; i < n; ++i)null == (node = nodes[i]).fx ? node.x += node.vx *= velocityDecay : (node.x = node.fx, node.vx = 0), null == node.fy ? node.y += node.vy *= velocityDecay : (node.y = node.fy, node.vy = 0);
return simulation;
}
function initializeNodes() {
for(var node, i = 0, n = nodes.length; i < n; ++i){
if ((node = nodes[i]).index = i, null != node.fx && (node.x = node.fx), null != node.fy && (node.y = node.fy), isNaN(node.x) || isNaN(node.y)) {
var radius = 10 * Math.sqrt(0.5 + i), angle = i * initialAngle;
node.x = radius * Math.cos(angle), node.y = radius * Math.sin(angle);
}
(isNaN(node.vx) || isNaN(node.vy)) && (node.vx = node.vy = 0);
}
}
function initializeForce(force) {
return force.initialize && force.initialize(nodes, random), force;
}
return null == nodes && (nodes = []), initializeNodes(), simulation = {
tick: tick,
restart: function() {
return stepper.restart(step), simulation;
},
stop: function() {
return stepper.stop(), simulation;
},
nodes: function(_) {
return arguments.length ? (nodes = _, initializeNodes(), forces.forEach(initializeForce), simulation) : nodes;
},
alpha: function(_) {
return arguments.length ? (alpha = +_, simulation) : alpha;
},
alphaMin: function(_) {
return arguments.length ? (alphaMin = +_, simulation) : alphaMin;
},
alphaDecay: function(_) {
return arguments.length ? (alphaDecay = +_, simulation) : +alphaDecay;
},
alphaTarget: function(_) {
return arguments.length ? (alphaTarget = +_, simulation) : alphaTarget;
},
velocityDecay: function(_) {
return arguments.length ? (velocityDecay = 1 - _, simulation) : 1 - velocityDecay;
},
randomSource: function(_) {
return arguments.length ? (random = _, forces.forEach(initializeForce), simulation) : random;
},
force: function(name, _) {
return arguments.length > 1 ? (null == _ ? forces.delete(name) : forces.set(name, initializeForce(_)), simulation) : forces.get(name);
},
find: function(x, y, radius) {
var dx, dy, d2, node, closest, i = 0, n = nodes.length;
for(null == radius ? radius = 1 / 0 : radius *= radius, i = 0; i < n; ++i)(d2 = (dx = x - (node = nodes[i]).x) * dx + (dy = y - node.y) * dy) < radius && (closest = node, radius = d2);
return closest;
},
on: function(name, _) {
return arguments.length > 1 ? (event.on(name, _), simulation) : event.on(name);
}
};
}, exports1.forceX = function(x) {
var nodes, strengths, xz, strength = constant$7(0.1);
function force(alpha) {
for(var node, i = 0, n = nodes.length; i < n; ++i)node = nodes[i], node.vx += (xz[i] - node.x) * strengths[i] * alpha;
}
function initialize() {
if (nodes) {
var i, n = nodes.length;
for(i = 0, strengths = Array(n), xz = Array(n); i < n; ++i)strengths[i] = isNaN(xz[i] = +x(nodes[i], i, nodes)) ? 0 : +strength(nodes[i], i, nodes);
}
}
return "function" != typeof x && (x = constant$7(null == x ? 0 : +x)), force.initialize = function(_) {
nodes = _, initialize();
}, force.strength = function(_) {
return arguments.length ? (strength = "function" == typeof _ ? _ : constant$7(+_), initialize(), force) : strength;
}, force.x = function(_) {
return arguments.length ? (x = "function" == typeof _ ? _ : constant$7(+_), initialize(), force) : x;
}, force;
}, exports1.forceY = function(y) {
var nodes, strengths, yz, strength = constant$7(0.1);
function force(alpha) {
for(var node, i = 0, n = nodes.length; i < n; ++i)node = nodes[i], node.vy += (yz[i] - node.y) * strengths[i] * alpha;
}
function initialize() {
if (nodes) {
var i, n = nodes.length;
for(i = 0, strengths = Array(n), yz = Array(n); i < n; ++i)strengths[i] = isNaN(yz[i] = +y(nodes[i], i, nodes)) ? 0 : +strength(nodes[i], i, nodes);
}
}
return "function" != typeof y && (y = constant$7(null == y ? 0 : +y)), force.initialize = function(_) {
nodes = _, initialize();
}, force.strength = function(_) {
return arguments.length ? (strength = "function" == typeof _ ? _ : constant$7(+_), initialize(), force) : strength;
}, force.y = function(_) {
return arguments.length ? (y = "function" == typeof _ ? _ : constant$7(+_), initialize(), force) : y;
}, force;
}, exports1.formatDefaultLocale = defaultLocale, exports1.formatLocale = formatLocale, exports1.formatSpecifier = formatSpecifier, exports1.fsum = function(values, valueof) {
const adder = new Adder();
if (void 0 === valueof) for (let value of values)(value *= 1) && adder.add(value);
else {
let index = -1;
for (let value of values)(value = +valueof(value, ++index, values)) && adder.add(value);
}
return +adder;
}, exports1.geoAlbers = albers, exports1.geoAlbersUsa = // A composite projection for the United States, configured by default for
// 960×500. The projection also works quite well at 960×600 if you change the
// scale to 1285 and adjust the translate accordingly. The set of standard
// parallels for each region comes from USGS, which is published here:
// http://egsc.usgs.gov/isb/pubs/MapProjections/projections.html#albers
function() {
var cache, cacheStream, lower48Point, alaskaPoint, hawaiiPoint, point, lower48 = albers(), alaska = conicEqualArea().rotate([
154,
0
]).center([
-2,
58.5
]).parallels([
55,
65
]), hawaii = conicEqualArea().rotate([
157,
0
]).center([
-3,
19.9
]).parallels([
8,
18
]), pointStream = {
point: function(x, y) {
point = [
x,
y
];
}
};
function albersUsa(coordinates) {
var x = coordinates[0], y = coordinates[1];
return point = null, lower48Point.point(x, y), point || (alaskaPoint.point(x, y), point) || (hawaiiPoint.point(x, y), point);
}
function reset() {
return cache = cacheStream = null, albersUsa;
}
return albersUsa.invert = function(coordinates) {
var k = lower48.scale(), t = lower48.translate(), x = (coordinates[0] - t[0]) / k, y = (coordinates[1] - t[1]) / k;
return (y >= 0.120 && y < 0.234 && x >= -0.425 && x < -0.214 ? alaska : y >= 0.166 && y < 0.234 && x >= -0.214 && x < -0.115 ? hawaii : lower48).invert(coordinates);
}, albersUsa.stream = function(stream) {
var streams, n;
return cache && cacheStream === stream ? cache : (n = (streams = [
lower48.stream(cacheStream = stream),
alaska.stream(stream),
hawaii.stream(stream)
]).length, cache = {
point: function(x, y) {
for(var i = -1; ++i < n;)streams[i].point(x, y);
},
sphere: function() {
for(var i = -1; ++i < n;)streams[i].sphere();
},
lineStart: function() {
for(var i = -1; ++i < n;)streams[i].lineStart();
},
lineEnd: function() {
for(var i = -1; ++i < n;)streams[i].lineEnd();
},
polygonStart: function() {
for(var i = -1; ++i < n;)streams[i].polygonStart();
},
polygonEnd: function() {
for(var i = -1; ++i < n;)streams[i].polygonEnd();
}
});
}, albersUsa.precision = function(_) {
return arguments.length ? (lower48.precision(_), alaska.precision(_), hawaii.precision(_), reset()) : lower48.precision();
}, albersUsa.scale = function(_) {
return arguments.length ? (lower48.scale(_), alaska.scale(0.35 * _), hawaii.scale(_), albersUsa.translate(lower48.translate())) : lower48.scale();
}, albersUsa.translate = function(_) {
if (!arguments.length) return lower48.translate();
var k = lower48.scale(), x = +_[0], y = +_[1];
return lower48Point = lower48.translate(_).clipExtent([
[
x - 0.455 * k,
y - 0.238 * k
],
[
x + 0.455 * k,
y + 0.238 * k
]
]).stream(pointStream), alaskaPoint = alaska.translate([
x - 0.307 * k,
y + 0.201 * k
]).clipExtent([
[
x - 0.425 * k + 1e-6,
y + 0.120 * k + 1e-6
],
[
x - 0.214 * k - 1e-6,
y + 0.234 * k - 1e-6
]
]).stream(pointStream), hawaiiPoint = hawaii.translate([
x - 0.205 * k,
y + 0.212 * k
]).clipExtent([
[
x - 0.214 * k + 1e-6,
y + 0.166 * k + 1e-6
],
[
x - 0.115 * k - 1e-6,
y + 0.234 * k - 1e-6
]
]).stream(pointStream), reset();
}, albersUsa.fitExtent = function(extent, object) {
return fitExtent(albersUsa, extent, object);
}, albersUsa.fitSize = function(size, object) {
return fitSize(albersUsa, size, object);
}, albersUsa.fitWidth = function(width, object) {
return fitWidth(albersUsa, width, object);
}, albersUsa.fitHeight = function(height, object) {
return fitHeight(albersUsa, height, object);
}, albersUsa.scale(1070);
}, exports1.geoArea = function(object) {
return areaSum = new Adder(), geoStream(object, areaStream), 2 * areaSum;
}, exports1.geoAzimuthalEqualArea = function() {
return projection(azimuthalEqualAreaRaw).scale(124.75).clipAngle(179.999);
}, exports1.geoAzimuthalEqualAreaRaw = azimuthalEqualAreaRaw, exports1.geoAzimuthalEquidistant = function() {
return projection(azimuthalEquidistantRaw).scale(79.4188).clipAngle(179.999);
}, exports1.geoAzimuthalEquidistantRaw = azimuthalEquidistantRaw, exports1.geoBounds = function(feature) {
var i, n, a, b, merged, deltaMax, delta;
// First, sort ranges by their minimum longitudes.
if (phi1 = lambda1 = -(lambda0$1 = phi0 = 1 / 0), ranges = [], geoStream(feature, boundsStream), n = ranges.length) {
// Then, merge any ranges that overlap.
for(ranges.sort(rangeCompare), i = 1, merged = [
a = ranges[0]
]; i < n; ++i)rangeContains(a, (b = ranges[i])[0]) || rangeContains(a, b[1]) ? (angle(a[0], b[1]) > angle(a[0], a[1]) && (a[1] = b[1]), angle(b[0], a[1]) > angle(a[0], a[1]) && (a[0] = b[0])) : merged.push(a = b);
// Finally, find the largest gap between the merged ranges.
// The final bounding box will be the inverse of this gap.
for(deltaMax = -1 / 0, n = merged.length - 1, i = 0, a = merged[n]; i <= n; a = b, ++i)b = merged[i], (delta = angle(a[1], b[0])) > deltaMax && (deltaMax = delta, lambda0$1 = b[0], lambda1 = a[1]);
}
return ranges = range$1 = null, lambda0$1 === 1 / 0 || phi0 === 1 / 0 ? [
[
NaN,
NaN
],
[
NaN,
NaN
]
] : [
[
lambda0$1,
phi0
],
[
lambda1,
phi1
]
];
}, exports1.geoCentroid = function(object) {
W0 = W1 = X0 = Y0 = Z0 = X1 = Y1 = Z1 = 0, X2 = new Adder(), Y2 = new Adder(), Z2 = new Adder(), geoStream(object, centroidStream);
var x = +X2, y = +Y2, z = +Z2, m = hypot(x, y, z);
return(// If the area-weighted ccentroid is undefined, fall back to length-weighted ccentroid.
m < 1e-12 && (x = X1, y = Y1, z = Z1, W1 < 1e-6 && (x = X0, y = Y0, z = Z0), (m = hypot(x, y, z)) < 1e-12) ? [
NaN,
NaN
] : [
atan2(y, x) * degrees$2,
asin(z / m) * degrees$2
]);
}, exports1.geoCircle = function() {
var ring, rotate, center = constant$8([
0,
0
]), radius = constant$8(90), precision = constant$8(6), stream = {
point: function(x, y) {
ring.push(x = rotate(x, y)), x[0] *= degrees$2, x[1] *= degrees$2;
}
};
function circle() {
var c = center.apply(this, arguments), r = radius.apply(this, arguments) * radians$1, p = precision.apply(this, arguments) * radians$1;
return ring = [], rotate = rotateRadians(-c[0] * radians$1, -c[1] * radians$1, 0).invert, circleStream(stream, r, p, 1), c = {
type: "Polygon",
coordinates: [
ring
]
}, ring = rotate = null, c;
}
return circle.center = function(_) {
return arguments.length ? (center = "function" == typeof _ ? _ : constant$8([
+_[0],
+_[1]
]), circle) : center;
}, circle.radius = function(_) {
return arguments.length ? (radius = "function" == typeof _ ? _ : constant$8(+_), circle) : radius;
}, circle.precision = function(_) {
return arguments.length ? (precision = "function" == typeof _ ? _ : constant$8(+_), circle) : precision;
}, circle;
}, exports1.geoClipAntimeridian = clipAntimeridian, exports1.geoClipCircle = clipCircle, exports1.geoClipExtent = function() {
var cache, cacheStream, clip, x0 = 0, y0 = 0, x1 = 960, y1 = 500;
return clip = {
stream: function(stream) {
return cache && cacheStream === stream ? cache : cache = clipRectangle(x0, y0, x1, y1)(cacheStream = stream);
},
extent: function(_) {
return arguments.length ? (x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1], cache = cacheStream = null, clip) : [
[
x0,
y0
],
[
x1,
y1
]
];
}
};
}, exports1.geoClipRectangle = clipRectangle, exports1.geoConicConformal = function() {
return conicProjection(conicConformalRaw).scale(109.5).parallels([
30,
30
]);
}, exports1.geoConicConformalRaw = conicConformalRaw, exports1.geoConicEqualArea = conicEqualArea, exports1.geoConicEqualAreaRaw = conicEqualAreaRaw, exports1.geoConicEquidistant = function() {
return conicProjection(conicEquidistantRaw).scale(131.154).center([
0,
13.9389
]);
}, exports1.geoConicEquidistantRaw = conicEquidistantRaw, exports1.geoContains = function(object, point) {
return (object && containsObjectType.hasOwnProperty(object.type) ? containsObjectType[object.type] : containsGeometry)(object, point);
}, exports1.geoDistance = distance, exports1.geoEqualEarth = function() {
return projection(equalEarthRaw).scale(177.158);
}, exports1.geoEqualEarthRaw = equalEarthRaw, exports1.geoEquirectangular = function() {
return projection(equirectangularRaw).scale(152.63);
}, exports1.geoEquirectangularRaw = equirectangularRaw, exports1.geoGnomonic = function() {
return projection(gnomonicRaw).scale(144.049).clipAngle(60);
}, exports1.geoGnomonicRaw = gnomonicRaw, exports1.geoGraticule = graticule, exports1.geoGraticule10 = function() {
return graticule()();
}, exports1.geoIdentity = function() {
var ca, sa, y0, x1, y1, cache, cacheStream, k = 1, tx = 0, ty = 0, sx = 1, sy = 1, alpha = 0, x0 = null, kx = 1, ky = 1, transform = transformer({
point: function(x, y) {
var p = projection([
x,
y
]);
this.stream.point(p[0], p[1]);
}
}), postclip = identity$4;
function reset() {
return kx = k * sx, ky = k * sy, cache = cacheStream = null, projection;
}
function projection(p) {
var x = p[0] * kx, y = p[1] * ky;
if (alpha) {
var t = y * ca - x * sa;
x = x * ca + y * sa, y = t;
}
return [
x + tx,
y + ty
];
}
return projection.invert = function(p) {
var x = p[0] - tx, y = p[1] - ty;
if (alpha) {
var t = y * ca + x * sa;
x = x * ca - y * sa, y = t;
}
return [
x / kx,
y / ky
];
}, projection.stream = function(stream) {
return cache && cacheStream === stream ? cache : cache = transform(postclip(cacheStream = stream));
}, projection.postclip = function(_) {
return arguments.length ? (postclip = _, x0 = y0 = x1 = y1 = null, reset()) : postclip;
}, projection.clipExtent = function(_) {
return arguments.length ? (postclip = null == _ ? (x0 = y0 = x1 = y1 = null, identity$4) : clipRectangle(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]), reset()) : null == x0 ? null : [
[
x0,
y0
],
[
x1,
y1
]
];
}, projection.scale = function(_) {
return arguments.length ? (k = +_, reset()) : k;
}, projection.translate = function(_) {
return arguments.length ? (tx = +_[0], ty = +_[1], reset()) : [
tx,
ty
];
}, projection.angle = function(_) {
return arguments.length ? (sa = sin$1(alpha = _ % 360 * radians$1), ca = cos$1(alpha), reset()) : alpha * degrees$2;
}, projection.reflectX = function(_) {
return arguments.length ? (sx = _ ? -1 : 1, reset()) : sx < 0;
}, projection.reflectY = function(_) {
return arguments.length ? (sy = _ ? -1 : 1, reset()) : sy < 0;
}, projection.fitExtent = function(extent, object) {
return fitExtent(projection, extent, object);
}, projection.fitSize = function(size, object) {
return fitSize(projection, size, object);
}, projection.fitWidth = function(width, object) {
return fitWidth(projection, width, object);
}, projection.fitHeight = function(height, object) {
return fitHeight(projection, height, object);
}, projection;
}, exports1.geoInterpolate = function(a, b) {
var x, x1, x0 = a[0] * radians$1, y0 = a[1] * radians$1, x11 = b[0] * radians$1, y1 = b[1] * radians$1, cy0 = cos$1(y0), sy0 = sin$1(y0), cy1 = cos$1(y1), sy1 = sin$1(y1), kx0 = cy0 * cos$1(x0), ky0 = cy0 * sin$1(x0), kx1 = cy1 * cos$1(x11), ky1 = cy1 * sin$1(x11), d = 2 * asin(sqrt((x = sin$1((x = y1 - y0) / 2)) * x + cy0 * cy1 * ((x1 = sin$1((x1 = x11 - x0) / 2)) * x1))), k = sin$1(d), interpolate = d ? function(t) {
var B = sin$1(t *= d) / k, A = sin$1(d - t) / k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1;
return [
atan2(y, x) * degrees$2,
atan2(A * sy0 + B * sy1, sqrt(x * x + y * y)) * degrees$2
];
} : function() {
return [
x0 * degrees$2,
y0 * degrees$2
];
};
return interpolate.distance = d, interpolate;
}, exports1.geoLength = length$2, exports1.geoMercator = function() {
return mercatorProjection(mercatorRaw).scale(961 / tau$4);
}, exports1.geoMercatorRaw = mercatorRaw, exports1.geoNaturalEarth1 = function() {
return projection(naturalEarth1Raw).scale(175.295);
}, exports1.geoNaturalEarth1Raw = naturalEarth1Raw, exports1.geoOrthographic = function() {
return projection(orthographicRaw).scale(249.5).clipAngle(90.000001);
}, exports1.geoOrthographicRaw = orthographicRaw, exports1.geoPath = function(projection, context) {
var projectionStream, contextStream, pointRadius = 4.5;
function path(object) {
return object && ("function" == typeof pointRadius && contextStream.pointRadius(+pointRadius.apply(this, arguments)), geoStream(object, projectionStream(contextStream))), contextStream.result();
}
return path.area = function(object) {
return geoStream(object, projectionStream(areaStream$1)), areaStream$1.result();
}, path.measure = function(object) {
return geoStream(object, projectionStream(lengthStream$1)), lengthStream$1.result();
}, path.bounds = function(object) {
return geoStream(object, projectionStream(boundsStream$1)), boundsStream$1.result();
}, path.centroid = function(object) {
return geoStream(object, projectionStream(centroidStream$1)), centroidStream$1.result();
}, path.projection = function(_) {
return arguments.length ? (projectionStream = null == _ ? (projection = null, identity$4) : (projection = _).stream, path) : projection;
}, path.context = function(_) {
return arguments.length ? (contextStream = null == _ ? (context = null, new PathString) : new PathContext(context = _), "function" != typeof pointRadius && contextStream.pointRadius(pointRadius), path) : context;
}, path.pointRadius = function(_) {
return arguments.length ? (pointRadius = "function" == typeof _ ? _ : (contextStream.pointRadius(+_), +_), path) : pointRadius;
}, path.projection(projection).context(context);
}, exports1.geoProjection = projection, exports1.geoProjectionMutator = projectionMutator, exports1.geoRotation = rotation, exports1.geoStereographic = function() {
return projection(stereographicRaw).scale(250).clipAngle(142);
}, exports1.geoStereographicRaw = stereographicRaw, exports1.geoStream = geoStream, exports1.geoTransform = function(methods) {
return {
stream: transformer(methods)
};
}, exports1.geoTransverseMercator = function() {
var m = mercatorProjection(transverseMercatorRaw), center = m.center, rotate = m.rotate;
return m.center = function(_) {
return arguments.length ? center([
-_[1],
_[0]
]) : [
(_ = center())[1],
-_[0]
];
}, m.rotate = function(_) {
return arguments.length ? rotate([
_[0],
_[1],
_.length > 2 ? _[2] + 90 : 90
]) : [
(_ = rotate())[0],
_[1],
_[2] - 90
];
}, rotate([
0,
0,
90
]).scale(159.155);
}, exports1.geoTransverseMercatorRaw = transverseMercatorRaw, exports1.gray = function(l, opacity) {
return new Lab(l, 0, 0, null == opacity ? 1 : opacity);
}, exports1.greatest = function(values, compare = ascending) {
let max;
let defined = !1;
if (1 === compare.length) {
let maxValue;
for (const element of values){
const value = compare(element);
(defined ? ascending(value, maxValue) > 0 : 0 === ascending(value, value)) && (max = element, maxValue = value, defined = !0);
}
} else for (const value of values)(defined ? compare(value, max) > 0 : 0 === compare(value, value)) && (max = value, defined = !0);
return max;
}, exports1.greatestIndex = function(values, compare = ascending) {
let maxValue;
if (1 === compare.length) return maxIndex(values, compare);
let max = -1, index = -1;
for (const value of values)++index, (max < 0 ? 0 === compare(value, value) : compare(value, maxValue) > 0) && (maxValue = value, max = index);
return max;
}, exports1.group = function(values, ...keys) {
return nest(values, identity, identity, keys);
}, exports1.groups = function(values, ...keys) {
return nest(values, Array.from, identity, keys);
}, exports1.hcl = hcl, exports1.hierarchy = hierarchy, exports1.histogram = bin, exports1.hsl = hsl, exports1.html = html, exports1.image = function(input, init) {
return new Promise(function(resolve, reject) {
var image = new Image;
for(var key in init)image[key] = init[key];
image.onerror = reject, image.onload = function() {
resolve(image);
}, image.src = input;
});
}, exports1.index = function(values, ...keys) {
return nest(values, identity, unique, keys);
}, exports1.indexes = function(values, ...keys) {
return nest(values, Array.from, unique, keys);
}, exports1.interpolate = interpolate, exports1.interpolateArray = function(a, b) {
return (isNumberArray(b) ? numberArray : genericArray)(a, b);
}, exports1.interpolateBasis = basis$1, exports1.interpolateBasisClosed = basisClosed, exports1.interpolateBlues = Blues, exports1.interpolateBrBG = BrBG, exports1.interpolateBuGn = BuGn, exports1.interpolateBuPu = BuPu, exports1.interpolateCividis = function(t) {
return "rgb(" + Math.max(0, Math.min(255, Math.round(-4.54 - (t = Math.max(0, Math.min(1, t))) * (35.34 - t * (2381.73 - t * (6402.7 - t * (7024.72 - 2710.57 * t))))))) + ", " + Math.max(0, Math.min(255, Math.round(32.49 + t * (170.73 + t * (52.82 - t * (131.46 - t * (176.58 - 67.37 * t))))))) + ", " + Math.max(0, Math.min(255, Math.round(81.24 + t * (442.36 - t * (2482.43 - t * (6167.24 - t * (6614.94 - 2475.67 * t))))))) + ")";
}, exports1.interpolateCool = cool, exports1.interpolateCubehelix = cubehelix$2, exports1.interpolateCubehelixDefault = cubehelix$3, exports1.interpolateCubehelixLong = cubehelixLong, exports1.interpolateDate = date, exports1.interpolateDiscrete = function(range) {
var n = range.length;
return function(t) {
return range[Math.max(0, Math.min(n - 1, Math.floor(t * n)))];
};
}, exports1.interpolateGnBu = GnBu, exports1.interpolateGreens = Greens, exports1.interpolateGreys = Greys, exports1.interpolateHcl = hcl$2, exports1.interpolateHclLong = hclLong, exports1.interpolateHsl = hsl$2, exports1.interpolateHslLong = hslLong, exports1.interpolateHue = function(a, b) {
var i = hue(+a, +b);
return function(t) {
var x = i(t);
return x - 360 * Math.floor(x / 360);
};
}, exports1.interpolateInferno = inferno, exports1.interpolateLab = function(start, end) {
var l = nogamma((start = lab(start)).l, (end = lab(end)).l), a = nogamma(start.a, end.a), b = nogamma(start.b, end.b), opacity = nogamma(start.opacity, end.opacity);
return function(t) {
return start.l = l(t), start.a = a(t), start.b = b(t), start.opacity = opacity(t), start + "";
};
}, exports1.interpolateMagma = magma, exports1.interpolateNumber = interpolateNumber, exports1.interpolateNumberArray = numberArray, exports1.interpolateObject = object, exports1.interpolateOrRd = OrRd, exports1.interpolateOranges = Oranges, exports1.interpolatePRGn = PRGn, exports1.interpolatePiYG = PiYG, exports1.interpolatePlasma = plasma, exports1.interpolatePuBu = PuBu, exports1.interpolatePuBuGn = PuBuGn, exports1.interpolatePuOr = PuOr, exports1.interpolatePuRd = PuRd, exports1.interpolatePurples = Purples, exports1.interpolateRainbow = function(t) {
(t < 0 || t > 1) && (t -= Math.floor(t));
var ts = Math.abs(t - 0.5);
return c$1.h = 360 * t - 100, c$1.s = 1.5 - 1.5 * ts, c$1.l = 0.8 - 0.9 * ts, c$1 + "";
}, exports1.interpolateRdBu = RdBu, exports1.interpolateRdGy = RdGy, exports1.interpolateRdPu = RdPu, exports1.interpolateRdYlBu = RdYlBu, exports1.interpolateRdYlGn = RdYlGn, exports1.interpolateReds = Reds, exports1.interpolateRgb = interpolateRgb, exports1.interpolateRgbBasis = rgbBasis, exports1.interpolateRgbBasisClosed = rgbBasisClosed, exports1.interpolateRound = interpolateRound, exports1.interpolateSinebow = function(t) {
var x;
return c$2.r = 255 * (x = Math.sin(t = (0.5 - t) * Math.PI)) * x, c$2.g = 255 * (x = Math.sin(t + pi_1_3)) * x, c$2.b = 255 * (x = Math.sin(t + pi_2_3)) * x, c$2 + "";
}, exports1.interpolateSpectral = Spectral, exports1.interpolateString = interpolateString, exports1.interpolateTransformCss = interpolateTransformCss, exports1.interpolateTransformSvg = interpolateTransformSvg, exports1.interpolateTurbo = function(t) {
return "rgb(" + Math.max(0, Math.min(255, Math.round(34.61 + (t = Math.max(0, Math.min(1, t))) * (1172.33 - t * (10793.56 - t * (33300.12 - t * (38394.49 - 14825.05 * t))))))) + ", " + Math.max(0, Math.min(255, Math.round(23.31 + t * (557.33 + t * (1225.33 - t * (3574.96 - t * (1073.77 + 707.56 * t))))))) + ", " + Math.max(0, Math.min(255, Math.round(27.2 + t * (3211.1 - t * (15327.97 - t * (27814 - t * (22569.18 - 6838.66 * t))))))) + ")";
}, exports1.interpolateViridis = viridis, exports1.interpolateWarm = warm, exports1.interpolateYlGn = YlGn, exports1.interpolateYlGnBu = YlGnBu, exports1.interpolateYlOrBr = YlOrBr, exports1.interpolateYlOrRd = YlOrRd, exports1.interpolateZoom = interpolateZoom, exports1.interrupt = interrupt, exports1.intersection = function(values, ...others) {
values = new Set(values), others = others.map(set);
out: for (const value of values)for (const other of others)if (!other.has(value)) {
values.delete(value);
continue out;
}
return values;
}, exports1.interval = function(callback, delay, time) {
var t = new Timer, total = delay;
return null == delay || (t._restart = t.restart, t.restart = function(callback, delay, time) {
delay *= 1, time = null == time ? now() : +time, t._restart(function tick(elapsed) {
elapsed += total, t._restart(tick, total += delay, time), callback(elapsed);
}, delay, time);
}), t.restart(callback, delay, time), t;
}, exports1.isoFormat = formatIso, exports1.isoParse = parseIso, exports1.json = function(input, init) {
return fetch(input, init).then(responseJson);
}, exports1.lab = lab, exports1.lch = function(l, c, h, opacity) {
return 1 == arguments.length ? hclConvert(l) : new Hcl(h, c, l, null == opacity ? 1 : opacity);
}, exports1.least = function(values, compare = ascending) {
let min;
let defined = !1;
if (1 === compare.length) {
let minValue;
for (const element of values){
const value = compare(element);
(defined ? 0 > ascending(value, minValue) : 0 === ascending(value, value)) && (min = element, minValue = value, defined = !0);
}
} else for (const value of values)(defined ? 0 > compare(value, min) : 0 === compare(value, value)) && (min = value, defined = !0);
return min;
}, exports1.leastIndex = leastIndex, exports1.line = line, exports1.lineRadial = lineRadial$1, exports1.linkHorizontal = function() {
return link$2(curveHorizontal);
}, exports1.linkRadial = function() {
var l = link$2(curveRadial$1);
return l.angle = l.x, delete l.x, l.radius = l.y, delete l.y, l;
}, exports1.linkVertical = function() {
return link$2(curveVertical);
}, exports1.local = local, exports1.map = function(values, mapper) {
if ("function" != typeof values[Symbol.iterator]) throw TypeError("values is not iterable");
if ("function" != typeof mapper) throw TypeError("mapper is not a function");
return Array.from(values, (value, index)=>mapper(value, index, values));
}, exports1.matcher = matcher, exports1.max = max, exports1.maxIndex = maxIndex, exports1.mean = function(values, valueof) {
let count = 0, sum = 0;
if (void 0 === valueof) for (let value of values)null != value && (value *= 1) >= value && (++count, sum += value);
else {
let index = -1;
for (let value of values)null != (value = valueof(value, ++index, values)) && (value *= 1) >= value && (++count, sum += value);
}
if (count) return sum / count;
}, exports1.median = function(values, valueof) {
return quantile(values, 0.5, valueof);
}, exports1.merge = merge, exports1.min = min, exports1.minIndex = minIndex, exports1.namespace = namespace, exports1.namespaces = namespaces, exports1.nice = nice, exports1.now = now, exports1.pack = function() {
var radius = null, dx = 1, dy = 1, padding = constantZero;
function pack(root) {
return root.x = dx / 2, root.y = dy / 2, radius ? root.eachBefore(radiusLeaf(radius)).eachAfter(packChildren(padding, 0.5)).eachBefore(translateChild(1)) : root.eachBefore(radiusLeaf(defaultRadius$1)).eachAfter(packChildren(constantZero, 1)).eachAfter(packChildren(padding, root.r / Math.min(dx, dy))).eachBefore(translateChild(Math.min(dx, dy) / (2 * root.r))), root;
}
return pack.radius = function(x) {
return arguments.length ? (radius = null == x ? null : required(x), pack) : radius;
}, pack.size = function(x) {
return arguments.length ? (dx = +x[0], dy = +x[1], pack) : [
dx,
dy
];
}, pack.padding = function(x) {
return arguments.length ? (padding = "function" == typeof x ? x : constant$9(+x), pack) : padding;
}, pack;
}, exports1.packEnclose = enclose, exports1.packSiblings = function(circles) {
return packEnclose(circles), circles;
}, exports1.pairs = function(values, pairof = pair) {
let previous;
const pairs = [];
let first = !1;
for (const value of values)first && pairs.push(pairof(previous, value)), previous = value, first = !0;
return pairs;
}, exports1.partition = function() {
var dx = 1, dy = 1, padding = 0, round = !1;
function partition(root) {
var dy1, n = root.height + 1;
return root.x0 = root.y0 = padding, root.x1 = dx, root.y1 = dy / n, root.eachBefore((dy1 = dy, function(node) {
node.children && treemapDice(node, node.x0, dy1 * (node.depth + 1) / n, node.x1, dy1 * (node.depth + 2) / n);
var x0 = node.x0, y0 = node.y0, x1 = node.x1 - padding, y1 = node.y1 - padding;
x1 < x0 && (x0 = x1 = (x0 + x1) / 2), y1 < y0 && (y0 = y1 = (y0 + y1) / 2), node.x0 = x0, node.y0 = y0, node.x1 = x1, node.y1 = y1;
})), round && root.eachBefore(roundNode), root;
}
return partition.round = function(x) {
return arguments.length ? (round = !!x, partition) : round;
}, partition.size = function(x) {
return arguments.length ? (dx = +x[0], dy = +x[1], partition) : [
dx,
dy
];
}, partition.padding = function(x) {
return arguments.length ? (padding = +x, partition) : padding;
}, partition;
}, exports1.path = path, exports1.permute = permute, exports1.pie = function() {
var value = identity$8, sortValues = descending$1, sort = null, startAngle = constant$a(0), endAngle = constant$a(tau$5), padAngle = constant$a(0);
function pie(data) {
var i, j, k, a1, v, n = (data = array$5(data)).length, sum = 0, index = Array(n), arcs = Array(n), a0 = +startAngle.apply(this, arguments), da = Math.min(tau$5, Math.max(-tau$5, endAngle.apply(this, arguments) - a0)), p = Math.min(Math.abs(da) / n, padAngle.apply(this, arguments)), pa = p * (da < 0 ? -1 : 1);
for(i = 0; i < n; ++i)(v = arcs[index[i] = i] = +value(data[i], i, data)) > 0 && (sum += v);
// Compute the arcs! They are stored in the original data's order.
for(null != sortValues ? index.sort(function(i, j) {
return sortValues(arcs[i], arcs[j]);
}) : null != sort && index.sort(function(i, j) {
return sort(data[i], data[j]);
}), i = 0, k = sum ? (da - n * pa) / sum : 0; i < n; ++i, a0 = a1)a1 = a0 + ((v = arcs[j = index[i]]) > 0 ? v * k : 0) + pa, arcs[j] = {
data: data[j],
index: i,
value: v,
startAngle: a0,
endAngle: a1,
padAngle: p
};
return arcs;
}
return pie.value = function(_) {
return arguments.length ? (value = "function" == typeof _ ? _ : constant$a(+_), pie) : value;
}, pie.sortValues = function(_) {
return arguments.length ? (sortValues = _, sort = null, pie) : sortValues;
}, pie.sort = function(_) {
return arguments.length ? (sort = _, sortValues = null, pie) : sort;
}, pie.startAngle = function(_) {
return arguments.length ? (startAngle = "function" == typeof _ ? _ : constant$a(+_), pie) : startAngle;
}, pie.endAngle = function(_) {
return arguments.length ? (endAngle = "function" == typeof _ ? _ : constant$a(+_), pie) : endAngle;
}, pie.padAngle = function(_) {
return arguments.length ? (padAngle = "function" == typeof _ ? _ : constant$a(+_), pie) : padAngle;
}, pie;
}, exports1.piecewise = piecewise, exports1.pointRadial = pointRadial, exports1.pointer = pointer, exports1.pointers = function(events, node) {
return events.target && (events = sourceEvent(events), void 0 === node && (node = events.currentTarget), events = events.touches || [
events
]), Array.from(events, (event)=>pointer(event, node));
}, exports1.polygonArea = function(polygon) {
for(var a, i = -1, n = polygon.length, b = polygon[n - 1], area = 0; ++i < n;)a = b, b = polygon[i], area += a[1] * b[0] - a[0] * b[1];
return area / 2;
}, exports1.polygonCentroid = function(polygon) {
for(var a, c, i = -1, n = polygon.length, x = 0, y = 0, b = polygon[n - 1], k = 0; ++i < n;)a = b, b = polygon[i], k += c = a[0] * b[1] - b[0] * a[1], x += (a[0] + b[0]) * c, y += (a[1] + b[1]) * c;
return [
x / (k *= 3),
y / k
];
}, exports1.polygonContains = function(polygon, point) {
for(var x1, y1, n = polygon.length, p = polygon[n - 1], x = point[0], y = point[1], x0 = p[0], y0 = p[1], inside = !1, i = 0; i < n; ++i)x1 = (p = polygon[i])[0], (y1 = p[1]) > y != y0 > y && x < (x0 - x1) * (y - y1) / (y0 - y1) + x1 && (inside = !inside), x0 = x1, y0 = y1;
return inside;
}, exports1.polygonHull = function(points) {
if ((n = points.length) < 3) return null;
var i, n, sortedPoints = Array(n), flippedPoints = Array(n);
for(i = 0; i < n; ++i)sortedPoints[i] = [
+points[i][0],
+points[i][1],
i
];
for(sortedPoints.sort(lexicographicOrder), i = 0; i < n; ++i)flippedPoints[i] = [
sortedPoints[i][0],
-sortedPoints[i][1]
];
var upperIndexes = computeUpperHullIndexes(sortedPoints), lowerIndexes = computeUpperHullIndexes(flippedPoints), skipLeft = lowerIndexes[0] === upperIndexes[0], skipRight = lowerIndexes[lowerIndexes.length - 1] === upperIndexes[upperIndexes.length - 1], hull = [];
// Add upper hull in right-to-l order.
// Then add lower hull in left-to-right order.
for(i = upperIndexes.length - 1; i >= 0; --i)hull.push(points[sortedPoints[upperIndexes[i]][2]]);
for(i = +skipLeft; i < lowerIndexes.length - skipRight; ++i)hull.push(points[sortedPoints[lowerIndexes[i]][2]]);
return hull;
}, exports1.polygonLength = function(polygon) {
for(var xa, ya, i = -1, n = polygon.length, b = polygon[n - 1], xb = b[0], yb = b[1], perimeter = 0; ++i < n;)xa = xb, ya = yb, xb = (b = polygon[i])[0], yb = b[1], xa -= xb, ya -= yb, perimeter += Math.hypot(xa, ya);
return perimeter;
}, exports1.precisionFixed = precisionFixed, exports1.precisionPrefix = precisionPrefix, exports1.precisionRound = precisionRound, exports1.quadtree = quadtree, exports1.quantile = quantile, exports1.quantileSorted = quantileSorted, exports1.quantize = function(interpolator, n) {
for(var samples = Array(n), i = 0; i < n; ++i)samples[i] = interpolator(i / (n - 1));
return samples;
}, exports1.quickselect = quickselect, exports1.radialArea = areaRadial, exports1.radialLine = lineRadial$1, exports1.randomBates = bates, exports1.randomBernoulli = bernoulli, exports1.randomBeta = beta, exports1.randomBinomial = binomial, exports1.randomCauchy = cauchy, exports1.randomExponential = exponential$1, exports1.randomGamma = gamma$1, exports1.randomGeometric = geometric, exports1.randomInt = int, exports1.randomIrwinHall = irwinHall, exports1.randomLcg = function(seed = Math.random()) {
let state = (0 <= seed && seed < 1 ? seed / eps : Math.abs(seed)) | 0;
return ()=>eps * ((state = 0x19660D * state + 0x3C6EF35F | 0) >>> 0);
}, exports1.randomLogNormal = logNormal, exports1.randomLogistic = logistic, exports1.randomNormal = normal, exports1.randomPareto = pareto, exports1.randomPoisson = poisson, exports1.randomUniform = uniform, exports1.randomWeibull = weibull, exports1.range = sequence, exports1.reduce = function(values, reducer, value) {
if ("function" != typeof reducer) throw TypeError("reducer is not a function");
const iterator = values[Symbol.iterator]();
let done, next, index = -1;
if (arguments.length < 3) {
if ({ done, value } = iterator.next(), done) return;
++index;
}
for(; { done, value: next } = iterator.next(), !done;)value = reducer(value, next, ++index, values);
return value;
}, exports1.reverse = function(values) {
if ("function" != typeof values[Symbol.iterator]) throw TypeError("values is not iterable");
return Array.from(values).reverse();
}, exports1.rgb = rgb, exports1.ribbon = function() {
return ribbon();
}, exports1.ribbonArrow = function() {
return ribbon(defaultArrowheadRadius);
}, exports1.rollup = function(values, reduce, ...keys) {
return nest(values, identity, reduce, keys);
}, exports1.rollups = function(values, reduce, ...keys) {
return nest(values, Array.from, reduce, keys);
}, exports1.scaleBand = band, exports1.scaleDiverging = function diverging() {
var scale = linearish(transformer$3()(identity$6));
return scale.copy = function() {
return copy$1(scale, diverging());
}, initInterpolator.apply(scale, arguments);
}, exports1.scaleDivergingLog = function divergingLog() {
var scale = loggish(transformer$3()).domain([
0.1,
1,
10
]);
return scale.copy = function() {
return copy$1(scale, divergingLog()).base(scale.base());
}, initInterpolator.apply(scale, arguments);
}, exports1.scaleDivergingPow = divergingPow, exports1.scaleDivergingSqrt = function() {
return divergingPow.apply(null, arguments).exponent(0.5);
}, exports1.scaleDivergingSymlog = function divergingSymlog() {
var scale = symlogish(transformer$3());
return scale.copy = function() {
return copy$1(scale, divergingSymlog()).constant(scale.constant());
}, initInterpolator.apply(scale, arguments);
}, exports1.scaleIdentity = function identity$7(domain) {
var unknown;
function scale(x) {
return isNaN(x *= 1) ? unknown : x;
}
return scale.invert = scale, scale.domain = scale.range = function(_) {
return arguments.length ? (domain = Array.from(_, number$2), scale) : domain.slice();
}, scale.unknown = function(_) {
return arguments.length ? (unknown = _, scale) : unknown;
}, scale.copy = function() {
return identity$7(domain).unknown(unknown);
}, domain = arguments.length ? Array.from(domain, number$2) : [
0,
1
], linearish(scale);
}, exports1.scaleImplicit = implicit, exports1.scaleLinear = function linear$2() {
var scale = continuous();
return scale.copy = function() {
return copy(scale, linear$2());
}, initRange.apply(scale, arguments), linearish(scale);
}, exports1.scaleLog = function log$1() {
var scale = loggish(transformer$1()).domain([
1,
10
]);
return scale.copy = function() {
return copy(scale, log$1()).base(scale.base());
}, initRange.apply(scale, arguments), scale;
}, exports1.scaleOrdinal = ordinal, exports1.scalePoint = function() {
return function pointish(scale) {
var copy = scale.copy;
return scale.padding = scale.paddingOuter, delete scale.paddingInner, delete scale.paddingOuter, scale.copy = function() {
return pointish(copy());
}, scale;
}(band.apply(null, arguments).paddingInner(1));
}, exports1.scalePow = pow$2, exports1.scaleQuantile = function quantile$1() {
var unknown, domain = [], range = [], thresholds = [];
function rescale() {
var i = 0, n = Math.max(1, range.length);
for(thresholds = Array(n - 1); ++i < n;)thresholds[i - 1] = quantileSorted(domain, i / n);
return scale;
}
function scale(x) {
return isNaN(x *= 1) ? unknown : range[bisectRight(thresholds, x)];
}
return scale.invertExtent = function(y) {
var i = range.indexOf(y);
return i < 0 ? [
NaN,
NaN
] : [
i > 0 ? thresholds[i - 1] : domain[0],
i < thresholds.length ? thresholds[i] : domain[domain.length - 1]
];
}, scale.domain = function(_) {
if (!arguments.length) return domain.slice();
for (let d of (domain = [], _))null == d || isNaN(d *= 1) || domain.push(d);
return domain.sort(ascending), rescale();
}, scale.range = function(_) {
return arguments.length ? (range = Array.from(_), rescale()) : range.slice();
}, scale.unknown = function(_) {
return arguments.length ? (unknown = _, scale) : unknown;
}, scale.quantiles = function() {
return thresholds.slice();
}, scale.copy = function() {
return quantile$1().domain(domain).range(range).unknown(unknown);
}, initRange.apply(scale, arguments);
}, exports1.scaleQuantize = function quantize$1() {
var unknown, x0 = 0, x1 = 1, n = 1, domain = [
0.5
], range = [
0,
1
];
function scale(x) {
return x <= x ? range[bisectRight(domain, x, 0, n)] : unknown;
}
function rescale() {
var i = -1;
for(domain = Array(n); ++i < n;)domain[i] = ((i + 1) * x1 - (i - n) * x0) / (n + 1);
return scale;
}
return scale.domain = function(_) {
return arguments.length ? ([x0, x1] = _, x0 *= 1, x1 *= 1, rescale()) : [
x0,
x1
];
}, scale.range = function(_) {
return arguments.length ? (n = (range = Array.from(_)).length - 1, rescale()) : range.slice();
}, scale.invertExtent = function(y) {
var i = range.indexOf(y);
return i < 0 ? [
NaN,
NaN
] : i < 1 ? [
x0,
domain[0]
] : i >= n ? [
domain[n - 1],
x1
] : [
domain[i - 1],
domain[i]
];
}, scale.unknown = function(_) {
return arguments.length && (unknown = _), scale;
}, scale.thresholds = function() {
return domain.slice();
}, scale.copy = function() {
return quantize$1().domain([
x0,
x1
]).range(range).unknown(unknown);
}, initRange.apply(linearish(scale), arguments);
}, exports1.scaleRadial = function radial$1() {
var unknown, squared = continuous(), range = [
0,
1
], round = !1;
function scale(x) {
var x1, y = Math.sign(x1 = squared(x)) * Math.sqrt(Math.abs(x1));
return isNaN(y) ? unknown : round ? Math.round(y) : y;
}
return scale.invert = function(y) {
return squared.invert(square(y));
}, scale.domain = function(_) {
return arguments.length ? (squared.domain(_), scale) : squared.domain();
}, scale.range = function(_) {
return arguments.length ? (squared.range((range = Array.from(_, number$2)).map(square)), scale) : range.slice();
}, scale.rangeRound = function(_) {
return scale.range(_).round(!0);
}, scale.round = function(_) {
return arguments.length ? (round = !!_, scale) : round;
}, scale.clamp = function(_) {
return arguments.length ? (squared.clamp(_), scale) : squared.clamp();
}, scale.unknown = function(_) {
return arguments.length ? (unknown = _, scale) : unknown;
}, scale.copy = function() {
return radial$1(squared.domain(), range).round(round).clamp(squared.clamp()).unknown(unknown);
}, initRange.apply(scale, arguments), linearish(scale);
}, exports1.scaleSequential = function sequential() {
var scale = linearish(transformer$2()(identity$6));
return scale.copy = function() {
return copy$1(scale, sequential());
}, initInterpolator.apply(scale, arguments);
}, exports1.scaleSequentialLog = function sequentialLog() {
var scale = loggish(transformer$2()).domain([
1,
10
]);
return scale.copy = function() {
return copy$1(scale, sequentialLog()).base(scale.base());
}, initInterpolator.apply(scale, arguments);
}, exports1.scaleSequentialPow = sequentialPow, exports1.scaleSequentialQuantile = function sequentialQuantile() {
var domain = [], interpolator = identity$6;
function scale(x) {
if (!isNaN(x *= 1)) return interpolator((bisectRight(domain, x, 1) - 1) / (domain.length - 1));
}
return scale.domain = function(_) {
if (!arguments.length) return domain.slice();
for (let d of (domain = [], _))null == d || isNaN(d *= 1) || domain.push(d);
return domain.sort(ascending), scale;
}, scale.interpolator = function(_) {
return arguments.length ? (interpolator = _, scale) : interpolator;
}, scale.range = function() {
return domain.map((d, i)=>interpolator(i / (domain.length - 1)));
}, scale.quantiles = function(n) {
return Array.from({
length: n + 1
}, (_, i)=>quantile(domain, i / n));
}, scale.copy = function() {
return sequentialQuantile(interpolator).domain(domain);
}, initInterpolator.apply(scale, arguments);
}, exports1.scaleSequentialSqrt = function() {
return sequentialPow.apply(null, arguments).exponent(0.5);
}, exports1.scaleSequentialSymlog = function sequentialSymlog() {
var scale = symlogish(transformer$2());
return scale.copy = function() {
return copy$1(scale, sequentialSymlog()).constant(scale.constant());
}, initInterpolator.apply(scale, arguments);
}, exports1.scaleSqrt = function() {
return pow$2.apply(null, arguments).exponent(0.5);
}, exports1.scaleSymlog = function symlog() {
var scale = symlogish(transformer$1());
return scale.copy = function() {
return copy(scale, symlog()).constant(scale.constant());
}, initRange.apply(scale, arguments);
}, exports1.scaleThreshold = function threshold() {
var unknown, domain = [
0.5
], range = [
0,
1
], n = 1;
function scale(x) {
return x <= x ? range[bisectRight(domain, x, 0, n)] : unknown;
}
return scale.domain = function(_) {
return arguments.length ? (n = Math.min((domain = Array.from(_)).length, range.length - 1), scale) : domain.slice();
}, scale.range = function(_) {
return arguments.length ? (range = Array.from(_), n = Math.min(domain.length, range.length - 1), scale) : range.slice();
}, scale.invertExtent = function(y) {
var i = range.indexOf(y);
return [
domain[i - 1],
domain[i]
];
}, scale.unknown = function(_) {
return arguments.length ? (unknown = _, scale) : unknown;
}, scale.copy = function() {
return threshold().domain(domain).range(range).unknown(unknown);
}, initRange.apply(scale, arguments);
}, exports1.scaleTime = function() {
return initRange.apply(calendar(year, month, sunday, day, hour, minute, second, millisecond, exports1.timeFormat).domain([
new Date(2000, 0, 1),
new Date(2000, 0, 2)
]), arguments);
}, exports1.scaleUtc = function() {
return initRange.apply(calendar(utcYear, utcMonth, utcSunday, utcDay, utcHour, utcMinute, second, millisecond, exports1.utcFormat).domain([
Date.UTC(2000, 0, 1),
Date.UTC(2000, 0, 2)
]), arguments);
}, exports1.scan = function(values, compare) {
const index = leastIndex(values, compare);
return index < 0 ? void 0 : index;
}, exports1.schemeAccent = Accent, exports1.schemeBlues = scheme$l, exports1.schemeBrBG = scheme, exports1.schemeBuGn = scheme$9, exports1.schemeBuPu = scheme$a, exports1.schemeCategory10 = category10, exports1.schemeDark2 = Dark2, exports1.schemeGnBu = scheme$b, exports1.schemeGreens = scheme$m, exports1.schemeGreys = scheme$n, exports1.schemeOrRd = scheme$c, exports1.schemeOranges = scheme$q, exports1.schemePRGn = scheme$1, exports1.schemePaired = Paired, exports1.schemePastel1 = Pastel1, exports1.schemePastel2 = Pastel2, exports1.schemePiYG = scheme$2, exports1.schemePuBu = scheme$e, exports1.schemePuBuGn = scheme$d, exports1.schemePuOr = scheme$3, exports1.schemePuRd = scheme$f, exports1.schemePurples = scheme$o, exports1.schemeRdBu = scheme$4, exports1.schemeRdGy = scheme$5, exports1.schemeRdPu = scheme$g, exports1.schemeRdYlBu = scheme$6, exports1.schemeRdYlGn = scheme$7, exports1.schemeReds = scheme$p, exports1.schemeSet1 = Set1, exports1.schemeSet2 = Set2, exports1.schemeSet3 = Set3, exports1.schemeSpectral = scheme$8, exports1.schemeTableau10 = Tableau10, exports1.schemeYlGn = scheme$i, exports1.schemeYlGnBu = scheme$h, exports1.schemeYlOrBr = scheme$j, exports1.schemeYlOrRd = scheme$k, exports1.select = select, exports1.selectAll = function(selector) {
return "string" == typeof selector ? new Selection([
document.querySelectorAll(selector)
], [
document.documentElement
]) : new Selection([
null == selector ? [] : array$1(selector)
], root);
}, exports1.selection = selection, exports1.selector = selector, exports1.selectorAll = selectorAll, exports1.shuffle = shuffle, exports1.shuffler = shuffler, exports1.some = function(values, test) {
if ("function" != typeof test) throw TypeError("test is not a function");
let index = -1;
for (const value of values)if (test(value, ++index, values)) return !0;
return !1;
}, exports1.sort = function(values, f = ascending) {
if ("function" != typeof values[Symbol.iterator]) throw TypeError("values is not iterable");
return (values = Array.from(values), 1 === f.length) ? (f = values.map(f), permute(values, values.map((d, i)=>i).sort((i, j)=>ascending(f[i], f[j])))) : values.sort(f);
}, exports1.stack = function() {
var keys = constant$a([]), order = none$2, offset = none$1, value = stackValue;
function stack(data) {
var i, oz, sz = Array.from(keys.apply(this, arguments), stackSeries), n = sz.length, j = -1;
for (const d of data)for(i = 0, ++j; i < n; ++i)(sz[i][j] = [
0,
+value(d, sz[i].key, j, data)
]).data = d;
for(i = 0, oz = array$5(order(sz)); i < n; ++i)sz[oz[i]].index = i;
return offset(sz, oz), sz;
}
return stack.keys = function(_) {
return arguments.length ? (keys = "function" == typeof _ ? _ : constant$a(Array.from(_)), stack) : keys;
}, stack.value = function(_) {
return arguments.length ? (value = "function" == typeof _ ? _ : constant$a(+_), stack) : value;
}, stack.order = function(_) {
return arguments.length ? (order = null == _ ? none$2 : "function" == typeof _ ? _ : constant$a(Array.from(_)), stack) : order;
}, stack.offset = function(_) {
return arguments.length ? (offset = null == _ ? none$1 : _, stack) : offset;
}, stack;
}, exports1.stackOffsetDiverging = function(series, order) {
if ((n = series.length) > 0) for(var i, d, dy, yp, yn, n, j = 0, m = series[order[0]].length; j < m; ++j)for(yp = yn = 0, i = 0; i < n; ++i)(dy = (d = series[order[i]][j])[1] - d[0]) > 0 ? (d[0] = yp, d[1] = yp += dy) : dy < 0 ? (d[1] = yn, d[0] = yn += dy) : (d[0] = 0, d[1] = dy);
}, exports1.stackOffsetExpand = function(series, order) {
if ((n = series.length) > 0) {
for(var i, n, y, j = 0, m = series[0].length; j < m; ++j){
for(y = i = 0; i < n; ++i)y += series[i][j][1] || 0;
if (y) for(i = 0; i < n; ++i)series[i][j][1] /= y;
}
none$1(series, order);
}
}, exports1.stackOffsetNone = none$1, exports1.stackOffsetSilhouette = function(series, order) {
if ((n = series.length) > 0) {
for(var n, j = 0, s0 = series[order[0]], m = s0.length; j < m; ++j){
for(var i = 0, y = 0; i < n; ++i)y += series[i][j][1] || 0;
s0[j][1] += s0[j][0] = -y / 2;
}
none$1(series, order);
}
}, exports1.stackOffsetWiggle = function(series, order) {
if ((n = series.length) > 0 && (m = (s0 = series[order[0]]).length) > 0) {
for(var s0, m, n, y = 0, j = 1; j < m; ++j){
for(var i = 0, s1 = 0, s2 = 0; i < n; ++i){
for(var si = series[order[i]], sij0 = si[j][1] || 0, s3 = (sij0 - (si[j - 1][1] || 0)) / 2, k = 0; k < i; ++k){
var sk = series[order[k]];
s3 += (sk[j][1] || 0) - (sk[j - 1][1] || 0);
}
s1 += sij0, s2 += s3 * sij0;
}
s0[j - 1][1] += s0[j - 1][0] = y, s1 && (y -= s2 / s1);
}
s0[j - 1][1] += s0[j - 1][0] = y, none$1(series, order);
}
}, exports1.stackOrderAppearance = appearance, exports1.stackOrderAscending = ascending$3, exports1.stackOrderDescending = function(series) {
return ascending$3(series).reverse();
}, exports1.stackOrderInsideOut = function(series) {
var i, j, n = series.length, sums = series.map(sum$1), order = appearance(series), top = 0, bottom = 0, tops = [], bottoms = [];
for(i = 0; i < n; ++i)j = order[i], top < bottom ? (top += sums[j], tops.push(j)) : (bottom += sums[j], bottoms.push(j));
return bottoms.reverse().concat(tops);
}, exports1.stackOrderNone = none$2, exports1.stackOrderReverse = function(series) {
return none$2(series).reverse();
}, exports1.stratify = function() {
var id = defaultId, parentId = defaultParentId;
function stratify(data) {
var d, i, root, parent, node, nodeId, nodeKey, nodes = Array.from(data), n = nodes.length, nodeByKey = new Map;
for(i = 0; i < n; ++i)d = nodes[i], node = nodes[i] = new Node(d), null != (nodeId = id(d, i, data)) && (nodeId += "") && (nodeKey = node.id = nodeId, nodeByKey.set(nodeKey, nodeByKey.has(nodeKey) ? ambiguous : node)), null != (nodeId = parentId(d, i, data)) && (nodeId += "") && (node.parent = nodeId);
for(i = 0; i < n; ++i)if (nodeId = (node = nodes[i]).parent) {
if (!(parent = nodeByKey.get(nodeId))) throw Error("missing: " + nodeId);
if (parent === ambiguous) throw Error("ambiguous: " + nodeId);
parent.children ? parent.children.push(node) : parent.children = [
node
], node.parent = parent;
} else {
if (root) throw Error("multiple roots");
root = node;
}
if (!root) throw Error("no root");
if (root.parent = preroot, root.eachBefore(function(node) {
node.depth = node.parent.depth + 1, --n;
}).eachBefore(computeHeight), root.parent = null, n > 0) throw Error("cycle");
return root;
}
return stratify.id = function(x) {
return arguments.length ? (id = required(x), stratify) : id;
}, stratify.parentId = function(x) {
return arguments.length ? (parentId = required(x), stratify) : parentId;
}, stratify;
}, exports1.style = styleValue, exports1.subset = function(values, other) {
return superset(other, values);
}, exports1.sum = function(values, valueof) {
let sum = 0;
if (void 0 === valueof) for (let value of values)(value *= 1) && (sum += value);
else {
let index = -1;
for (let value of values)(value = +valueof(value, ++index, values)) && (sum += value);
}
return sum;
}, exports1.superset = superset, exports1.svg = svg, exports1.symbol = function(type, size) {
var context = null;
function symbol() {
var buffer;
if (context || (context = buffer = path()), type.apply(this, arguments).draw(context, +size.apply(this, arguments)), buffer) return context = null, buffer + "" || null;
}
return type = "function" == typeof type ? type : constant$a(type || circle$2), size = "function" == typeof size ? size : constant$a(void 0 === size ? 64 : +size), symbol.type = function(_) {
return arguments.length ? (type = "function" == typeof _ ? _ : constant$a(_), symbol) : type;
}, symbol.size = function(_) {
return arguments.length ? (size = "function" == typeof _ ? _ : constant$a(+_), symbol) : size;
}, symbol.context = function(_) {
return arguments.length ? (context = null == _ ? null : _, symbol) : context;
}, symbol;
}, exports1.symbolCircle = circle$2, exports1.symbolCross = cross$2, exports1.symbolDiamond = diamond, exports1.symbolSquare = square$1, exports1.symbolStar = star, exports1.symbolTriangle = triangle, exports1.symbolWye = wye, exports1.symbols = symbols, exports1.text = text, exports1.thresholdFreedmanDiaconis = function(values, min, max) {
return Math.ceil((max - min) / (2 * (quantile(values, 0.75) - quantile(values, 0.25)) * Math.pow(count(values), -1 / 3)));
}, exports1.thresholdScott = function(values, min, max) {
return Math.ceil((max - min) / (3.5 * deviation(values) * Math.pow(count(values), -1 / 3)));
}, exports1.thresholdSturges = thresholdSturges, exports1.tickFormat = tickFormat, exports1.tickIncrement = tickIncrement, exports1.tickStep = tickStep, exports1.ticks = ticks, exports1.timeDay = day, exports1.timeDays = days, exports1.timeFormatDefaultLocale = defaultLocale$1, exports1.timeFormatLocale = formatLocale$1, exports1.timeFriday = friday, exports1.timeFridays = fridays, exports1.timeHour = hour, exports1.timeHours = hours, exports1.timeInterval = newInterval, exports1.timeMillisecond = millisecond, exports1.timeMilliseconds = milliseconds, exports1.timeMinute = minute, exports1.timeMinutes = minutes, exports1.timeMonday = monday, exports1.timeMondays = mondays, exports1.timeMonth = month, exports1.timeMonths = months, exports1.timeSaturday = saturday, exports1.timeSaturdays = saturdays, exports1.timeSecond = second, exports1.timeSeconds = seconds, exports1.timeSunday = sunday, exports1.timeSundays = sundays, exports1.timeThursday = thursday, exports1.timeThursdays = thursdays, exports1.timeTuesday = tuesday, exports1.timeTuesdays = tuesdays, exports1.timeWednesday = wednesday, exports1.timeWednesdays = wednesdays, exports1.timeWeek = sunday, exports1.timeWeeks = sundays, exports1.timeYear = year, exports1.timeYears = years, exports1.timeout = timeout$1, exports1.timer = timer, exports1.timerFlush = timerFlush, exports1.transition = transition, exports1.transpose = transpose, exports1.tree = // Node-link tree diagram using the Reingold-Tilford "tidy" algorithm
function() {
var separation = defaultSeparation$1, dx = 1, dy = 1, nodeSize = null;
function tree(root) {
var t = function(root) {
for(var node, child, children, i, n, tree = new TreeNode(root, 0), nodes = [
tree
]; node = nodes.pop();)if (children = node._.children) for(node.children = Array(n = children.length), i = n - 1; i >= 0; --i)nodes.push(child = node.children[i] = new TreeNode(children[i], i)), child.parent = node;
return (tree.parent = new TreeNode(null, 0)).children = [
tree
], tree;
}(root);
// If a fixed node size is specified, scale x and y.
if (// Compute the layout using Buchheim et al.’s algorithm.
t.eachAfter(firstWalk), t.parent.m = -t.z, t.eachBefore(secondWalk), nodeSize) root.eachBefore(sizeNode);
else {
var left = root, right = root, bottom = root;
root.eachBefore(function(node) {
node.x < left.x && (left = node), node.x > right.x && (right = node), node.depth > bottom.depth && (bottom = node);
});
var s = left === right ? 1 : separation(left, right) / 2, tx = s - left.x, kx = dx / (right.x + s + tx), ky = dy / (bottom.depth || 1);
root.eachBefore(function(node) {
node.x = (node.x + tx) * kx, node.y = node.depth * ky;
});
}
return root;
}
// Computes a preliminary x-coordinate for v. Before that, FIRST WALK is
// applied recursively to the children of v, as well as the function
// APPORTION. After spacing out the children by calling EXECUTE SHIFTS, the
// node v is placed to the midpoint of its outermost children.
function firstWalk(v) {
var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null;
if (children) {
!// All other shifts, applied to the smaller subtrees between w- and w+, are
// performed by this function. To prepare the shifts, we have to adjust
// change(w+), shift(w+), and change(w-).
function(v) {
for(var w, shift = 0, change = 0, children = v.children, i = children.length; --i >= 0;)w = children[i], w.z += shift, w.m += shift, shift += w.s + (change += w.c);
}(v);
var midpoint = (children[0].z + children[children.length - 1].z) / 2;
w ? (v.z = w.z + separation(v._, w._), v.m = v.z - midpoint) : v.z = midpoint;
} else w && (v.z = w.z + separation(v._, w._));
v.parent.A = // The core of the algorithm. Here, a new subtree is combined with the
// previous subtrees. Threads are used to traverse the inside and outside
// contours of the left and right subtree up to the highest common level. The
// vertices used for the traversals are vi+, vi-, vo-, and vo+, where the
// superscript o means outside and i means inside, the subscript - means left
// subtree and + means right subtree. For summing up the modifiers along the
// contour, we use respective variables si+, si-, so-, and so+. Whenever two
// nodes of the inside contours conflict, we compute the left one of the
// greatest uncommon ancestors using the function ANCESTOR and call MOVE
// SUBTREE to shift the subtree and prepare the shifts of smaller subtrees.
// Finally, we add a new thread (if necessary).
function(v, w, ancestor) {
if (w) {
for(var vim, ancestor1, shift, vip = v, vop = v, vim1 = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim1.m, som = vom.m; vim1 = nextRight(vim1), vip = nextLeft(vip), vim1 && vip;)vom = nextLeft(vom), (vop = nextRight(vop)).a = v, (shift = vim1.z + sim - vip.z - sip + separation(vim1._, vip._)) > 0 && (// Shifts the current subtree rooted at w+. This is done by increasing
// prelim(w+) and mod(w+) by shift.
function(wm, wp, shift) {
var change = shift / (wp.i - wm.i);
wp.c -= change, wp.s += shift, wm.c += change, wp.z += shift, wp.m += shift;
}((vim = vim1, ancestor1 = ancestor, vim.a.parent === v.parent ? vim.a : ancestor1), v, shift), sip += shift, sop += shift), sim += vim1.m, sip += vip.m, som += vom.m, sop += vop.m;
vim1 && !nextRight(vop) && (vop.t = vim1, vop.m += sim - sop), vip && !nextLeft(vom) && (vom.t = vip, vom.m += sip - som, ancestor = v);
}
return ancestor;
}(v, w, v.parent.A || siblings[0]);
}
// Computes all real x-coordinates by summing up the modifiers recursively.
function secondWalk(v) {
v._.x = v.z + v.parent.m, v.m += v.parent.m;
}
function sizeNode(node) {
node.x *= dx, node.y = node.depth * dy;
}
return tree.separation = function(x) {
return arguments.length ? (separation = x, tree) : separation;
}, tree.size = function(x) {
return arguments.length ? (nodeSize = !1, dx = +x[0], dy = +x[1], tree) : nodeSize ? null : [
dx,
dy
];
}, tree.nodeSize = function(x) {
return arguments.length ? (nodeSize = !0, dx = +x[0], dy = +x[1], tree) : nodeSize ? [
dx,
dy
] : null;
}, tree;
}, exports1.treemap = function() {
var tile = squarify, round = !1, dx = 1, dy = 1, paddingStack = [
0
], paddingInner = constantZero, paddingTop = constantZero, paddingRight = constantZero, paddingBottom = constantZero, paddingLeft = constantZero;
function treemap(root) {
return root.x0 = root.y0 = 0, root.x1 = dx, root.y1 = dy, root.eachBefore(positionNode), paddingStack = [
0
], round && root.eachBefore(roundNode), root;
}
function positionNode(node) {
var p = paddingStack[node.depth], x0 = node.x0 + p, y0 = node.y0 + p, x1 = node.x1 - p, y1 = node.y1 - p;
x1 < x0 && (x0 = x1 = (x0 + x1) / 2), y1 < y0 && (y0 = y1 = (y0 + y1) / 2), node.x0 = x0, node.y0 = y0, node.x1 = x1, node.y1 = y1, node.children && (p = paddingStack[node.depth + 1] = paddingInner(node) / 2, x0 += paddingLeft(node) - p, y0 += paddingTop(node) - p, x1 -= paddingRight(node) - p, y1 -= paddingBottom(node) - p, x1 < x0 && (x0 = x1 = (x0 + x1) / 2), y1 < y0 && (y0 = y1 = (y0 + y1) / 2), tile(node, x0, y0, x1, y1));
}
return treemap.round = function(x) {
return arguments.length ? (round = !!x, treemap) : round;
}, treemap.size = function(x) {
return arguments.length ? (dx = +x[0], dy = +x[1], treemap) : [
dx,
dy
];
}, treemap.tile = function(x) {
return arguments.length ? (tile = required(x), treemap) : tile;
}, treemap.padding = function(x) {
return arguments.length ? treemap.paddingInner(x).paddingOuter(x) : treemap.paddingInner();
}, treemap.paddingInner = function(x) {
return arguments.length ? (paddingInner = "function" == typeof x ? x : constant$9(+x), treemap) : paddingInner;
}, treemap.paddingOuter = function(x) {
return arguments.length ? treemap.paddingTop(x).paddingRight(x).paddingBottom(x).paddingLeft(x) : treemap.paddingTop();
}, treemap.paddingTop = function(x) {
return arguments.length ? (paddingTop = "function" == typeof x ? x : constant$9(+x), treemap) : paddingTop;
}, treemap.paddingRight = function(x) {
return arguments.length ? (paddingRight = "function" == typeof x ? x : constant$9(+x), treemap) : paddingRight;
}, treemap.paddingBottom = function(x) {
return arguments.length ? (paddingBottom = "function" == typeof x ? x : constant$9(+x), treemap) : paddingBottom;
}, treemap.paddingLeft = function(x) {
return arguments.length ? (paddingLeft = "function" == typeof x ? x : constant$9(+x), treemap) : paddingLeft;
}, treemap;
}, exports1.treemapBinary = function(parent, x0, y0, x1, y1) {
var i, sum, nodes = parent.children, n = nodes.length, sums = Array(n + 1);
for(sums[0] = sum = i = 0; i < n; ++i)sums[i + 1] = sum += nodes[i].value;
(function partition(i, j, value, x0, y0, x1, y1) {
if (i >= j - 1) {
var node = nodes[i];
node.x0 = x0, node.y0 = y0, node.x1 = x1, node.y1 = y1;
return;
}
for(var valueOffset = sums[i], valueTarget = value / 2 + valueOffset, k = i + 1, hi = j - 1; k < hi;){
var mid = k + hi >>> 1;
sums[mid] < valueTarget ? k = mid + 1 : hi = mid;
}
valueTarget - sums[k - 1] < sums[k] - valueTarget && i + 1 < k && --k;
var valueLeft = sums[k] - valueOffset, valueRight = value - valueLeft;
if (x1 - x0 > y1 - y0) {
var xk = value ? (x0 * valueRight + x1 * valueLeft) / value : x1;
partition(i, k, valueLeft, x0, y0, xk, y1), partition(k, j, valueRight, xk, y0, x1, y1);
} else {
var yk = value ? (y0 * valueRight + y1 * valueLeft) / value : y1;
partition(i, k, valueLeft, x0, y0, x1, yk), partition(k, j, valueRight, x0, yk, x1, y1);
}
})(0, n, parent.value, x0, y0, x1, y1);
}, exports1.treemapDice = treemapDice, exports1.treemapResquarify = resquarify, exports1.treemapSlice = treemapSlice, exports1.treemapSliceDice = function(parent, x0, y0, x1, y1) {
(1 & parent.depth ? treemapSlice : treemapDice)(parent, x0, y0, x1, y1);
}, exports1.treemapSquarify = squarify, exports1.tsv = tsv$1, exports1.tsvFormat = tsvFormat, exports1.tsvFormatBody = tsvFormatBody, exports1.tsvFormatRow = tsvFormatRow, exports1.tsvFormatRows = tsvFormatRows, exports1.tsvFormatValue = tsvFormatValue, exports1.tsvParse = tsvParse, exports1.tsvParseRows = tsvParseRows, exports1.union = function(...others) {
const set = new Set();
for (const other of others)for (const o of other)set.add(o);
return set;
}, exports1.utcDay = utcDay, exports1.utcDays = utcDays, exports1.utcFriday = utcFriday, exports1.utcFridays = utcFridays, exports1.utcHour = utcHour, exports1.utcHours = utcHours, exports1.utcMillisecond = millisecond, exports1.utcMilliseconds = milliseconds, exports1.utcMinute = utcMinute, exports1.utcMinutes = utcMinutes, exports1.utcMonday = utcMonday, exports1.utcMondays = utcMondays, exports1.utcMonth = utcMonth, exports1.utcMonths = utcMonths, exports1.utcSaturday = utcSaturday, exports1.utcSaturdays = utcSaturdays, exports1.utcSecond = second, exports1.utcSeconds = seconds, exports1.utcSunday = utcSunday, exports1.utcSundays = utcSundays, exports1.utcThursday = utcThursday, exports1.utcThursdays = utcThursdays, exports1.utcTuesday = utcTuesday, exports1.utcTuesdays = utcTuesdays, exports1.utcWednesday = utcWednesday, exports1.utcWednesdays = utcWednesdays, exports1.utcWeek = utcSunday, exports1.utcWeeks = utcSundays, exports1.utcYear = utcYear, exports1.utcYears = utcYears, exports1.variance = variance, exports1.version = "6.3.1", exports1.window = defaultView, exports1.xml = xml, exports1.zip = function() {
return transpose(arguments);
}, exports1.zoom = function() {
var touchstarting, touchfirst, touchending, filter = defaultFilter$2, extent = defaultExtent$1, constrain = defaultConstrain, wheelDelta = defaultWheelDelta, touchable = defaultTouchable$2, scaleExtent = [
0,
1 / 0
], translateExtent = [
[
-1 / 0,
-1 / 0
],
[
1 / 0,
1 / 0
]
], duration = 250, interpolate = interpolateZoom, listeners = dispatch("start", "zoom", "end"), clickDistance2 = 0, tapDistance = 10;
function zoom(selection) {
selection.property("__zoom", defaultTransform).on("wheel.zoom", wheeled).on("mousedown.zoom", mousedowned).on("dblclick.zoom", dblclicked).filter(touchable).on("touchstart.zoom", touchstarted).on("touchmove.zoom", touchmoved).on("touchend.zoom touchcancel.zoom", touchended).style("-webkit-tap-highlight-color", "rgba(0,0,0,0)");
}
function scale(transform, k) {
return (k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], k))) === transform.k ? transform : new Transform(k, transform.x, transform.y);
}
function translate(transform, p0, p1) {
var x = p0[0] - p1[0] * transform.k, y = p0[1] - p1[1] * transform.k;
return x === transform.x && y === transform.y ? transform : new Transform(transform.k, x, y);
}
function centroid(extent) {
return [
(+extent[0][0] + +extent[1][0]) / 2,
(+extent[0][1] + +extent[1][1]) / 2
];
}
function schedule(transition, transform, point, event) {
transition.on("start.zoom", function() {
gesture(this, arguments).event(event).start();
}).on("interrupt.zoom end.zoom", function() {
gesture(this, arguments).event(event).end();
}).tween("zoom", function() {
var args = arguments, g = gesture(this, args).event(event), e = extent.apply(this, args), p = null == point ? centroid(e) : "function" == typeof point ? point.apply(this, args) : point, w = Math.max(e[1][0] - e[0][0], e[1][1] - e[0][1]), a = this.__zoom, b = "function" == typeof transform ? transform.apply(this, args) : transform, i = interpolate(a.invert(p).concat(w / a.k), b.invert(p).concat(w / b.k));
return function(t) {
if (1 === t) t = b; // Avoid rounding error on end.
else {
var l = i(t), k = w / l[2];
t = new Transform(k, p[0] - l[0] * k, p[1] - l[1] * k);
}
g.zoom(null, t);
};
});
}
function gesture(that, args, clean) {
return !clean && that.__zooming || new Gesture(that, args);
}
function Gesture(that, args) {
this.that = that, this.args = args, this.active = 0, this.sourceEvent = null, this.extent = extent.apply(that, args), this.taps = 0;
}
function wheeled(event, ...args) {
if (filter.apply(this, arguments)) {
var g = gesture(this, args).event(event), t = this.__zoom, k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], t.k * Math.pow(2, wheelDelta.apply(this, arguments)))), p = pointer(event);
// If the mouse is in the same location as before, reuse it.
// If there were recent wheel events, reset the wheel idle timeout.
if (g.wheel) (g.mouse[0][0] !== p[0] || g.mouse[0][1] !== p[1]) && (g.mouse[1] = t.invert(g.mouse[0] = p)), clearTimeout(g.wheel);
else {
if (t.k === k) return;
g.mouse = [
p,
t.invert(p)
], interrupt(this), g.start();
}
noevent$2(event), g.wheel = setTimeout(function() {
g.wheel = null, g.end();
}, 150), g.zoom("mouse", constrain(translate(scale(t, k), g.mouse[0], g.mouse[1]), g.extent, translateExtent));
}
}
function mousedowned(event, ...args) {
if (!touchending && filter.apply(this, arguments)) {
var g = gesture(this, args, !0).event(event), v = select(event.view).on("mousemove.zoom", function(event) {
if (noevent$2(event), !g.moved) {
var dx = event.clientX - x0, dy = event.clientY - y0;
g.moved = dx * dx + dy * dy > clickDistance2;
}
g.event(event).zoom("mouse", constrain(translate(g.that.__zoom, g.mouse[0] = pointer(event, currentTarget), g.mouse[1]), g.extent, translateExtent));
}, !0).on("mouseup.zoom", function(event) {
v.on("mousemove.zoom mouseup.zoom", null), yesdrag(event.view, g.moved), noevent$2(event), g.event(event).end();
}, !0), p = pointer(event, currentTarget), currentTarget = event.currentTarget, x0 = event.clientX, y0 = event.clientY;
dragDisable(event.view), nopropagation$2(event), g.mouse = [
p,
this.__zoom.invert(p)
], interrupt(this), g.start();
}
}
function dblclicked(event, ...args) {
if (filter.apply(this, arguments)) {
var t0 = this.__zoom, p0 = pointer(event.changedTouches ? event.changedTouches[0] : event, this), p1 = t0.invert(p0), k1 = t0.k * (event.shiftKey ? 0.5 : 2), t1 = constrain(translate(scale(t0, k1), p0, p1), extent.apply(this, args), translateExtent);
noevent$2(event), duration > 0 ? select(this).transition().duration(duration).call(schedule, t1, p0, event) : select(this).call(zoom.transform, t1, p0, event);
}
}
function touchstarted(event, ...args) {
if (filter.apply(this, arguments)) {
var started, i, t, p, touches = event.touches, n = touches.length, g = gesture(this, args, event.changedTouches.length === n).event(event);
for(nopropagation$2(event), i = 0; i < n; ++i)p = [
p = pointer(t = touches[i], this),
this.__zoom.invert(p),
t.identifier
], g.touch0 ? g.touch1 || g.touch0[2] === p[2] || (g.touch1 = p, g.taps = 0) : (g.touch0 = p, started = !0, g.taps = 1 + !!touchstarting);
touchstarting && (touchstarting = clearTimeout(touchstarting)), started && (g.taps < 2 && (touchfirst = p[0], touchstarting = setTimeout(function() {
touchstarting = null;
}, 500)), interrupt(this), g.start());
}
}
function touchmoved(event, ...args) {
if (this.__zooming) {
var i, t, p, l, g = gesture(this, args).event(event), touches = event.changedTouches, n = touches.length;
for(noevent$2(event), i = 0; i < n; ++i)p = pointer(t = touches[i], this), g.touch0 && g.touch0[2] === t.identifier ? g.touch0[0] = p : g.touch1 && g.touch1[2] === t.identifier && (g.touch1[0] = p);
if (t = g.that.__zoom, g.touch1) {
var p0 = g.touch0[0], l0 = g.touch0[1], p1 = g.touch1[0], l1 = g.touch1[1], dp = (dp = p1[0] - p0[0]) * dp + (dp = p1[1] - p0[1]) * dp, dl = (dl = l1[0] - l0[0]) * dl + (dl = l1[1] - l0[1]) * dl;
t = scale(t, Math.sqrt(dp / dl)), p = [
(p0[0] + p1[0]) / 2,
(p0[1] + p1[1]) / 2
], l = [
(l0[0] + l1[0]) / 2,
(l0[1] + l1[1]) / 2
];
} else {
if (!g.touch0) return;
p = g.touch0[0], l = g.touch0[1];
}
g.zoom("touch", constrain(translate(t, p, l), g.extent, translateExtent));
}
}
function touchended(event, ...args) {
if (this.__zooming) {
var i, t, g = gesture(this, args).event(event), touches = event.changedTouches, n = touches.length;
for(nopropagation$2(event), touchending && clearTimeout(touchending), touchending = setTimeout(function() {
touchending = null;
}, 500), i = 0; i < n; ++i)t = touches[i], g.touch0 && g.touch0[2] === t.identifier ? delete g.touch0 : g.touch1 && g.touch1[2] === t.identifier && delete g.touch1;
if (g.touch1 && !g.touch0 && (g.touch0 = g.touch1, delete g.touch1), g.touch0) g.touch0[1] = this.__zoom.invert(g.touch0[0]);
else // If this was a dbltap, reroute to the (optional) dblclick.zoom handler.
if (g.end(), 2 === g.taps && (t = pointer(t, this), Math.hypot(touchfirst[0] - t[0], touchfirst[1] - t[1]) < tapDistance)) {
var p = select(this).on("dblclick.zoom");
p && p.apply(this, arguments);
}
}
}
return zoom.transform = function(collection, transform, point, event) {
var selection = collection.selection ? collection.selection() : collection;
selection.property("__zoom", defaultTransform), collection !== selection ? schedule(collection, transform, point, event) : selection.interrupt().each(function() {
gesture(this, arguments).event(event).start().zoom(null, "function" == typeof transform ? transform.apply(this, arguments) : transform).end();
});
}, zoom.scaleBy = function(selection, k, p, event) {
zoom.scaleTo(selection, function() {
var k0 = this.__zoom.k, k1 = "function" == typeof k ? k.apply(this, arguments) : k;
return k0 * k1;
}, p, event);
}, zoom.scaleTo = function(selection, k, p, event) {
zoom.transform(selection, function() {
var e = extent.apply(this, arguments), t0 = this.__zoom, p0 = null == p ? centroid(e) : "function" == typeof p ? p.apply(this, arguments) : p, p1 = t0.invert(p0), k1 = "function" == typeof k ? k.apply(this, arguments) : k;
return constrain(translate(scale(t0, k1), p0, p1), e, translateExtent);
}, p, event);
}, zoom.translateBy = function(selection, x, y, event) {
zoom.transform(selection, function() {
return constrain(this.__zoom.translate("function" == typeof x ? x.apply(this, arguments) : x, "function" == typeof y ? y.apply(this, arguments) : y), extent.apply(this, arguments), translateExtent);
}, null, event);
}, zoom.translateTo = function(selection, x, y, p, event) {
zoom.transform(selection, function() {
var e = extent.apply(this, arguments), t = this.__zoom, p0 = null == p ? centroid(e) : "function" == typeof p ? p.apply(this, arguments) : p;
return constrain(identity$9.translate(p0[0], p0[1]).scale(t.k).translate("function" == typeof x ? -x.apply(this, arguments) : -x, "function" == typeof y ? -y.apply(this, arguments) : -y), e, translateExtent);
}, p, event);
}, Gesture.prototype = {
event: function(event) {
return event && (this.sourceEvent = event), this;
},
start: function() {
return 1 == ++this.active && (this.that.__zooming = this, this.emit("start")), this;
},
zoom: function(key, transform) {
return this.mouse && "mouse" !== key && (this.mouse[1] = transform.invert(this.mouse[0])), this.touch0 && "touch" !== key && (this.touch0[1] = transform.invert(this.touch0[0])), this.touch1 && "touch" !== key && (this.touch1[1] = transform.invert(this.touch1[0])), this.that.__zoom = transform, this.emit("zoom"), this;
},
end: function() {
return 0 == --this.active && (delete this.that.__zooming, this.emit("end")), this;
},
emit: function(type) {
var d = select(this.that).datum();
listeners.call(type, this.that, new ZoomEvent(type, {
sourceEvent: this.sourceEvent,
target: zoom,
type,
transform: this.that.__zoom,
dispatch: listeners
}), d);
}
}, zoom.wheelDelta = function(_) {
return arguments.length ? (wheelDelta = "function" == typeof _ ? _ : constant$b(+_), zoom) : wheelDelta;
}, zoom.filter = function(_) {
return arguments.length ? (filter = "function" == typeof _ ? _ : constant$b(!!_), zoom) : filter;
}, zoom.touchable = function(_) {
return arguments.length ? (touchable = "function" == typeof _ ? _ : constant$b(!!_), zoom) : touchable;
}, zoom.extent = function(_) {
return arguments.length ? (extent = "function" == typeof _ ? _ : constant$b([
[
+_[0][0],
+_[0][1]
],
[
+_[1][0],
+_[1][1]
]
]), zoom) : extent;
}, zoom.scaleExtent = function(_) {
return arguments.length ? (scaleExtent[0] = +_[0], scaleExtent[1] = +_[1], zoom) : [
scaleExtent[0],
scaleExtent[1]
];
}, zoom.translateExtent = function(_) {
return arguments.length ? (translateExtent[0][0] = +_[0][0], translateExtent[1][0] = +_[1][0], translateExtent[0][1] = +_[0][1], translateExtent[1][1] = +_[1][1], zoom) : [
[
translateExtent[0][0],
translateExtent[0][1]
],
[
translateExtent[1][0],
translateExtent[1][1]
]
];
}, zoom.constrain = function(_) {
return arguments.length ? (constrain = _, zoom) : constrain;
}, zoom.duration = function(_) {
return arguments.length ? (duration = +_, zoom) : duration;
}, zoom.interpolate = function(_) {
return arguments.length ? (interpolate = _, zoom) : interpolate;
}, zoom.on = function() {
var value = listeners.on.apply(listeners, arguments);
return value === listeners ? zoom : value;
}, zoom.clickDistance = function(_) {
return arguments.length ? (clickDistance2 = (_ *= 1) * _, zoom) : Math.sqrt(clickDistance2);
}, zoom.tapDistance = function(_) {
return arguments.length ? (tapDistance = +_, zoom) : tapDistance;
}, zoom;
}, exports1.zoomIdentity = identity$9, exports1.zoomTransform = transform$1, Object.defineProperty(exports1, '__esModule', {
value: !0
});
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/benches-full/jquery.js | JavaScript | !/*!
* jQuery JavaScript Library v3.5.1
* https://jquery.com/
*
* Includes Sizzle.js
* https://sizzlejs.com/
*
* Copyright JS Foundation and other contributors
* Released under the MIT license
* https://jquery.org/license
*
* Date: 2020-05-04T22:49Z
*/ function(global, factory) {
"use strict";
"object" == typeof module && "object" == typeof module.exports ? // For CommonJS and CommonJS-like environments where a proper `window`
// is present, execute the factory and get jQuery.
// For environments that do not have a `window` with a `document`
// (such as Node.js), expose a factory as module.exports.
// This accentuates the need for the creation of a real `window`.
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info.
module.exports = global.document ? factory(global, !0) : function(w) {
if (!w.document) throw Error("jQuery requires a window with a document");
return factory(w);
} : factory(global);
// Pass this if window is not defined yet
}("undefined" != typeof window ? window : this, function(window1, noGlobal) {
// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1
// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode
// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common
// enough that all such attempts are guarded in a try block.
"use strict";
var body, arr = [], getProto = Object.getPrototypeOf, slice = arr.slice, flat = arr.flat ? function(array) {
return arr.flat.call(array);
} : function(array) {
return arr.concat.apply([], array);
}, push = arr.push, indexOf = arr.indexOf, class2type = {}, toString = class2type.toString, hasOwn = class2type.hasOwnProperty, fnToString = hasOwn.toString, ObjectFunctionString = fnToString.call(Object), support = {}, isFunction = function(obj) {
// Support: Chrome <=57, Firefox <=52
// In some browsers, typeof returns "function" for HTML <object> elements
// (i.e., `typeof document.createElement( "object" ) === "function"`).
// We don't want to classify *any* DOM node as a function.
return "function" == typeof obj && "number" != typeof obj.nodeType;
}, isWindow = function(obj) {
return null != obj && obj === obj.window;
}, document = window1.document, preservedScriptAttributes = {
type: !0,
src: !0,
nonce: !0,
noModule: !0
};
function DOMEval(code, node, doc) {
var i, val, script = (doc = doc || document).createElement("script");
if (script.text = code, node) for(i in preservedScriptAttributes)// Support: Firefox 64+, Edge 18+
// Some browsers don't support the "nonce" property on scripts.
// On the other hand, just using `getAttribute` is not enough as
// the `nonce` attribute is reset to an empty string whenever it
// becomes browsing-context connected.
// See https://github.com/whatwg/html/issues/2369
// See https://html.spec.whatwg.org/#nonce-attributes
// The `node.getAttribute` check was added for the sake of
// `jQuery.globalEval` so that it can fake a nonce-containing node
// via an object.
(val = node[i] || node.getAttribute && node.getAttribute(i)) && script.setAttribute(i, val);
doc.head.appendChild(script).parentNode.removeChild(script);
}
function toType(obj) {
return null == obj ? obj + "" : "object" == typeof obj || "function" == typeof obj ? class2type[toString.call(obj)] || "object" : typeof obj;
}
/* global Symbol */ // Defining this global in .eslintrc.json would create a danger of using the global
// unguarded in another place, it seems safer to define global only for this module
var version = "3.5.1", // Define a local copy of jQuery
jQuery = function(selector, context) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init(selector, context);
};
function isArrayLike(obj) {
// Support: real iOS 8.2 only (not reproducible in simulator)
// `in` check used to prevent JIT error (gh-2145)
// hasOwn isn't used here due to false negatives
// regarding Nodelist length in IE
var length = !!obj && "length" in obj && obj.length, type = toType(obj);
return !(isFunction(obj) || isWindow(obj)) && ("array" === type || 0 === length || "number" == typeof length && length > 0 && length - 1 in obj);
}
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return slice.call(this);
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function(num) {
return(// Return all the elements in a clean array
null == num ? slice.call(this) : num < 0 ? this[num + this.length] : this[num]);
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function(elems) {
// Build a new jQuery matched element set
var ret = jQuery.merge(this.constructor(), elems);
// Return the newly-formed element set
return(// Add the old object onto the stack (as a reference)
ret.prevObject = this, ret);
},
// Execute a callback for every element in the matched set.
each: function(callback) {
return jQuery.each(this, callback);
},
map: function(callback) {
return this.pushStack(jQuery.map(this, function(elem, i) {
return callback.call(elem, i, elem);
}));
},
slice: function() {
return this.pushStack(slice.apply(this, arguments));
},
first: function() {
return this.eq(0);
},
last: function() {
return this.eq(-1);
},
even: function() {
return this.pushStack(jQuery.grep(this, function(_elem, i) {
return (i + 1) % 2;
}));
},
odd: function() {
return this.pushStack(jQuery.grep(this, function(_elem, i) {
return i % 2;
}));
},
eq: function(i) {
var len = this.length, j = +i + (i < 0 ? len : 0);
return this.pushStack(j >= 0 && j < len ? [
this[j]
] : []);
},
end: function() {
return this.prevObject || this.constructor();
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: arr.sort,
splice: arr.splice
}, jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = !1;
for("boolean" == typeof target && (deep = target, // Skip the boolean and the target
target = arguments[i] || {}, i++), "object" == typeof target || isFunction(target) || (target = {}), i === length && (target = this, i--); i < length; i++)// Only deal with non-null/undefined values
if (null != (options = arguments[i])) // Extend the base object
for(name in options)// Prevent Object.prototype pollution
// Prevent never-ending loop
copy = options[name], "__proto__" !== name && target !== copy && (deep && copy && (jQuery.isPlainObject(copy) || (copyIsArray = Array.isArray(copy))) ? (src = target[name], clone = copyIsArray && !Array.isArray(src) ? [] : copyIsArray || jQuery.isPlainObject(src) ? src : {}, copyIsArray = !1, // Never move original objects, clone them
target[name] = jQuery.extend(deep, clone, copy)) : void 0 !== copy && (target[name] = copy));
// Return the modified object
return target;
}, jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + (version + Math.random()).replace(/\D/g, ""),
// Assume jQuery is ready without the ready module
isReady: !0,
error: function(msg) {
throw Error(msg);
},
noop: function() {},
isPlainObject: function(obj) {
var proto, Ctor;
return(// Detect obvious negatives
// Use toString instead of jQuery.type to catch host objects
!!obj && "[object Object]" === toString.call(obj) && (!(proto = getProto(obj)) || "function" == typeof // Objects with prototype are plain iff they were constructed by a global Object function
(Ctor = hasOwn.call(proto, "constructor") && proto.constructor) && fnToString.call(Ctor) === ObjectFunctionString));
},
isEmptyObject: function(obj) {
var name;
for(name in obj)return !1;
return !0;
},
// Evaluates a script in a provided context; falls back to the global one
// if not specified.
globalEval: function(code, options, doc) {
DOMEval(code, {
nonce: options && options.nonce
}, doc);
},
each: function(obj, callback) {
var length, i = 0;
if (isArrayLike(obj)) for(length = obj.length; i < length && !1 !== callback.call(obj[i], i, obj[i]); i++);
else for(i in obj)if (!1 === callback.call(obj[i], i, obj[i])) break;
return obj;
},
// results is for internal usage only
makeArray: function(arr, results) {
var ret = results || [];
return null != arr && (isArrayLike(Object(arr)) ? jQuery.merge(ret, "string" == typeof arr ? [
arr
] : arr) : push.call(ret, arr)), ret;
},
inArray: function(elem, arr, i) {
return null == arr ? -1 : indexOf.call(arr, elem, i);
},
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
merge: function(first, second) {
for(var len = +second.length, j = 0, i = first.length; j < len; j++)first[i++] = second[j];
return first.length = i, first;
},
grep: function(elems, callback, invert) {
// Go through the array, only saving the items
// that pass the validator function
for(var matches = [], i = 0, length = elems.length, callbackExpect = !invert; i < length; i++)!callback(elems[i], i) !== callbackExpect && matches.push(elems[i]);
return matches;
},
// arg is for internal usage only
map: function(elems, callback, arg) {
var length, value, i = 0, ret = [];
// Go through the array, translating each of the items to their new values
if (isArrayLike(elems)) for(length = elems.length; i < length; i++)null != (value = callback(elems[i], i, arg)) && ret.push(value);
else for(i in elems)null != (value = callback(elems[i], i, arg)) && ret.push(value);
// Flatten any nested arrays
return flat(ret);
},
// A global GUID counter for objects
guid: 1,
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
}), "function" == typeof Symbol && (jQuery.fn[Symbol.iterator] = arr[Symbol.iterator]), // Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "), function(_i, name) {
class2type["[object " + name + "]"] = name.toLowerCase();
});
var Sizzle = /*!
* Sizzle CSS Selector Engine v2.3.5
* https://sizzlejs.com/
*
* Copyright JS Foundation and other contributors
* Released under the MIT license
* https://js.foundation/
*
* Date: 2020-03-14
*/ function(window1) {
var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars
setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data
expando = "sizzle" + +new Date(), preferredDoc = window1.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), nonnativeSelectorCache = createCache(), sortOrder = function(a, b) {
return a === b && (hasDuplicate = !0), 0;
}, // Instance methods
hasOwn = {}.hasOwnProperty, arr = [], pop = arr.pop, pushNative = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native
// https://jsperf.com/thor-indexof-vs-for/5
indexOf = function(list, elem) {
for(var i = 0, len = list.length; i < len; i++)if (list[i] === elem) return i;
return -1;
}, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions
// http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]", // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram
identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2)
"*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5]
// or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rwhitespace = RegExp(whitespace + "+", "g"), rtrim = RegExp("^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g"), rcomma = RegExp("^" + whitespace + "*," + whitespace + "*"), rcombinators = RegExp("^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*"), rdescend = RegExp(whitespace + "|>"), rpseudo = new RegExp(pseudos), ridentifier = RegExp("^" + identifier + "$"), matchExpr = {
ID: RegExp("^#(" + identifier + ")"),
CLASS: RegExp("^\\.(" + identifier + ")"),
TAG: RegExp("^(" + identifier + "|[*])"),
ATTR: RegExp("^" + attributes),
PSEUDO: RegExp("^" + pseudos),
CHILD: RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i"),
bool: RegExp("^(?:" + booleans + ")$", "i"),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
needsContext: RegExp("^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i")
}, rhtml = /HTML$/i, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, // CSS escapes
// http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = RegExp("\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g"), funescape = function(escape, nonHex) {
var high = "0x" + escape.slice(1) - 0x10000;
return nonHex || // Replace a hexadecimal escape sequence with the encoded Unicode code point
// Support: IE <=11+
// For values outside the Basic Multilingual Plane (BMP), manually construct a
// surrogate pair
(high < 0 ? String.fromCharCode(high + 0x10000) : String.fromCharCode(high >> 10 | 0xD800, 0x3FF & high | 0xDC00));
}, // CSS string/identifier serialization
// https://drafts.csswg.org/cssom/#common-serializing-idioms
rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, fcssescape = function(ch, asCodePoint) {
return asCodePoint ? // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
"\0" === ch ? "\uFFFD" : ch.slice(0, -1) + "\\" + ch.charCodeAt(ch.length - 1).toString(16) + " " : "\\" + ch;
}, // Used for iframes
// See setDocument()
// Removing the function wrapper causes a "Permission Denied"
// error in IE
unloadHandler = function() {
setDocument();
}, inDisabledFieldset = addCombinator(function(elem) {
return !0 === elem.disabled && "fieldset" === elem.nodeName.toLowerCase();
}, {
dir: "parentNode",
next: "legend"
});
// Optimize for push.apply( _, NodeList )
try {
push.apply(arr = slice.call(preferredDoc.childNodes), preferredDoc.childNodes), // Support: Android<4.0
// Detect silently failing push.apply
// eslint-disable-next-line no-unused-expressions
arr[preferredDoc.childNodes.length].nodeType;
} catch (e) {
push = {
apply: arr.length ? // Leverage slice if possible
function(target, els) {
pushNative.apply(target, slice.call(els));
} : // Support: IE<9
// Otherwise append directly
function(target, els) {
// Can't trust NodeList.length
for(var j = target.length, i = 0; target[j++] = els[i++];);
target.length = j - 1;
}
};
}
function Sizzle(selector, context, results, seed) {
var m, i, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document
nodeType = context ? context.nodeType : 9;
// Return early from calls with invalid selector or context
if (results = results || [], "string" != typeof selector || !selector || 1 !== nodeType && 9 !== nodeType && 11 !== nodeType) return results;
// Try to shortcut find operations (as opposed to filters) in HTML documents
if (!seed && (setDocument(context), context = context || document, documentIsHTML)) {
// If the selector is sufficiently simple, try using a "get*By*" DOM method
// (excepting DocumentFragment context, where the methods don't exist)
if (11 !== nodeType && (match = rquickExpr.exec(selector))) {
// ID selector
if (m = match[1]) {
// Document context
if (9 === nodeType) {
if (!(elem = context.getElementById(m))) return results;
// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if (elem.id === m) return results.push(elem), results;
// Element context
} else // Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if (newContext && (elem = newContext.getElementById(m)) && contains(context, elem) && elem.id === m) return results.push(elem), results;
} else if (match[2]) return push.apply(results, context.getElementsByTagName(selector)), results;
else if ((m = match[3]) && support.getElementsByClassName && context.getElementsByClassName) return push.apply(results, context.getElementsByClassName(m)), results;
}
// Take advantage of querySelectorAll
if (support.qsa && !nonnativeSelectorCache[selector + " "] && (!rbuggyQSA || !rbuggyQSA.test(selector)) && // Support: IE 8 only
// Exclude object elements
(1 !== nodeType || "object" !== context.nodeName.toLowerCase())) {
// qSA considers elements outside a scoping root when evaluating child or
// descendant combinators, which is not what we want.
// In such cases, we work around the behavior by prefixing every selector in the
// list with an ID selector referencing the scope context.
// The technique has to be used as well when a leading combinator is used
// as such selectors are not recognized by querySelectorAll.
// Thanks to Andrew Dupont for this technique.
if (newSelector = selector, newContext = context, 1 === nodeType && (rdescend.test(selector) || rcombinators.test(selector))) {
for(// Expand context for sibling selectors
(newContext = rsibling.test(selector) && testContext(context.parentNode) || context) === context && support.scope || ((nid = context.getAttribute("id")) ? nid = nid.replace(rcssescape, fcssescape) : context.setAttribute("id", nid = expando)), i = // Prefix every selector in the list
(groups = tokenize(selector)).length; i--;)groups[i] = (nid ? "#" + nid : ":scope") + " " + toSelector(groups[i]);
newSelector = groups.join(",");
}
try {
return push.apply(results, newContext.querySelectorAll(newSelector)), results;
} catch (qsaError) {
nonnativeSelectorCache(selector, !0);
} finally{
nid === expando && context.removeAttribute("id");
}
}
}
// All others
return select(selector.replace(rtrim, "$1"), context, results, seed);
}
/**
* Create key-value caches of limited size
* @returns {function(string, object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/ function createCache() {
var keys = [];
function cache(key, value) {
return keys.push(key + " ") > Expr.cacheLength && // Only keep the most recent entries
delete cache[keys.shift()], cache[key + " "] = value;
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/ function markFunction(fn) {
return fn[expando] = !0, fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created element and returns a boolean result
*/ function assert(fn) {
var el = document.createElement("fieldset");
try {
return !!fn(el);
} catch (e) {
return !1;
} finally{
el.parentNode && el.parentNode.removeChild(el), // release memory in IE
el = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/ function addHandle(attrs, handler) {
for(var arr = attrs.split("|"), i = arr.length; i--;)Expr.attrHandle[arr[i]] = handler;
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/ function siblingCheck(a, b) {
var cur = b && a, diff = cur && 1 === a.nodeType && 1 === b.nodeType && a.sourceIndex - b.sourceIndex;
// Use IE sourceIndex if available on both nodes
if (diff) return diff;
// Check if b follows a
if (cur) {
for(; cur = cur.nextSibling;)if (cur === b) return -1;
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for :enabled/:disabled
* @param {Boolean} disabled true for :disabled; false for :enabled
*/ function createDisabledPseudo(disabled) {
// Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable
return function(elem) {
// Only certain elements can match :enabled or :disabled
// https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled
// https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled
if ("form" in elem) return(// Check for inherited disabledness on relevant non-disabled elements:
// * listed form-associated elements in a disabled fieldset
// https://html.spec.whatwg.org/multipage/forms.html#category-listed
// https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled
// * option elements in a disabled optgroup
// https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled
// All such elements have a "form" property.
elem.parentNode && !1 === elem.disabled ? // Option elements defer to a parent optgroup if present
"label" in elem ? "label" in elem.parentNode ? elem.parentNode.disabled === disabled : elem.disabled === disabled : elem.isDisabled === disabled || // Where there is no isDisabled, check manually
/* jshint -W018 */ !disabled !== elem.isDisabled && inDisabledFieldset(elem) === disabled : elem.disabled === disabled);
return "label" in elem && elem.disabled === disabled;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/ function createPositionalPseudo(fn) {
return markFunction(function(argument) {
return argument *= 1, markFunction(function(seed, matches) {
// Match elements found at the specified indexes
for(var j, matchIndexes = fn([], seed.length, argument), i = matchIndexes.length; i--;)seed[j = matchIndexes[i]] && (seed[j] = !(matches[j] = seed[j]));
});
});
}
/**
* Checks a node for validity as a Sizzle context
* @param {Element|Object=} context
* @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
*/ function testContext(context) {
return context && void 0 !== context.getElementsByTagName && context;
}
// Add button/input type pseudos
for(i in // Expose support vars for convenience
support = Sizzle.support = {}, /**
* Detects XML nodes
* @param {Element|Object} elem An element or a document
* @returns {Boolean} True iff elem is a non-HTML XML node
*/ isXML = Sizzle.isXML = function(elem) {
var namespace = elem.namespaceURI, docElem = (elem.ownerDocument || elem).documentElement;
// Support: IE <=8
// Assume HTML when documentElement doesn't yet exist, such as inside loading iframes
// https://bugs.jquery.com/ticket/4833
return !rhtml.test(namespace || docElem && docElem.nodeName || "HTML");
}, /**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/ setDocument = Sizzle.setDocument = function(node) {
var hasCompare, subWindow, doc = node ? node.ownerDocument || node : preferredDoc;
return doc != document && 9 === doc.nodeType && doc.documentElement && (docElem = // Update global variables
(document = doc).documentElement, documentIsHTML = !isXML(document), preferredDoc != document && (subWindow = document.defaultView) && subWindow.top !== subWindow && (subWindow.addEventListener ? subWindow.addEventListener("unload", unloadHandler, !1) : subWindow.attachEvent && subWindow.attachEvent("onunload", unloadHandler)), // Support: IE 8 - 11+, Edge 12 - 18+, Chrome <=16 - 25 only, Firefox <=3.6 - 31 only,
// Safari 4 - 5 only, Opera <=11.6 - 12.x only
// IE/Edge & older browsers don't support the :scope pseudo-class.
// Support: Safari 6.0 only
// Safari 6.0 supports :scope but it's an alias of :root there.
support.scope = assert(function(el) {
return docElem.appendChild(el).appendChild(document.createElement("div")), void 0 !== el.querySelectorAll && !el.querySelectorAll(":scope fieldset div").length;
}), /* Attributes
---------------------------------------------------------------------- */ // Support: IE<8
// Verify that getAttribute really returns attributes and not properties
// (excepting IE8 booleans)
support.attributes = assert(function(el) {
return el.className = "i", !el.getAttribute("className");
}), /* getElement(s)By*
---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function(el) {
return el.appendChild(document.createComment("")), !el.getElementsByTagName("*").length;
}), // Support: IE<9
support.getElementsByClassName = rnative.test(document.getElementsByClassName), // Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programmatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function(el) {
return docElem.appendChild(el).id = expando, !document.getElementsByName || !document.getElementsByName(expando).length;
}), support.getById ? (Expr.filter.ID = function(id) {
var attrId = id.replace(runescape, funescape);
return function(elem) {
return elem.getAttribute("id") === attrId;
};
}, Expr.find.ID = function(id, context) {
if (void 0 !== context.getElementById && documentIsHTML) {
var elem = context.getElementById(id);
return elem ? [
elem
] : [];
}
}) : (Expr.filter.ID = function(id) {
var attrId = id.replace(runescape, funescape);
return function(elem) {
var node = void 0 !== elem.getAttributeNode && elem.getAttributeNode("id");
return node && node.value === attrId;
};
}, // Support: IE 6 - 7 only
// getElementById is not reliable as a find shortcut
Expr.find.ID = function(id, context) {
if (void 0 !== context.getElementById && documentIsHTML) {
var node, i, elems, elem = context.getElementById(id);
if (elem) {
if (// Verify the id attribute
(node = elem.getAttributeNode("id")) && node.value === id) return [
elem
];
for(// Fall back on getElementsByName
elems = context.getElementsByName(id), i = 0; elem = elems[i++];)if ((node = elem.getAttributeNode("id")) && node.value === id) return [
elem
];
}
return [];
}
}), // Tag
Expr.find.TAG = support.getElementsByTagName ? function(tag, context) {
return void 0 !== context.getElementsByTagName ? context.getElementsByTagName(tag) : support.qsa ? context.querySelectorAll(tag) : void 0;
} : function(tag, context) {
var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
results = context.getElementsByTagName(tag);
// Filter out possible comments
if ("*" === tag) {
for(; elem = results[i++];)1 === elem.nodeType && tmp.push(elem);
return tmp;
}
return results;
}, // Class
Expr.find.CLASS = support.getElementsByClassName && function(className, context) {
if (void 0 !== context.getElementsByClassName && documentIsHTML) return context.getElementsByClassName(className);
}, /* QSA/matchesSelector
---------------------------------------------------------------------- */ // QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [], // qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See https://bugs.jquery.com/ticket/13378
rbuggyQSA = [], (support.qsa = rnative.test(document.querySelectorAll)) && (// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function(el) {
var input;
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// https://bugs.jquery.com/ticket/12359
docElem.appendChild(el).innerHTML = "<a id='" + expando + "'></a><select id='" + expando + "-\r\\' msallowcapture=''><option selected=''></option></select>", el.querySelectorAll("[msallowcapture^='']").length && rbuggyQSA.push("[*^$]=" + whitespace + "*(?:''|\"\")"), el.querySelectorAll("[selected]").length || rbuggyQSA.push("\\[" + whitespace + "*(?:value|" + booleans + ")"), el.querySelectorAll("[id~=" + expando + "-]").length || rbuggyQSA.push("~="), // Support: IE 11+, Edge 15 - 18+
// IE 11/Edge don't find elements on a `[name='']` query in some cases.
// Adding a temporary attribute to the document before the selection works
// around the issue.
// Interestingly, IE 10 & older don't seem to have the issue.
(input = document.createElement("input")).setAttribute("name", ""), el.appendChild(input), el.querySelectorAll("[name='']").length || rbuggyQSA.push("\\[" + whitespace + "*name" + whitespace + "*=" + whitespace + "*(?:''|\"\")"), el.querySelectorAll(":checked").length || rbuggyQSA.push(":checked"), el.querySelectorAll("a#" + expando + "+*").length || rbuggyQSA.push(".#.+[+~]"), // Support: Firefox <=3.6 - 5 only
// Old Firefox doesn't throw on a badly-escaped identifier.
el.querySelectorAll("\\\f"), rbuggyQSA.push("[\\r\\n\\f]");
}), assert(function(el) {
el.innerHTML = "<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = document.createElement("input");
input.setAttribute("type", "hidden"), el.appendChild(input).setAttribute("name", "D"), el.querySelectorAll("[name=d]").length && rbuggyQSA.push("name" + whitespace + "*[*^$|!~]?="), 2 !== el.querySelectorAll(":enabled").length && rbuggyQSA.push(":enabled", ":disabled"), // Support: IE9-11+
// IE's :disabled selector does not pick up the children of disabled fieldsets
docElem.appendChild(el).disabled = !0, 2 !== el.querySelectorAll(":disabled").length && rbuggyQSA.push(":enabled", ":disabled"), // Support: Opera 10 - 11 only
// Opera 10-11 does not throw on post-comma invalid pseudos
el.querySelectorAll("*,:x"), rbuggyQSA.push(",.*:");
})), (support.matchesSelector = rnative.test(matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector)) && assert(function(el) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call(el, "*"), // This should fail with an exception
// Gecko does not error, returns false instead
matches.call(el, "[s!='']:x"), rbuggyMatches.push("!=", pseudos);
}), rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join("|")), rbuggyMatches = rbuggyMatches.length && new RegExp(rbuggyMatches.join("|")), // Element contains another
// Purposefully self-exclusive
// As in, an element does not contain itself
contains = /* Contains
---------------------------------------------------------------------- */ (hasCompare = rnative.test(docElem.compareDocumentPosition)) || rnative.test(docElem.contains) ? function(a, b) {
var adown = 9 === a.nodeType ? a.documentElement : a, bup = b && b.parentNode;
return a === bup || !!(bup && 1 === bup.nodeType && (adown.contains ? adown.contains(bup) : a.compareDocumentPosition && 16 & a.compareDocumentPosition(bup)));
} : function(a, b) {
if (b) {
for(; b = b.parentNode;)if (b === a) return !0;
}
return !1;
}, /* Sorting
---------------------------------------------------------------------- */ // Document order sorting
sortOrder = hasCompare ? function(a, b) {
// Flag for duplicate removal
if (a === b) return hasDuplicate = !0, 0;
// Sort on method existence if only one input has compareDocumentPosition
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
return compare || (1 & // Calculate position if both inputs belong to the same document
// Support: IE 11+, Edge 17 - 18+
// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
// two documents; shallow comparisons work.
// eslint-disable-next-line eqeqeq
(compare = (a.ownerDocument || a) == (b.ownerDocument || b) ? a.compareDocumentPosition(b) : // Otherwise we know they are disconnected
1) || !support.sortDetached && b.compareDocumentPosition(a) === compare ? // Choose the first element that is related to our preferred document
// Support: IE 11+, Edge 17 - 18+
// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
// two documents; shallow comparisons work.
// eslint-disable-next-line eqeqeq
a == document || a.ownerDocument == preferredDoc && contains(preferredDoc, a) ? -1 : b == document || b.ownerDocument == preferredDoc && contains(preferredDoc, b) ? 1 : sortInput ? indexOf(sortInput, a) - indexOf(sortInput, b) : 0 : 4 & compare ? -1 : 1);
} : function(a, b) {
// Exit early if the nodes are identical
if (a === b) return hasDuplicate = !0, 0;
var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [
a
], bp = [
b
];
// Parentless nodes are either documents or disconnected
if (!aup || !bup) // Support: IE 11+, Edge 17 - 18+
// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
// two documents; shallow comparisons work.
/* eslint-disable eqeqeq */ return a == document ? -1 : b == document ? 1 : /* eslint-enable eqeqeq */ aup ? -1 : bup ? 1 : sortInput ? indexOf(sortInput, a) - indexOf(sortInput, b) : 0;
if (aup === bup) return siblingCheck(a, b);
for(// Otherwise we need full lists of their ancestors for comparison
cur = a; cur = cur.parentNode;)ap.unshift(cur);
for(cur = b; cur = cur.parentNode;)bp.unshift(cur);
// Walk down the tree looking for a discrepancy
for(; ap[i] === bp[i];)i++;
return i ? // Do a sibling check if the nodes have a common ancestor
siblingCheck(ap[i], bp[i]) : // Otherwise nodes in our document sort first
// Support: IE 11+, Edge 17 - 18+
// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
// two documents; shallow comparisons work.
/* eslint-disable eqeqeq */ ap[i] == preferredDoc ? -1 : +(bp[i] == preferredDoc);
}), document;
}, Sizzle.matches = function(expr, elements) {
return Sizzle(expr, null, null, elements);
}, Sizzle.matchesSelector = function(elem, expr) {
if (setDocument(elem), support.matchesSelector && documentIsHTML && !nonnativeSelectorCache[expr + " "] && (!rbuggyMatches || !rbuggyMatches.test(expr)) && (!rbuggyQSA || !rbuggyQSA.test(expr))) try {
var ret = matches.call(elem, expr);
// IE 9's matchesSelector returns false on disconnected nodes
if (ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && 11 !== elem.document.nodeType) return ret;
} catch (e) {
nonnativeSelectorCache(expr, !0);
}
return Sizzle(expr, document, null, [
elem
]).length > 0;
}, Sizzle.contains = function(context, elem) {
return (context.ownerDocument || context) != document && setDocument(context), contains(context, elem);
}, Sizzle.attr = function(elem, name) {
// Set document vars if needed
// Support: IE 11+, Edge 17 - 18+
// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
// two documents; shallow comparisons work.
// eslint-disable-next-line eqeqeq
(elem.ownerDocument || elem) != document && setDocument(elem);
var fn = Expr.attrHandle[name.toLowerCase()], // Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call(Expr.attrHandle, name.toLowerCase()) ? fn(elem, name, !documentIsHTML) : void 0;
return void 0 !== val ? val : support.attributes || !documentIsHTML ? elem.getAttribute(name) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null;
}, Sizzle.escape = function(sel) {
return (sel + "").replace(rcssescape, fcssescape);
}, Sizzle.error = function(msg) {
throw Error("Syntax error, unrecognized expression: " + msg);
}, /**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/ Sizzle.uniqueSort = function(results) {
var elem, duplicates = [], j = 0, i = 0;
if (// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates, sortInput = !support.sortStable && results.slice(0), results.sort(sortOrder), hasDuplicate) {
for(; elem = results[i++];)elem === results[i] && (j = duplicates.push(i));
for(; j--;)results.splice(duplicates[j], 1);
}
return(// Clear input after sorting to release objects
// See https://github.com/jquery/sizzle/pull/225
sortInput = null, results);
}, /**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/ getText = Sizzle.getText = function(elem) {
var node, ret = "", i = 0, nodeType = elem.nodeType;
if (nodeType) {
if (1 === nodeType || 9 === nodeType || 11 === nodeType) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (jQuery #11153)
if ("string" == typeof elem.textContent) return elem.textContent;
// Traverse its children
for(elem = elem.firstChild; elem; elem = elem.nextSibling)ret += getText(elem);
} else if (3 === nodeType || 4 === nodeType) return elem.nodeValue;
} else // If no nodeType, this is expected to be an array
for(; node = elem[i++];)// Do not traverse comment nodes
ret += getText(node);
// Do not include comment or processing instruction nodes
return ret;
}, (Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": {
dir: "parentNode",
first: !0
},
" ": {
dir: "parentNode"
},
"+": {
dir: "previousSibling",
first: !0
},
"~": {
dir: "previousSibling"
}
},
preFilter: {
ATTR: function(match) {
return match[1] = match[1].replace(runescape, funescape), // Move the given value to match[3] whether quoted or unquoted
match[3] = (match[3] || match[4] || match[5] || "").replace(runescape, funescape), "~=" === match[2] && (match[3] = " " + match[3] + " "), match.slice(0, 4);
},
CHILD: function(match) {
return(/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/ match[1] = match[1].toLowerCase(), "nth" === match[1].slice(0, 3) ? (match[3] || Sizzle.error(match[0]), // numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +(match[4] ? match[5] + (match[6] || 1) : 2 * ("even" === match[3] || "odd" === match[3])), match[5] = +(match[7] + match[8] || "odd" === match[3])) : match[3] && Sizzle.error(match[0]), match);
},
PSEUDO: function(match) {
var excess, unquoted = !match[6] && match[2];
return matchExpr.CHILD.test(match[0]) ? null : (match[3] ? match[2] = match[4] || match[5] || "" : unquoted && rpseudo.test(unquoted) && // Get excess from tokenize (recursively)
(excess = tokenize(unquoted, !0)) && // advance to the next closing parenthesis
(excess = unquoted.indexOf(")", unquoted.length - excess) - unquoted.length) && (// excess is a negative index
match[0] = match[0].slice(0, excess), match[2] = unquoted.slice(0, excess)), match.slice(0, 3));
}
},
filter: {
TAG: function(nodeNameSelector) {
var nodeName = nodeNameSelector.replace(runescape, funescape).toLowerCase();
return "*" === nodeNameSelector ? function() {
return !0;
} : function(elem) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
CLASS: function(className) {
var pattern = classCache[className + " "];
return pattern || (pattern = RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)"), classCache(className, function(elem) {
return pattern.test("string" == typeof elem.className && elem.className || void 0 !== elem.getAttribute && elem.getAttribute("class") || "");
}));
},
ATTR: function(name, operator, check) {
return function(elem) {
var result = Sizzle.attr(elem, name);
return null == result ? "!=" === operator : !operator || (result += "", "=" === operator ? result === check : "!=" === operator ? result !== check : "^=" === operator ? check && 0 === result.indexOf(check) : "*=" === operator ? check && result.indexOf(check) > -1 : "$=" === operator ? check && result.slice(-check.length) === check : "~=" === operator ? (" " + result.replace(rwhitespace, " ") + " ").indexOf(check) > -1 : "|=" === operator && (result === check || result.slice(0, check.length + 1) === check + "-"));
/* eslint-enable max-len */ };
},
CHILD: function(type, what, _argument, first, last) {
var simple = "nth" !== type.slice(0, 3), forward = "last" !== type.slice(-4), ofType = "of-type" === what;
return 1 === first && 0 === last ? // Shortcut for :nth-*(n)
function(elem) {
return !!elem.parentNode;
} : function(elem, _context, xml) {
var cache, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = !1;
if (parent) {
// :(first|last|only)-(child|of-type)
if (simple) {
for(; dir;){
for(node = elem; node = node[dir];)if (ofType ? node.nodeName.toLowerCase() === name : 1 === node.nodeType) return !1;
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = "only" === type && !start && "nextSibling";
}
return !0;
}
// non-xml :nth-child(...) stores cache data on `parent`
if (start = [
forward ? parent.firstChild : parent.lastChild
], forward && useCache) {
for(diff = (nodeIndex = (cache = // Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
(uniqueCache = (outerCache = // Seek `elem` from a previously-cached index
// ...in a gzip-friendly way
(node = parent)[expando] || (node[expando] = {}))[node.uniqueID] || (outerCache[node.uniqueID] = {}))[type] || [])[0] === dirruns && cache[1]) && cache[2], node = nodeIndex && parent.childNodes[nodeIndex]; node = ++nodeIndex && node && node[dir] || // Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop();)// When found, cache indexes on `parent` and break
if (1 === node.nodeType && ++diff && node === elem) {
uniqueCache[type] = [
dirruns,
nodeIndex,
diff
];
break;
}
} else // xml :nth-child(...)
// or :nth-last-child(...) or :nth(-last)?-of-type(...)
if (useCache && (diff = nodeIndex = (cache = // Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
(uniqueCache = (outerCache = // ...in a gzip-friendly way
(node = elem)[expando] || (node[expando] = {}))[node.uniqueID] || (outerCache[node.uniqueID] = {}))[type] || [])[0] === dirruns && cache[1]), !1 === diff) // Use the same loop as above to seek `elem` from the start
for(; (node = ++nodeIndex && node && node[dir] || (diff = nodeIndex = 0) || start.pop()) && (!((ofType ? node.nodeName.toLowerCase() === name : 1 === node.nodeType) && ++diff) || (useCache && (// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
(uniqueCache = (outerCache = node[expando] || (node[expando] = {}))[node.uniqueID] || (outerCache[node.uniqueID] = {}))[type] = [
dirruns,
diff
]), node !== elem)););
return(// Incorporate the offset, then check against cycle size
(diff -= last) === first || diff % first == 0 && diff / first >= 0);
}
};
},
PSEUDO: function(pseudo, argument) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args, fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle.error("unsupported pseudo: " + pseudo);
return(// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
fn[expando] ? fn(argument) : fn.length > 1 ? (args = [
pseudo,
pseudo,
"",
argument
], Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function(seed, matches) {
for(var idx, matched = fn(seed, argument), i = matched.length; i--;)idx = indexOf(seed, matched[i]), seed[idx] = !(matches[idx] = matched[i]);
}) : function(elem) {
return fn(elem, 0, args);
}) : fn);
}
},
pseudos: {
// Potentially complex pseudos
not: markFunction(function(selector) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [], results = [], matcher = compile(selector.replace(rtrim, "$1"));
return matcher[expando] ? markFunction(function(seed, matches, _context, xml) {
// Match elements unmatched by `matcher`
for(var elem, unmatched = matcher(seed, null, xml, []), i = seed.length; i--;)(elem = unmatched[i]) && (seed[i] = !(matches[i] = elem));
}) : function(elem, _context, xml) {
return input[0] = elem, matcher(input, null, xml, results), // Don't keep the element (issue #299)
input[0] = null, !results.pop();
};
}),
has: markFunction(function(selector) {
return function(elem) {
return Sizzle(selector, elem).length > 0;
};
}),
contains: markFunction(function(text) {
return text = text.replace(runescape, funescape), function(elem) {
return (elem.textContent || getText(elem)).indexOf(text) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
lang: markFunction(function(lang) {
return ridentifier.test(lang || "") || Sizzle.error("unsupported lang: " + lang), lang = lang.replace(runescape, funescape).toLowerCase(), function(elem) {
var elemLang;
do if (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) return (elemLang = elemLang.toLowerCase()) === lang || 0 === elemLang.indexOf(lang + "-");
while ((elem = elem.parentNode) && 1 === elem.nodeType)
return !1;
};
}),
// Miscellaneous
target: function(elem) {
var hash = window1.location && window1.location.hash;
return hash && hash.slice(1) === elem.id;
},
root: function(elem) {
return elem === docElem;
},
focus: function(elem) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
enabled: createDisabledPseudo(!1),
disabled: createDisabledPseudo(!0),
checked: function(elem) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return "input" === nodeName && !!elem.checked || "option" === nodeName && !!elem.selected;
},
selected: function(elem) {
return elem.parentNode && // eslint-disable-next-line no-unused-expressions
elem.parentNode.selectedIndex, !0 === elem.selected;
},
// Contents
empty: function(elem) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
// but not by others (comment: 8; processing instruction: 7; etc.)
// nodeType < 6 works because attributes (2) do not appear as children
for(elem = elem.firstChild; elem; elem = elem.nextSibling)if (elem.nodeType < 6) return !1;
return !0;
},
parent: function(elem) {
return !Expr.pseudos.empty(elem);
},
// Element/input types
header: function(elem) {
return rheader.test(elem.nodeName);
},
input: function(elem) {
return rinputs.test(elem.nodeName);
},
button: function(elem) {
var name = elem.nodeName.toLowerCase();
return "input" === name && "button" === elem.type || "button" === name;
},
text: function(elem) {
var attr;
return "input" === elem.nodeName.toLowerCase() && "text" === elem.type && // Support: IE<8
// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
(null == (attr = elem.getAttribute("type")) || "text" === attr.toLowerCase());
},
// Position-in-collection
first: createPositionalPseudo(function() {
return [
0
];
}),
last: createPositionalPseudo(function(_matchIndexes, length) {
return [
length - 1
];
}),
eq: createPositionalPseudo(function(_matchIndexes, length, argument) {
return [
argument < 0 ? argument + length : argument
];
}),
even: createPositionalPseudo(function(matchIndexes, length) {
for(var i = 0; i < length; i += 2)matchIndexes.push(i);
return matchIndexes;
}),
odd: createPositionalPseudo(function(matchIndexes, length) {
for(var i = 1; i < length; i += 2)matchIndexes.push(i);
return matchIndexes;
}),
lt: createPositionalPseudo(function(matchIndexes, length, argument) {
for(var i = argument < 0 ? argument + length : argument > length ? length : argument; --i >= 0;)matchIndexes.push(i);
return matchIndexes;
}),
gt: createPositionalPseudo(function(matchIndexes, length, argument) {
for(var i = argument < 0 ? argument + length : argument; ++i < length;)matchIndexes.push(i);
return matchIndexes;
})
}
}).pseudos.nth = Expr.pseudos.eq, {
radio: !0,
checkbox: !0,
file: !0,
password: !0,
image: !0
})Expr.pseudos[i] = /**
* Returns a function to use in pseudos for input types
* @param {String} type
*/ function(type) {
return function(elem) {
return "input" === elem.nodeName.toLowerCase() && elem.type === type;
};
}(i);
for(i in {
submit: !0,
reset: !0
})Expr.pseudos[i] = /**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/ function(type) {
return function(elem) {
var name = elem.nodeName.toLowerCase();
return ("input" === name || "button" === name) && elem.type === type;
};
}(i);
// Easy API for creating new setFilters
function setFilters() {}
function toSelector(tokens) {
for(var i = 0, len = tokens.length, selector = ""; i < len; i++)selector += tokens[i].value;
return selector;
}
function addCombinator(matcher, combinator, base) {
var dir = combinator.dir, skip = combinator.next, key = skip || dir, checkNonElements = base && "parentNode" === key, doneName = done++;
return combinator.first ? // Check against closest ancestor/preceding element
function(elem, context, xml) {
for(; elem = elem[dir];)if (1 === elem.nodeType || checkNonElements) return matcher(elem, context, xml);
return !1;
} : // Check against all ancestor/preceding elements
function(elem, context, xml) {
var oldCache, uniqueCache, outerCache, newCache = [
dirruns,
doneName
];
// We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
if (xml) {
for(; elem = elem[dir];)if ((1 === elem.nodeType || checkNonElements) && matcher(elem, context, xml)) return !0;
} else for(; elem = elem[dir];)if (1 === elem.nodeType || checkNonElements) {
if (// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = (outerCache = elem[expando] || (elem[expando] = {}))[elem.uniqueID] || (outerCache[elem.uniqueID] = {}), skip && skip === elem.nodeName.toLowerCase()) elem = elem[dir] || elem;
else if ((oldCache = uniqueCache[key]) && oldCache[0] === dirruns && oldCache[1] === doneName) // Assign to newCache so results back-propagate to previous elements
return newCache[2] = oldCache[2];
else // A match means we're done; a fail means we have to keep checking
if (// Reuse newcache so results back-propagate to previous elements
uniqueCache[key] = newCache, newCache[2] = matcher(elem, context, xml)) return !0;
}
return !1;
};
}
function elementMatcher(matchers) {
return matchers.length > 1 ? function(elem, context, xml) {
for(var i = matchers.length; i--;)if (!matchers[i](elem, context, xml)) return !1;
return !0;
} : matchers[0];
}
function condense(unmatched, map, filter, context, xml) {
for(var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = null != map; i < len; i++)(elem = unmatched[i]) && (!filter || filter(elem, context, xml)) && (newUnmatched.push(elem), mapped && map.push(i));
return newUnmatched;
}
return setFilters.prototype = Expr.filters = Expr.pseudos, Expr.setFilters = new setFilters(), tokenize = Sizzle.tokenize = function(selector, parseOnly) {
var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[selector + " "];
if (cached) return parseOnly ? 0 : cached.slice(0);
for(soFar = selector, groups = [], preFilters = Expr.preFilter; soFar;){
// Filters
for(type in (!matched || (match = rcomma.exec(soFar))) && (match && // Don't consume trailing commas as valid
(soFar = soFar.slice(match[0].length) || soFar), groups.push(tokens = [])), matched = !1, (match = rcombinators.exec(soFar)) && (matched = match.shift(), tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace(rtrim, " ")
}), soFar = soFar.slice(matched.length)), Expr.filter)(match = matchExpr[type].exec(soFar)) && (!preFilters[type] || (match = preFilters[type](match))) && (matched = match.shift(), tokens.push({
value: matched,
type: type,
matches: match
}), soFar = soFar.slice(matched.length));
if (!matched) break;
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) : // Cache the tokens
tokenCache(selector, groups).slice(0);
}, compile = Sizzle.compile = function(selector, match /* Internal Use Only */ ) {
var bySet, byElement, superMatcher, i, setMatchers = [], elementMatchers = [], cached = compilerCache[selector + " "];
if (!cached) {
for(match || (match = tokenize(selector)), i = match.length; i--;)(cached = function matcherFromTokens(tokens) {
for(var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[tokens[0].type], implicitRelative = leadingRelative || Expr.relative[" "], i = +!!leadingRelative, // The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator(function(elem) {
return elem === checkContext;
}, implicitRelative, !0), matchAnyContext = addCombinator(function(elem) {
return indexOf(checkContext, elem) > -1;
}, implicitRelative, !0), matchers = [
function(elem, context, xml) {
var ret = !leadingRelative && (xml || context !== outermostContext) || ((checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml));
return(// Avoid hanging onto element (issue #299)
checkContext = null, ret);
}
]; i < len; i++)if (matcher = Expr.relative[tokens[i].type]) matchers = [
addCombinator(elementMatcher(matchers), matcher)
];
else {
// Return special upon seeing a positional matcher
if ((matcher = Expr.filter[tokens[i].type].apply(null, tokens[i].matches))[expando]) {
for(// Find the next relative operator (if any) for proper handling
j = ++i; j < len && !Expr.relative[tokens[j].type]; j++);
return function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) {
return postFilter && !postFilter[expando] && (postFilter = setMatcher(postFilter)), postFinder && !postFinder[expando] && (postFinder = setMatcher(postFinder, postSelector)), markFunction(function(seed, results, context, xml) {
var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context
elems = seed || function(selector, contexts, results) {
for(var i = 0, len = contexts.length; i < len; i++)Sizzle(selector, contexts[i], results);
return results;
}(selector || "*", context.nodeType ? [
context
] : context, []), // Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && (seed || !selector) ? condense(elems, preMap, preFilter, context, xml) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || (seed ? preFilter : preexisting || postFilter) ? // ...intermediate processing is necessary
[] : // ...otherwise use results directly
results : matcherIn;
// Apply postFilter
if (matcher && matcher(matcherIn, matcherOut, context, xml), postFilter) for(temp = condense(matcherOut, postMap), postFilter(temp, [], context, xml), // Un-match failing elements by moving them back to matcherIn
i = temp.length; i--;)(elem = temp[i]) && (matcherOut[postMap[i]] = !(matcherIn[postMap[i]] = elem));
if (seed) {
if (postFinder || preFilter) {
if (postFinder) {
for(// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [], i = matcherOut.length; i--;)(elem = matcherOut[i]) && // Restore matcherIn since elem is not yet a final match
temp.push(matcherIn[i] = elem);
postFinder(null, matcherOut = [], temp, xml);
}
for(// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length; i--;)(elem = matcherOut[i]) && (temp = postFinder ? indexOf(seed, elem) : preMap[i]) > -1 && (seed[temp] = !(results[temp] = elem));
}
} else matcherOut = condense(matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut), postFinder ? postFinder(null, results, matcherOut, xml) : push.apply(results, matcherOut);
});
}(i > 1 && elementMatcher(matchers), i > 1 && toSelector(// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice(0, i - 1).concat({
value: " " === tokens[i - 2].type ? "*" : ""
})).replace(rtrim, "$1"), matcher, i < j && matcherFromTokens(tokens.slice(i, j)), j < len && matcherFromTokens(tokens = tokens.slice(j)), j < len && toSelector(tokens));
}
matchers.push(matcher);
}
return elementMatcher(matchers);
}(match[i]))[expando] ? setMatchers.push(cached) : elementMatchers.push(cached);
// Save selector and tokenization
// Cache the compiled function
(cached = compilerCache(selector, (bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function(seed, context, xml, results, outermost) {
var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find.TAG("*", outermost), // Use integer dirruns iff this is the outermost matcher
dirrunsUnique = dirruns += null == contextBackup ? 1 : Math.random() || 0.1, len = elems.length;
// Add elements passing elementMatchers directly to results
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for(outermost && // Support: IE 11+, Edge 17 - 18+
// IE/Edge sometimes throw a "Permission denied" error when strict-comparing
// two documents; shallow comparisons work.
// eslint-disable-next-line eqeqeq
(outermostContext = context == document || context || outermost); i !== len && null != (elem = elems[i]); i++){
if (byElement && elem) {
for(j = 0, context || elem.ownerDocument == document || (setDocument(elem), xml = !documentIsHTML); matcher = elementMatchers[j++];)if (matcher(elem, context || document, xml)) {
results.push(elem);
break;
}
outermost && (dirruns = dirrunsUnique);
}
// Track unmatched elements for set filters
bySet && ((elem = !matcher && elem) && matchedCount--, seed && unmatched.push(elem));
}
// Apply set filters to unmatched elements
// NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
// equals `i`), unless we didn't visit _any_ elements in the above loop because we have
// no element matchers and no seed.
// Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
// case, which will result in a "00" `matchedCount` that differs from `i` but is also
// numerically zero.
if (// `i` is now the count of elements visited above, and adding it to `matchedCount`
// makes the latter nonnegative.
matchedCount += i, bySet && i !== matchedCount) {
for(j = 0; matcher = setMatchers[j++];)matcher(unmatched, setMatched, context, xml);
if (seed) {
// Reintegrate element matches to eliminate the need for sorting
if (matchedCount > 0) for(; i--;)unmatched[i] || setMatched[i] || (setMatched[i] = pop.call(results));
// Discard index placeholder values to get only actual matches
setMatched = condense(setMatched);
}
// Add matches to results
push.apply(results, setMatched), outermost && !seed && setMatched.length > 0 && matchedCount + setMatchers.length > 1 && Sizzle.uniqueSort(results);
}
return outermost && (dirruns = dirrunsUnique, outermostContext = contextBackup), unmatched;
}, bySet ? markFunction(superMatcher) : superMatcher))).selector = selector;
}
return cached;
}, /**
* A low-level selection function that works with Sizzle's compiled
* selector functions
* @param {String|Function} selector A selector or a pre-compiled
* selector function built with Sizzle.compile
* @param {Element} context
* @param {Array} [results]
* @param {Array} [seed] A set of elements to match against
*/ select = Sizzle.select = function(selector, context, results, seed) {
var i, tokens, token, type, find, compiled = "function" == typeof selector && selector, match = !seed && tokenize(selector = compiled.selector || selector);
// Try to minimize operations if there is only one selector in the list and no seed
// (the latter of which guarantees us context)
if (results = results || [], 1 === match.length) {
if (// Reduce context if the leading compound selector is an ID
(tokens = match[0] = match[0].slice(0)).length > 2 && "ID" === (token = tokens[0]).type && 9 === context.nodeType && documentIsHTML && Expr.relative[tokens[1].type]) {
if (!(context = (Expr.find.ID(token.matches[0].replace(runescape, funescape), context) || [])[0])) return results;
compiled && (context = context.parentNode), selector = selector.slice(tokens.shift().value.length);
}
for(// Fetch a seed set for right-to-left matching
i = matchExpr.needsContext.test(selector) ? 0 : tokens.length; // Abort if we hit a combinator
i-- && (token = tokens[i], !Expr.relative[type = token.type]);)if ((find = Expr.find[type]) && (seed = find(token.matches[0].replace(runescape, funescape), rsibling.test(tokens[0].type) && testContext(context.parentNode) || context))) {
if (// If seed is empty or no tokens remain, we can return early
tokens.splice(i, 1), !(selector = seed.length && toSelector(tokens))) return push.apply(results, seed), results;
break;
}
}
return(// Compile and execute a filtering function if one is not provided
// Provide `match` to avoid retokenization if we modified the selector above
(compiled || compile(selector, match))(seed, context, !documentIsHTML, results, !context || rsibling.test(selector) && testContext(context.parentNode) || context), results);
}, // One-time assignments
// Sort stability
support.sortStable = expando.split("").sort(sortOrder).join("") === expando, // Support: Chrome 14-35+
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate, // Initialize against the default document
setDocument(), // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function(el) {
// Should return 1, but returns 4 (following)
return 1 & el.compareDocumentPosition(document.createElement("fieldset"));
}), assert(function(el) {
return el.innerHTML = "<a href='#'></a>", "#" === el.firstChild.getAttribute("href");
}) || addHandle("type|href|height|width", function(elem, name, isXML) {
if (!isXML) return elem.getAttribute(name, "type" === name.toLowerCase() ? 1 : 2);
}), support.attributes && assert(function(el) {
return el.innerHTML = "<input/>", el.firstChild.setAttribute("value", ""), "" === el.firstChild.getAttribute("value");
}) || addHandle("value", function(elem, _name, isXML) {
if (!isXML && "input" === elem.nodeName.toLowerCase()) return elem.defaultValue;
}), assert(function(el) {
return null == el.getAttribute("disabled");
}) || addHandle(booleans, function(elem, name, isXML) {
var val;
if (!isXML) return !0 === elem[name] ? name.toLowerCase() : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null;
}), Sizzle;
}(window1);
jQuery.find = Sizzle, jQuery.expr = Sizzle.selectors, // Deprecated
jQuery.expr[":"] = jQuery.expr.pseudos, jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort, jQuery.text = Sizzle.getText, jQuery.isXMLDoc = Sizzle.isXML, jQuery.contains = Sizzle.contains, jQuery.escapeSelector = Sizzle.escape;
var dir = function(elem, dir, until) {
for(var matched = [], truncate = void 0 !== until; (elem = elem[dir]) && 9 !== elem.nodeType;)if (1 === elem.nodeType) {
if (truncate && jQuery(elem).is(until)) break;
matched.push(elem);
}
return matched;
}, siblings = function(n, elem) {
for(var matched = []; n; n = n.nextSibling)1 === n.nodeType && n !== elem && matched.push(n);
return matched;
}, rneedsContext = jQuery.expr.match.needsContext;
function nodeName(elem, name) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
}
var rsingleTag = /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;
// Implement the identical functionality for filter and not
function winnow(elements, qualifier, not) {
return isFunction(qualifier) ? jQuery.grep(elements, function(elem, i) {
return !!qualifier.call(elem, i, elem) !== not;
}) : qualifier.nodeType ? jQuery.grep(elements, function(elem) {
return elem === qualifier !== not;
}) : "string" != typeof qualifier ? jQuery.grep(elements, function(elem) {
return indexOf.call(qualifier, elem) > -1 !== not;
}) : jQuery.filter(qualifier, elements, not);
}
jQuery.filter = function(expr, elems, not) {
var elem = elems[0];
return (not && (expr = ":not(" + expr + ")"), 1 === elems.length && 1 === elem.nodeType) ? jQuery.find.matchesSelector(elem, expr) ? [
elem
] : [] : jQuery.find.matches(expr, jQuery.grep(elems, function(elem) {
return 1 === elem.nodeType;
}));
}, jQuery.fn.extend({
find: function(selector) {
var i, ret, len = this.length, self = this;
if ("string" != typeof selector) return this.pushStack(jQuery(selector).filter(function() {
for(i = 0; i < len; i++)if (jQuery.contains(self[i], this)) return !0;
}));
for(i = 0, ret = this.pushStack([]); i < len; i++)jQuery.find(selector, self[i], ret);
return len > 1 ? jQuery.uniqueSort(ret) : ret;
},
filter: function(selector) {
return this.pushStack(winnow(this, selector || [], !1));
},
not: function(selector) {
return this.pushStack(winnow(this, selector || [], !0));
},
is: function(selector) {
return !!winnow(this, // If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
"string" == typeof selector && rneedsContext.test(selector) ? jQuery(selector) : selector || [], !1).length;
}
});
// Initialize a jQuery object
// A central reference to the root jQuery(document)
var rootjQuery, // A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
// Shortcut simple #id case for speed
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;
// Give the init function the jQuery prototype for later instantiation
(jQuery.fn.init = function(selector, context, root) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if (!selector) return this;
// Handle HTML strings
if (// Method init() accepts an alternate rootjQuery
// so migrate can support jQuery.sub (gh-2101)
root = root || rootjQuery, "string" == typeof selector) {
// Match html or make sure no context is specified for #id
if ((// Assume that strings that start and end with <> are HTML and skip the regex check
match = "<" === selector[0] && ">" === selector[selector.length - 1] && selector.length >= 3 ? [
null,
selector,
null
] : rquickExpr.exec(selector)) && (match[1] || !context)) {
// HANDLE: $(html) -> $(array)
if (!match[1]) return (elem = document.getElementById(match[2])) && (// Inject the element directly into the jQuery object
this[0] = elem, this.length = 1), this;
// HANDLE: $(html, props)
if (context = context instanceof jQuery ? context[0] : context, // Option to run scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
jQuery.merge(this, jQuery.parseHTML(match[1], context && context.nodeType ? context.ownerDocument || context : document, !0)), rsingleTag.test(match[1]) && jQuery.isPlainObject(context)) for(match in context)// Properties of context are called as methods if possible
isFunction(this[match]) ? this[match](context[match]) : this.attr(match, context[match]);
return this;
// HANDLE: $(expr, $(...))
}
return !context || context.jquery ? (context || root).find(selector) : this.constructor(context).find(selector);
// HANDLE: $(DOMElement)
}
return selector.nodeType ? (this[0] = selector, this.length = 1, this) : isFunction(selector) ? void 0 !== root.ready ? root.ready(selector) : // Execute immediately if ready is not present
selector(jQuery) : jQuery.makeArray(selector, this);
}).prototype = jQuery.fn, // Initialize central reference
rootjQuery = jQuery(document);
var rparentsprev = /^(?:parents|prev(?:Until|All))/, // Methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: !0,
contents: !0,
next: !0,
prev: !0
};
function sibling(cur, dir) {
for(; (cur = cur[dir]) && 1 !== cur.nodeType;);
return cur;
}
jQuery.fn.extend({
has: function(target) {
var targets = jQuery(target, this), l = targets.length;
return this.filter(function() {
for(var i = 0; i < l; i++)if (jQuery.contains(this, targets[i])) return !0;
});
},
closest: function(selectors, context) {
var cur, i = 0, l = this.length, matched = [], targets = "string" != typeof selectors && jQuery(selectors);
// Positional selectors never match, since there's no _selection_ context
if (!rneedsContext.test(selectors)) {
for(; i < l; i++)for(cur = this[i]; cur && cur !== context; cur = cur.parentNode)// Always skip document fragments
if (cur.nodeType < 11 && (targets ? targets.index(cur) > -1 : // Don't pass non-elements to Sizzle
1 === cur.nodeType && jQuery.find.matchesSelector(cur, selectors))) {
matched.push(cur);
break;
}
}
return this.pushStack(matched.length > 1 ? jQuery.uniqueSort(matched) : matched);
},
// Determine the position of an element within the set
index: function(elem) {
return(// No argument, return index in parent
elem ? "string" == typeof elem ? indexOf.call(jQuery(elem), this[0]) : indexOf.call(this, // If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem) : this[0] && this[0].parentNode ? this.first().prevAll().length : -1);
},
add: function(selector, context) {
return this.pushStack(jQuery.uniqueSort(jQuery.merge(this.get(), jQuery(selector, context))));
},
addBack: function(selector) {
return this.add(null == selector ? this.prevObject : this.prevObject.filter(selector));
}
}), jQuery.each({
parent: function(elem) {
var parent = elem.parentNode;
return parent && 11 !== parent.nodeType ? parent : null;
},
parents: function(elem) {
return dir(elem, "parentNode");
},
parentsUntil: function(elem, _i, until) {
return dir(elem, "parentNode", until);
},
next: function(elem) {
return sibling(elem, "nextSibling");
},
prev: function(elem) {
return sibling(elem, "previousSibling");
},
nextAll: function(elem) {
return dir(elem, "nextSibling");
},
prevAll: function(elem) {
return dir(elem, "previousSibling");
},
nextUntil: function(elem, _i, until) {
return dir(elem, "nextSibling", until);
},
prevUntil: function(elem, _i, until) {
return dir(elem, "previousSibling", until);
},
siblings: function(elem) {
return siblings((elem.parentNode || {}).firstChild, elem);
},
children: function(elem) {
return siblings(elem.firstChild);
},
contents: function(elem) {
return null != elem.contentDocument && // Support: IE 11+
// <object> elements with no `data` attribute has an object
// `contentDocument` with a `null` prototype.
getProto(elem.contentDocument) ? elem.contentDocument : (nodeName(elem, "template") && (elem = elem.content || elem), jQuery.merge([], elem.childNodes));
}
}, function(name, fn) {
jQuery.fn[name] = function(until, selector) {
var matched = jQuery.map(this, fn, until);
return "Until" !== name.slice(-5) && (selector = until), selector && "string" == typeof selector && (matched = jQuery.filter(selector, matched)), this.length > 1 && (guaranteedUnique[name] || jQuery.uniqueSort(matched), rparentsprev.test(name) && matched.reverse()), this.pushStack(matched);
};
});
var rnothtmlwhite = /[^\x20\t\r\n\f]+/g;
function Identity(v) {
return v;
}
function Thrower(ex) {
throw ex;
}
function adoptValue(value, resolve, reject, noValue) {
var method;
try {
// Check for promise aspect first to privilege synchronous behavior
value && isFunction(method = value.promise) ? method.call(value).done(resolve).fail(reject) : value && isFunction(method = value.then) ? method.call(value, resolve, reject) : // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer:
// * false: [ value ].slice( 0 ) => resolve( value )
// * true: [ value ].slice( 1 ) => resolve()
resolve.apply(void 0, [
value
].slice(noValue));
// For Promises/A+, convert exceptions into rejections
// Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in
// Deferred#then to conditionally suppress rejection.
} catch (value) {
// Support: Android 4.0 only
// Strict mode functions invoked without .call/.apply get global-object context
reject.apply(void 0, [
value
]);
}
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/ jQuery.Callbacks = function(options) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = "string" == typeof options ? (options1 = options, object = {}, jQuery.each(options1.match(rnothtmlwhite) || [], function(_, flag) {
object[flag] = !0;
}), object) : jQuery.extend({}, options);
var options1, object, firing, // Last fire value for non-forgettable lists
memory, // Flag to know if list was already fired
fired, // Flag to prevent firing
locked, // Actual callback list
list = [], // Queue of execution data for repeatable lists
queue = [], // Index of currently firing callback (modified by add/remove as needed)
firingIndex = -1, // Fire callbacks
fire = function() {
for(// Enforce single-firing
locked = locked || options.once, // Execute callbacks for all pending executions,
// respecting firingIndex overrides and runtime changes
fired = firing = !0; queue.length; firingIndex = -1)for(memory = queue.shift(); ++firingIndex < list.length;)// Run callback and check for early termination
!1 === list[firingIndex].apply(memory[0], memory[1]) && options.stopOnFalse && (// Jump to end and forget the data so .add doesn't re-fire
firingIndex = list.length, memory = !1);
options.memory || (memory = !1), firing = !1, locked && (list = memory ? [] : "");
}, // Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
return list && (memory && !firing && (firingIndex = list.length - 1, queue.push(memory)), function add(args) {
jQuery.each(args, function(_, arg) {
isFunction(arg) ? options.unique && self.has(arg) || list.push(arg) : arg && arg.length && "string" !== toType(arg) && // Inspect recursively
add(arg);
});
}(arguments), memory && !firing && fire()), this;
},
// Remove a callback from the list
remove: function() {
return jQuery.each(arguments, function(_, arg) {
for(var index; (index = jQuery.inArray(arg, list, index)) > -1;)list.splice(index, 1), index <= firingIndex && firingIndex--;
}), this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function(fn) {
return fn ? jQuery.inArray(fn, list) > -1 : list.length > 0;
},
// Remove all callbacks from the list
empty: function() {
return list && (list = []), this;
},
// Disable .fire and .add
// Abort any current/pending executions
// Clear all callbacks and values
disable: function() {
return locked = queue = [], list = memory = "", this;
},
disabled: function() {
return !list;
},
// Disable .fire
// Also disable .add unless we have memory (since it would have no effect)
// Abort any pending executions
lock: function() {
return locked = queue = [], memory || firing || (list = memory = ""), this;
},
locked: function() {
return !!locked;
},
// Call all callbacks with the given context and arguments
fireWith: function(context, args) {
return locked || (args = [
context,
(args = args || []).slice ? args.slice() : args
], queue.push(args), firing || fire()), this;
},
// Call all the callbacks with the given arguments
fire: function() {
return self.fireWith(this, arguments), this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
}, jQuery.extend({
Deferred: function(func) {
var tuples = [
// action, add listener, callbacks,
// ... .then handlers, argument index, [final state]
[
"notify",
"progress",
jQuery.Callbacks("memory"),
jQuery.Callbacks("memory"),
2
],
[
"resolve",
"done",
jQuery.Callbacks("once memory"),
jQuery.Callbacks("once memory"),
0,
"resolved"
],
[
"reject",
"fail",
jQuery.Callbacks("once memory"),
jQuery.Callbacks("once memory"),
1,
"rejected"
]
], state = "pending", promise = {
state: function() {
return state;
},
always: function() {
return deferred.done(arguments).fail(arguments), this;
},
catch: function(fn) {
return promise.then(null, fn);
},
// Keep pipe for back-compat
pipe: function() {
var fns = arguments;
return jQuery.Deferred(function(newDefer) {
jQuery.each(tuples, function(_i, tuple) {
// Map tuples (progress, done, fail) to arguments (done, fail, progress)
var fn = isFunction(fns[tuple[4]]) && fns[tuple[4]];
// deferred.progress(function() { bind to newDefer or newDefer.notify })
// deferred.done(function() { bind to newDefer or newDefer.resolve })
// deferred.fail(function() { bind to newDefer or newDefer.reject })
deferred[tuple[1]](function() {
var returned = fn && fn.apply(this, arguments);
returned && isFunction(returned.promise) ? returned.promise().progress(newDefer.notify).done(newDefer.resolve).fail(newDefer.reject) : newDefer[tuple[0] + "With"](this, fn ? [
returned
] : arguments);
});
}), fns = null;
}).promise();
},
then: function(onFulfilled, onRejected, onProgress) {
var maxDepth = 0;
function resolve(depth, deferred, handler, special) {
return function() {
var that = this, args = arguments, mightThrow = function() {
var returned, then;
// Support: Promises/A+ section 2.3.3.3.3
// https://promisesaplus.com/#point-59
// Ignore double-resolution attempts
if (!(depth < maxDepth)) {
// Support: Promises/A+ section 2.3.1
// https://promisesaplus.com/#point-48
if ((returned = handler.apply(that, args)) === deferred.promise()) throw TypeError("Thenable self-resolution");
// Handle a returned thenable
isFunction(// Support: Promises/A+ sections 2.3.3.1, 3.5
// https://promisesaplus.com/#point-54
// https://promisesaplus.com/#point-75
// Retrieve `then` only once
then = returned && // Support: Promises/A+ section 2.3.4
// https://promisesaplus.com/#point-64
// Only check objects and functions for thenability
("object" == typeof returned || "function" == typeof returned) && returned.then) ? special ? then.call(returned, resolve(maxDepth, deferred, Identity, special), resolve(maxDepth, deferred, Thrower, special)) : (// ...and disregard older resolution values
maxDepth++, then.call(returned, resolve(maxDepth, deferred, Identity, special), resolve(maxDepth, deferred, Thrower, special), resolve(maxDepth, deferred, Identity, deferred.notifyWith))) : (handler !== Identity && (that = void 0, args = [
returned
]), // Process the value(s)
// Default process is resolve
(special || deferred.resolveWith)(that, args));
}
}, // Only normal processors (resolve) catch and reject exceptions
process = special ? mightThrow : function() {
try {
mightThrow();
} catch (e) {
jQuery.Deferred.exceptionHook && jQuery.Deferred.exceptionHook(e, process.stackTrace), depth + 1 >= maxDepth && (handler !== Thrower && (that = void 0, args = [
e
]), deferred.rejectWith(that, args));
}
};
// Support: Promises/A+ section 2.3.3.3.1
// https://promisesaplus.com/#point-57
// Re-resolve promises immediately to dodge false rejection from
// subsequent errors
depth ? process() : (jQuery.Deferred.getStackHook && (process.stackTrace = jQuery.Deferred.getStackHook()), window1.setTimeout(process));
};
}
return jQuery.Deferred(function(newDefer) {
// progress_handlers.add( ... )
tuples[0][3].add(resolve(0, newDefer, isFunction(onProgress) ? onProgress : Identity, newDefer.notifyWith)), // fulfilled_handlers.add( ... )
tuples[1][3].add(resolve(0, newDefer, isFunction(onFulfilled) ? onFulfilled : Identity)), // rejected_handlers.add( ... )
tuples[2][3].add(resolve(0, newDefer, isFunction(onRejected) ? onRejected : Thrower));
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function(obj) {
return null != obj ? jQuery.extend(obj, promise) : promise;
}
}, deferred = {};
// All done!
return(// Add list-specific methods
jQuery.each(tuples, function(i, tuple) {
var list = tuple[2], stateString = tuple[5];
// promise.progress = list.add
// promise.done = list.add
// promise.fail = list.add
promise[tuple[1]] = list.add, stateString && list.add(function() {
// state = "resolved" (i.e., fulfilled)
// state = "rejected"
state = stateString;
}, // rejected_callbacks.disable
// fulfilled_callbacks.disable
tuples[3 - i][2].disable, // rejected_handlers.disable
// fulfilled_handlers.disable
tuples[3 - i][3].disable, // progress_callbacks.lock
tuples[0][2].lock, // progress_handlers.lock
tuples[0][3].lock), // progress_handlers.fire
// fulfilled_handlers.fire
// rejected_handlers.fire
list.add(tuple[3].fire), // deferred.notify = function() { deferred.notifyWith(...) }
// deferred.resolve = function() { deferred.resolveWith(...) }
// deferred.reject = function() { deferred.rejectWith(...) }
deferred[tuple[0]] = function() {
return deferred[tuple[0] + "With"](this === deferred ? void 0 : this, arguments), this;
}, // deferred.notifyWith = list.fireWith
// deferred.resolveWith = list.fireWith
// deferred.rejectWith = list.fireWith
deferred[tuple[0] + "With"] = list.fireWith;
}), // Make the deferred a promise
promise.promise(deferred), func && func.call(deferred, deferred), deferred);
},
// Deferred helper
when: function(singleValue) {
var // count of uncompleted subordinates
remaining = arguments.length, // count of unprocessed arguments
i = remaining, // subordinate fulfillment data
resolveContexts = Array(i), resolveValues = slice.call(arguments), // the master Deferred
master = jQuery.Deferred(), // subordinate callback factory
updateFunc = function(i) {
return function(value) {
resolveContexts[i] = this, resolveValues[i] = arguments.length > 1 ? slice.call(arguments) : value, --remaining || master.resolveWith(resolveContexts, resolveValues);
};
};
// Single- and empty arguments are adopted like Promise.resolve
if (remaining <= 1 && (adoptValue(singleValue, master.done(updateFunc(i)).resolve, master.reject, !remaining), "pending" === master.state() || isFunction(resolveValues[i] && resolveValues[i].then))) return master.then();
// Multiple arguments are aggregated like Promise.all array elements
for(; i--;)adoptValue(resolveValues[i], updateFunc(i), master.reject);
return master.promise();
}
});
// These usually indicate a programmer mistake during development,
// warn about them ASAP rather than swallowing them by default.
var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;
jQuery.Deferred.exceptionHook = function(error, stack) {
// Support: IE 8 - 9 only
// Console exists when dev tools are open, which can happen at any time
window1.console && window1.console.warn && error && rerrorNames.test(error.name) && window1.console.warn("jQuery.Deferred exception: " + error.message, error.stack, stack);
}, jQuery.readyException = function(error) {
window1.setTimeout(function() {
throw error;
});
};
// The deferred used on DOM ready
var readyList = jQuery.Deferred();
// The ready event handler and self cleanup method
function completed() {
document.removeEventListener("DOMContentLoaded", completed), window1.removeEventListener("load", completed), jQuery.ready();
}
jQuery.fn.ready = function(fn) {
return readyList.then(fn)// Wrap jQuery.readyException in a function so that the lookup
// happens at the time of error handling instead of callback
// registration.
.catch(function(error) {
jQuery.readyException(error);
}), this;
}, jQuery.extend({
// Is the DOM ready to be used? Set to true once it occurs.
isReady: !1,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Handle when the DOM is ready
ready: function(wait) {
// Abort if there are pending holds or we're already ready
!(!0 === wait ? --jQuery.readyWait : jQuery.isReady) && (// Remember that the DOM is ready
jQuery.isReady = !0, !0 !== wait && --jQuery.readyWait > 0 || // If there are functions bound, to execute
readyList.resolveWith(document, [
jQuery
]));
}
}), jQuery.ready.then = readyList.then, "complete" !== document.readyState && ("loading" === document.readyState || document.documentElement.doScroll) ? (// Use the handy event callback
document.addEventListener("DOMContentLoaded", completed), // A fallback to window.onload, that will always work
window1.addEventListener("load", completed)) : // Handle it asynchronously to allow scripts the opportunity to delay ready
window1.setTimeout(jQuery.ready);
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = function(elems, fn, key, value, chainable, emptyGet, raw) {
var i = 0, len = elems.length, bulk = null == key;
// Sets many values
if ("object" === toType(key)) for(i in chainable = !0, key)access(elems, fn, i, key[i], !0, emptyGet, raw);
else if (void 0 !== value && (chainable = !0, isFunction(value) || (raw = !0), bulk && (raw ? (fn.call(elems, value), fn = null) : (bulk = fn, fn = function(elem, _key, value) {
return bulk.call(jQuery(elem), value);
})), fn)) for(; i < len; i++)fn(elems[i], key, raw ? value : value.call(elems[i], i, fn(elems[i], key)));
return chainable ? elems : bulk ? fn.call(elems) : len ? fn(elems[0], key) : emptyGet;
}, rmsPrefix = /^-ms-/, rdashAlpha = /-([a-z])/g;
// Used by camelCase as callback to replace()
function fcamelCase(_all, letter) {
return letter.toUpperCase();
}
// Convert dashed to camelCase; used by the css and data modules
// Support: IE <=9 - 11, Edge 12 - 15
// Microsoft forgot to hump their vendor prefix (#9572)
function camelCase(string) {
return string.replace(rmsPrefix, "ms-").replace(rdashAlpha, fcamelCase);
}
var acceptData = function(owner) {
// Accepts only:
// - Node
// - Node.ELEMENT_NODE
// - Node.DOCUMENT_NODE
// - Object
// - Any
return 1 === owner.nodeType || 9 === owner.nodeType || !+owner.nodeType;
};
function Data() {
this.expando = jQuery.expando + Data.uid++;
}
Data.uid = 1, Data.prototype = {
cache: function(owner) {
// Check if the owner object already has a cache
var value = owner[this.expando];
return !value && (value = {}, acceptData(owner) && (owner.nodeType ? owner[this.expando] = value : Object.defineProperty(owner, this.expando, {
value: value,
configurable: !0
}))), value;
},
set: function(owner, data, value) {
var prop, cache = this.cache(owner);
// Handle: [ owner, key, value ] args
// Always use camelCase key (gh-2257)
if ("string" == typeof data) cache[camelCase(data)] = value;
else // Copy the properties one-by-one to the cache object
for(prop in data)cache[camelCase(prop)] = data[prop];
return cache;
},
get: function(owner, key) {
return void 0 === key ? this.cache(owner) : // Always use camelCase key (gh-2257)
owner[this.expando] && owner[this.expando][camelCase(key)];
},
access: function(owner, key, value) {
return(// In cases where either:
//
// 1. No key was specified
// 2. A string key was specified, but no value provided
//
// Take the "read" path and allow the get method to determine
// which value to return, respectively either:
//
// 1. The entire cache object
// 2. The data stored at the key
//
void 0 === key || key && "string" == typeof key && void 0 === value ? this.get(owner, key) : (// When the key is not a string, or both a key and value
// are specified, set or extend (existing objects) with either:
//
// 1. An object of properties
// 2. A key and value
//
this.set(owner, key, value), void 0 !== value ? value : key));
},
remove: function(owner, key) {
var i, cache = owner[this.expando];
if (void 0 !== cache) {
if (void 0 !== key) for(i = (// If key is an array of keys...
// We always set camelCase keys, so remove that.
key = Array.isArray(key) ? key.map(camelCase) : ((key = camelCase(key)) in cache) ? [
key
] : key.match(rnothtmlwhite) || []).length; i--;)delete cache[key[i]];
// Remove the expando if there's no more data
(void 0 === key || jQuery.isEmptyObject(cache)) && (owner.nodeType ? owner[this.expando] = void 0 : delete owner[this.expando]);
}
},
hasData: function(owner) {
var cache = owner[this.expando];
return void 0 !== cache && !jQuery.isEmptyObject(cache);
}
};
var dataPriv = new Data(), dataUser = new Data(), rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /[A-Z]/g;
function dataAttr(elem, key, data) {
var name, data1;
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if (void 0 === data && 1 === elem.nodeType) {
if (name = "data-" + key.replace(rmultiDash, "-$&").toLowerCase(), "string" == typeof (data = elem.getAttribute(name))) {
try {
data1 = data, data = "true" === data1 || "false" !== data1 && ("null" === data1 ? null : data1 === +data1 + "" ? +data1 : rbrace.test(data1) ? JSON.parse(data1) : data1);
} catch (e) {}
// Make sure we set the data so it isn't changed later
dataUser.set(elem, key, data);
} else data = void 0;
}
return data;
}
jQuery.extend({
hasData: function(elem) {
return dataUser.hasData(elem) || dataPriv.hasData(elem);
},
data: function(elem, name, data) {
return dataUser.access(elem, name, data);
},
removeData: function(elem, name) {
dataUser.remove(elem, name);
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to dataPriv methods, these can be deprecated.
_data: function(elem, name, data) {
return dataPriv.access(elem, name, data);
},
_removeData: function(elem, name) {
dataPriv.remove(elem, name);
}
}), jQuery.fn.extend({
data: function(key, value) {
var i, name, data, elem = this[0], attrs = elem && elem.attributes;
// Gets all values
if (void 0 === key) {
if (this.length && (data = dataUser.get(elem), 1 === elem.nodeType && !dataPriv.get(elem, "hasDataAttrs"))) {
for(i = attrs.length; i--;)// Support: IE 11 only
// The attrs elements can be null (#14894)
attrs[i] && 0 === (name = attrs[i].name).indexOf("data-") && dataAttr(elem, name = camelCase(name.slice(5)), data[name]);
dataPriv.set(elem, "hasDataAttrs", !0);
}
return data;
}
return(// Sets multiple values
"object" == typeof key ? this.each(function() {
dataUser.set(this, key);
}) : access(this, function(value) {
var data;
// The calling jQuery object (element matches) is not empty
// (and therefore has an element appears at this[ 0 ]) and the
// `value` parameter was not undefined. An empty jQuery object
// will result in `undefined` for elem = this[ 0 ] which will
// throw an exception if an attempt to read a data cache is made.
if (elem && void 0 === value) return void 0 !== // Attempt to get data from the cache
// The key will always be camelCased in Data
(data = dataUser.get(elem, key)) || void 0 !== // Attempt to "discover" the data in
// HTML5 custom data-* attrs
(data = dataAttr(elem, key)) ? data : // We tried really hard, but the data doesn't exist.
void 0;
// Set the data...
this.each(function() {
// We always store the camelCased key
dataUser.set(this, key, value);
});
}, null, value, arguments.length > 1, null, !0));
},
removeData: function(key) {
return this.each(function() {
dataUser.remove(this, key);
});
}
}), jQuery.extend({
queue: function(elem, type, data) {
var queue;
if (elem) return type = (type || "fx") + "queue", queue = dataPriv.get(elem, type), data && (!queue || Array.isArray(data) ? queue = dataPriv.access(elem, type, jQuery.makeArray(data)) : queue.push(data)), queue || [];
},
dequeue: function(elem, type) {
type = type || "fx";
var queue = jQuery.queue(elem, type), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks(elem, type);
"inprogress" === fn && (fn = queue.shift(), startLength--), fn && ("fx" === type && queue.unshift("inprogress"), // Clear up the last queue stop function
delete hooks.stop, fn.call(elem, function() {
jQuery.dequeue(elem, type);
}, hooks)), !startLength && hooks && hooks.empty.fire();
},
// Not public - generate a queueHooks object, or return the current one
_queueHooks: function(elem, type) {
var key = type + "queueHooks";
return dataPriv.get(elem, key) || dataPriv.access(elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
dataPriv.remove(elem, [
type + "queue",
key
]);
})
});
}
}), jQuery.fn.extend({
queue: function(type, data) {
var setter = 2;
return ("string" != typeof type && (data = type, type = "fx", setter--), arguments.length < setter) ? jQuery.queue(this[0], type) : void 0 === data ? this : this.each(function() {
var queue = jQuery.queue(this, type, data);
// Ensure a hooks for this queue
jQuery._queueHooks(this, type), "fx" === type && "inprogress" !== queue[0] && jQuery.dequeue(this, type);
});
},
dequeue: function(type) {
return this.each(function() {
jQuery.dequeue(this, type);
});
},
clearQueue: function(type) {
return this.queue(type || "fx", []);
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function(type, obj) {
var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() {
--count || defer.resolveWith(elements, [
elements
]);
};
for("string" != typeof type && (obj = type, type = void 0), type = type || "fx"; i--;)(tmp = dataPriv.get(elements[i], type + "queueHooks")) && tmp.empty && (count++, tmp.empty.add(resolve));
return resolve(), defer.promise(obj);
}
});
var pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, rcssNum = RegExp("^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i"), cssExpand = [
"Top",
"Right",
"Bottom",
"Left"
], documentElement = document.documentElement, isAttached = function(elem) {
return jQuery.contains(elem.ownerDocument, elem);
}, composed = {
composed: !0
};
documentElement.getRootNode && (isAttached = function(elem) {
return jQuery.contains(elem.ownerDocument, elem) || elem.getRootNode(composed) === elem.ownerDocument;
});
var isHiddenWithinTree = function(elem, el) {
// Inline style trumps all
return "none" === // isHiddenWithinTree might be called from jQuery#filter function;
// in that case, element will be second argument
(elem = el || elem).style.display || "" === elem.style.display && // Otherwise, check computed style
// Support: Firefox <=43 - 45
// Disconnected elements can have computed display: none, so first confirm that elem is
// in the document.
isAttached(elem) && "none" === jQuery.css(elem, "display");
};
function adjustCSS(elem, prop, valueParts, tween) {
var adjusted, scale, maxIterations = 20, currentValue = tween ? function() {
return tween.cur();
} : function() {
return jQuery.css(elem, prop, "");
}, initial = currentValue(), unit = valueParts && valueParts[3] || (jQuery.cssNumber[prop] ? "" : "px"), // Starting value computation is required for potential unit mismatches
initialInUnit = elem.nodeType && (jQuery.cssNumber[prop] || "px" !== unit && +initial) && rcssNum.exec(jQuery.css(elem, prop));
if (initialInUnit && initialInUnit[3] !== unit) {
for(// Support: Firefox <=54
// Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144)
initial /= 2, // Trust units reported by jQuery.css
unit = unit || initialInUnit[3], // Iteratively approximate from a nonzero starting point
initialInUnit = +initial || 1; maxIterations--;)// Evaluate and update our best guess (doubling guesses that zero out).
// Finish if the scale equals or crosses 1 (making the old*new product non-positive).
jQuery.style(elem, prop, initialInUnit + unit), (1 - scale) * (1 - (scale = currentValue() / initial || 0.5)) <= 0 && (maxIterations = 0), initialInUnit /= scale;
initialInUnit *= 2, jQuery.style(elem, prop, initialInUnit + unit), // Make sure we update the tween properties later on
valueParts = valueParts || [];
}
return valueParts && (initialInUnit = +initialInUnit || +initial || 0, // Apply relative offset (+=/-=) if specified
adjusted = valueParts[1] ? initialInUnit + (valueParts[1] + 1) * valueParts[2] : +valueParts[2], tween && (tween.unit = unit, tween.start = initialInUnit, tween.end = adjusted)), adjusted;
}
var defaultDisplayMap = {};
function showHide(elements, show) {
// Determine new display value for elements that need to change
for(var display, elem, values = [], index = 0, length = elements.length; index < length; index++)(elem = elements[index]).style && (display = elem.style.display, show ? ("none" !== display || (values[index] = dataPriv.get(elem, "display") || null, values[index] || (elem.style.display = "")), "" === elem.style.display && isHiddenWithinTree(elem) && (values[index] = function(elem) {
var temp, doc = elem.ownerDocument, nodeName = elem.nodeName, display = defaultDisplayMap[nodeName];
return display || (temp = doc.body.appendChild(doc.createElement(nodeName)), display = jQuery.css(temp, "display"), temp.parentNode.removeChild(temp), "none" === display && (display = "block"), defaultDisplayMap[nodeName] = display), display;
}(elem))) : "none" !== display && (values[index] = "none", // Remember what we're overwriting
dataPriv.set(elem, "display", display)));
// Set the display of the elements in a second loop to avoid constant reflow
for(index = 0; index < length; index++)null != values[index] && (elements[index].style.display = values[index]);
return elements;
}
jQuery.fn.extend({
show: function() {
return showHide(this, !0);
},
hide: function() {
return showHide(this);
},
toggle: function(state) {
return "boolean" == typeof state ? state ? this.show() : this.hide() : this.each(function() {
isHiddenWithinTree(this) ? jQuery(this).show() : jQuery(this).hide();
});
}
});
var rcheckableType = /^(?:checkbox|radio)$/i, rtagName = /<([a-z][^\/\0>\x20\t\r\n\f]*)/i, rscriptType = /^$|^module$|\/(?:java|ecma)script/i;
div = document.createDocumentFragment().appendChild(document.createElement("div")), // Support: Android 4.0 - 4.3 only
// Check state lost if the name is set (#11217)
// Support: Windows Web Apps (WWA)
// `name` and `type` must use .setAttribute for WWA (#14901)
(input = document.createElement("input")).setAttribute("type", "radio"), input.setAttribute("checked", "checked"), input.setAttribute("name", "t"), div.appendChild(input), // Support: Android <=4.1 only
// Older WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode(!0).cloneNode(!0).lastChild.checked, // Support: IE <=11 only
// Make sure textarea (and checkbox) defaultValue is properly cloned
div.innerHTML = "<textarea>x</textarea>", support.noCloneChecked = !!div.cloneNode(!0).lastChild.defaultValue, // Support: IE <=9 only
// IE <=9 replaces <option> tags with their contents when inserted outside of
// the select element.
div.innerHTML = "<option></option>", support.option = !!div.lastChild;
// We have to close these tags to support XHTML (#13200)
var wrapMap = {
// XHTML parsers do not magically insert elements in the
// same way that tag soup parsers do. So we cannot shorten
// this by omitting <tbody> or other required elements.
thead: [
1,
"<table>",
"</table>"
],
col: [
2,
"<table><colgroup>",
"</colgroup></table>"
],
tr: [
2,
"<table><tbody>",
"</tbody></table>"
],
td: [
3,
"<table><tbody><tr>",
"</tr></tbody></table>"
],
_default: [
0,
"",
""
]
};
function getAll(context, tag) {
// Support: IE <=9 - 11 only
// Use typeof to avoid zero-argument method invocation on host objects (#15151)
var ret;
return (ret = void 0 !== context.getElementsByTagName ? context.getElementsByTagName(tag || "*") : void 0 !== context.querySelectorAll ? context.querySelectorAll(tag || "*") : [], void 0 === tag || tag && nodeName(context, tag)) ? jQuery.merge([
context
], ret) : ret;
}
// Mark scripts as having already been evaluated
function setGlobalEval(elems, refElements) {
for(var i = 0, l = elems.length; i < l; i++)dataPriv.set(elems[i], "globalEval", !refElements || dataPriv.get(refElements[i], "globalEval"));
}
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead, wrapMap.th = wrapMap.td, support.option || (wrapMap.optgroup = wrapMap.option = [
1,
"<select multiple='multiple'>",
"</select>"
]);
var rhtml = /<|&#?\w+;/;
function buildFragment(elems, context, scripts, selection, ignored) {
for(var elem, tmp, wrap, attached, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; i < l; i++)if ((elem = elems[i]) || 0 === elem) {
// Add nodes directly
if ("object" === toType(elem)) // Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge(nodes, elem.nodeType ? [
elem
] : elem);
else if (rhtml.test(elem)) {
for(tmp = tmp || fragment.appendChild(context.createElement("div")), wrap = wrapMap[(rtagName.exec(elem) || [
"",
""
])[1].toLowerCase()] || wrapMap._default, tmp.innerHTML = wrap[1] + jQuery.htmlPrefilter(elem) + wrap[2], // Descend through wrappers to the right content
j = wrap[0]; j--;)tmp = tmp.lastChild;
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge(nodes, tmp.childNodes), // Ensure the created nodes are orphaned (#12392)
// Remember the top-level container
(tmp = fragment.firstChild).textContent = "";
} else nodes.push(context.createTextNode(elem));
}
for(// Remove wrapper from fragment
fragment.textContent = "", i = 0; elem = nodes[i++];){
// Skip elements already in the context collection (trac-4087)
if (selection && jQuery.inArray(elem, selection) > -1) {
ignored && ignored.push(elem);
continue;
}
// Capture executables
if (attached = isAttached(elem), // Append to fragment
tmp = getAll(fragment.appendChild(elem), "script"), attached && setGlobalEval(tmp), scripts) for(j = 0; elem = tmp[j++];)rscriptType.test(elem.type || "") && scripts.push(elem);
}
return fragment;
}
var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, rtypenamespace = /^([^.]*)(?:\.(.+)|)/;
function returnTrue() {
return !0;
}
function returnFalse() {
return !1;
}
// Support: IE <=9 - 11+
// focus() and blur() are asynchronous, except when they are no-op.
// So expect focus to be synchronous when the element is already active,
// and blur to be synchronous when the element is not already active.
// (focus and blur are always synchronous in other supported browsers,
// this just defines when we can count on it).
function expectSync(elem, type) {
return elem === // Support: IE <=9 only
// Accessing document.activeElement can throw unexpectedly
// https://bugs.jquery.com/ticket/13393
function() {
try {
return document.activeElement;
} catch (err) {}
}() == ("focus" === type);
}
function on(elem, types, selector, data, fn, one) {
var origFn, type;
// Types can be a map of types/handlers
if ("object" == typeof types) {
for(type in "string" != typeof selector && (// ( types-Object, data )
data = data || selector, selector = void 0), types)on(elem, type, selector, data, types[type], one);
return elem;
}
if (null == data && null == fn ? (// ( types, fn )
fn = selector, data = selector = void 0) : null == fn && ("string" == typeof selector ? (// ( types, selector, fn )
fn = data, data = void 0) : (// ( types, data, fn )
fn = data, data = selector, selector = void 0)), !1 === fn) fn = returnFalse;
else if (!fn) return elem;
return 1 === one && (origFn = fn, // Use same guid so caller can remove using origFn
(fn = function(event) {
return(// Can use an empty set, since event contains the info
jQuery().off(event), origFn.apply(this, arguments));
}).guid = origFn.guid || (origFn.guid = jQuery.guid++)), elem.each(function() {
jQuery.event.add(this, types, fn, data, selector);
});
}
// Ensure the presence of an event listener that handles manually-triggered
// synthetic events by interrupting progress until reinvoked in response to
// *native* events that it fires directly, ensuring that state changes have
// already occurred before other listeners are invoked.
function leverageNative(el, type, expectSync) {
// Missing expectSync indicates a trigger call, which must force setup through jQuery.event.add
if (!expectSync) {
void 0 === dataPriv.get(el, type) && jQuery.event.add(el, type, returnTrue);
return;
}
// Register the controller as a special universal handler for all event namespaces
dataPriv.set(el, type, !1), jQuery.event.add(el, type, {
namespace: !1,
handler: function(event) {
var notAsync, result, saved = dataPriv.get(this, type);
if (1 & event.isTrigger && this[type]) {
// Interrupt processing of the outer synthetic .trigger()ed event
// Saved data should be false in such cases, but might be a leftover capture object
// from an async native handler (gh-4350)
if (saved.length) (jQuery.event.special[type] || {}).delegateType && event.stopPropagation();
else if (// Store arguments for use when handling the inner native event
// There will always be at least one argument (an event object), so this array
// will not be confused with a leftover capture object.
saved = slice.call(arguments), dataPriv.set(this, type, saved), // Trigger the native event and capture its result
// Support: IE <=9 - 11+
// focus() and blur() are asynchronous
notAsync = expectSync(this, type), this[type](), saved !== (result = dataPriv.get(this, type)) || notAsync ? dataPriv.set(this, type, !1) : result = {}, saved !== result) return(// Cancel the outer synthetic event
event.stopImmediatePropagation(), event.preventDefault(), result.value);
} else saved.length && (// ...and capture the result
dataPriv.set(this, type, {
value: jQuery.event.trigger(// Support: IE <=9 - 11+
// Extend with the prototype to reset the above stopImmediatePropagation()
jQuery.extend(saved[0], jQuery.Event.prototype), saved.slice(1), this)
}), // Abort handling of the native event
event.stopImmediatePropagation());
}
});
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/ jQuery.event = {
global: {},
add: function(elem, types, handler, data, selector) {
var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.get(elem);
// Only attach events to objects that accept data
if (acceptData(elem)) for(handler.handler && (handler = (handleObjIn = handler).handler, selector = handleObjIn.selector), selector && jQuery.find.matchesSelector(documentElement, selector), handler.guid || (handler.guid = jQuery.guid++), (events = elemData.events) || (events = elemData.events = Object.create(null)), (eventHandle = elemData.handle) || (eventHandle = elemData.handle = function(e) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply(elem, arguments) : void 0;
}), t = // Handle multiple events separated by a space
(types = (types || "").match(rnothtmlwhite) || [
""
]).length; t--;)// There *must* be a type, no attaching namespace-only handlers
type = origType = (tmp = rtypenamespace.exec(types[t]) || [])[1], namespaces = (tmp[2] || "").split(".").sort(), type && (// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[type] || {}, // If selector defined, determine special event api type, otherwise given type
type = (selector ? special.delegateType : special.bindType) || type, // Update special based on newly reset type
special = jQuery.event.special[type] || {}, // handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test(selector),
namespace: namespaces.join(".")
}, handleObjIn), (handlers = events[type]) || ((handlers = events[type] = []).delegateCount = 0, (!special.setup || !1 === special.setup.call(elem, data, namespaces, eventHandle)) && elem.addEventListener && elem.addEventListener(type, eventHandle)), special.add && (special.add.call(elem, handleObj), handleObj.handler.guid || (handleObj.handler.guid = handler.guid)), selector ? handlers.splice(handlers.delegateCount++, 0, handleObj) : handlers.push(handleObj), // Keep track of which events have ever been used, for event optimization
jQuery.event.global[type] = !0);
},
// Detach an event or set of events from an element
remove: function(elem, types, handler, selector, mappedTypes) {
var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.hasData(elem) && dataPriv.get(elem);
if (elemData && (events = elemData.events)) {
for(t = // Once for each type.namespace in types; type may be omitted
(types = (types || "").match(rnothtmlwhite) || [
""
]).length; t--;){
// Unbind all events (on this namespace, if provided) for the element
if (type = origType = (tmp = rtypenamespace.exec(types[t]) || [])[1], namespaces = (tmp[2] || "").split(".").sort(), !type) {
for(type in events)jQuery.event.remove(elem, type + types[t], handler, selector, !0);
continue;
}
for(special = jQuery.event.special[type] || {}, handlers = events[type = (selector ? special.delegateType : special.bindType) || type] || [], tmp = tmp[2] && RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)"), // Remove matching events
origCount = j = handlers.length; j--;)handleObj = handlers[j], (mappedTypes || origType === handleObj.origType) && (!handler || handler.guid === handleObj.guid) && (!tmp || tmp.test(handleObj.namespace)) && (!selector || selector === handleObj.selector || "**" === selector && handleObj.selector) && (handlers.splice(j, 1), handleObj.selector && handlers.delegateCount--, special.remove && special.remove.call(elem, handleObj));
origCount && !handlers.length && (special.teardown && !1 !== special.teardown.call(elem, namespaces, elemData.handle) || jQuery.removeEvent(elem, type, elemData.handle), delete events[type]);
}
jQuery.isEmptyObject(events) && dataPriv.remove(elem, "handle events");
}
},
dispatch: function(nativeEvent) {
var i, j, ret, matched, handleObj, handlerQueue, args = Array(arguments.length), // Make a writable jQuery.Event from the native event object
event = jQuery.event.fix(nativeEvent), handlers = (dataPriv.get(this, "events") || Object.create(null))[event.type] || [], special = jQuery.event.special[event.type] || {};
for(i = 1, // Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event; i < arguments.length; i++)args[i] = arguments[i];
// Call the preDispatch hook for the mapped type, and let it bail if desired
if (event.delegateTarget = this, !special.preDispatch || !1 !== special.preDispatch.call(this, event)) {
for(// Determine handlers
handlerQueue = jQuery.event.handlers.call(this, event, handlers), // Run delegates first; they may want to stop propagation beneath us
i = 0; (matched = handlerQueue[i++]) && !event.isPropagationStopped();)for(event.currentTarget = matched.elem, j = 0; (handleObj = matched.handlers[j++]) && !event.isImmediatePropagationStopped();)// If the event is namespaced, then each handler is only invoked if it is
// specially universal or its namespaces are a superset of the event's.
(!event.rnamespace || !1 === handleObj.namespace || event.rnamespace.test(handleObj.namespace)) && (event.handleObj = handleObj, event.data = handleObj.data, void 0 !== (ret = ((jQuery.event.special[handleObj.origType] || {}).handle || handleObj.handler).apply(matched.elem, args)) && !1 === (event.result = ret) && (event.preventDefault(), event.stopPropagation()));
return special.postDispatch && special.postDispatch.call(this, event), event.result;
}
},
handlers: function(event, handlers) {
var i, handleObj, sel, matchedHandlers, matchedSelectors, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target;
// Find delegate handlers
if (delegateCount && // Support: IE <=9
// Black-hole SVG <use> instance trees (trac-13180)
cur.nodeType && // Support: Firefox <=42
// Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861)
// https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click
// Support: IE 11 only
// ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343)
!("click" === event.type && event.button >= 1)) {
for(; cur !== this; cur = cur.parentNode || this)// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if (1 === cur.nodeType && ("click" !== event.type || !0 !== cur.disabled)) {
for(i = 0, matchedHandlers = [], matchedSelectors = {}; i < delegateCount; i++)void 0 === matchedSelectors[// Don't conflict with Object.prototype properties (#13203)
sel = (handleObj = handlers[i]).selector + " "] && (matchedSelectors[sel] = handleObj.needsContext ? jQuery(sel, this).index(cur) > -1 : jQuery.find(sel, this, null, [
cur
]).length), matchedSelectors[sel] && matchedHandlers.push(handleObj);
matchedHandlers.length && handlerQueue.push({
elem: cur,
handlers: matchedHandlers
});
}
}
return(// Add the remaining (directly-bound) handlers
cur = this, delegateCount < handlers.length && handlerQueue.push({
elem: cur,
handlers: handlers.slice(delegateCount)
}), handlerQueue);
},
addProp: function(name, hook) {
Object.defineProperty(jQuery.Event.prototype, name, {
enumerable: !0,
configurable: !0,
get: isFunction(hook) ? function() {
if (this.originalEvent) return hook(this.originalEvent);
} : function() {
if (this.originalEvent) return this.originalEvent[name];
},
set: function(value) {
Object.defineProperty(this, name, {
enumerable: !0,
configurable: !0,
writable: !0,
value: value
});
}
});
},
fix: function(originalEvent) {
return originalEvent[jQuery.expando] ? originalEvent : new jQuery.Event(originalEvent);
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: !0
},
click: {
// Utilize native event to ensure correct state for checkable inputs
setup: function(data) {
// For mutual compressibility with _default, replace `this` access with a local var.
// `|| data` is dead code meant only to preserve the variable through minification.
var el = this || data;
// Return false to allow normal processing in the caller
return rcheckableType.test(el.type) && el.click && nodeName(el, "input") && // dataPriv.set( el, "click", ... )
leverageNative(el, "click", returnTrue), !1;
},
trigger: function(data) {
// For mutual compressibility with _default, replace `this` access with a local var.
// `|| data` is dead code meant only to preserve the variable through minification.
var el = this || data;
// Return non-false to allow normal event-path propagation
return rcheckableType.test(el.type) && el.click && nodeName(el, "input") && leverageNative(el, "click"), !0;
},
// For cross-browser consistency, suppress native .click() on links
// Also prevent it if we're currently inside a leveraged native-event stack
_default: function(event) {
var target = event.target;
return rcheckableType.test(target.type) && target.click && nodeName(target, "input") && dataPriv.get(target, "click") || nodeName(target, "a");
}
},
beforeunload: {
postDispatch: function(event) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
void 0 !== event.result && event.originalEvent && (event.originalEvent.returnValue = event.result);
}
}
}
}, jQuery.removeEvent = function(elem, type, handle) {
// This "if" is needed for plain objects
elem.removeEventListener && elem.removeEventListener(type, handle);
}, jQuery.Event = function(src, props) {
// Allow instantiation without the 'new' keyword
if (!(this instanceof jQuery.Event)) return new jQuery.Event(src, props);
src && src.type ? (this.originalEvent = src, this.type = src.type, // Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented || void 0 === src.defaultPrevented && // Support: Android <=2.3 only
!1 === src.returnValue ? returnTrue : returnFalse, // Create target properties
// Support: Safari <=6 - 7 only
// Target should not be a text node (#504, #13143)
this.target = src.target && 3 === src.target.nodeType ? src.target.parentNode : src.target, this.currentTarget = src.currentTarget, this.relatedTarget = src.relatedTarget) : this.type = src, props && jQuery.extend(this, props), // Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || Date.now(), // Mark it as fixed
this[jQuery.expando] = !0;
}, // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
constructor: jQuery.Event,
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
isSimulated: !1,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue, e && !this.isSimulated && e.preventDefault();
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue, e && !this.isSimulated && e.stopPropagation();
},
stopImmediatePropagation: function() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue, e && !this.isSimulated && e.stopImmediatePropagation(), this.stopPropagation();
}
}, // Includes all common event props including KeyEvent and MouseEvent specific props
jQuery.each({
altKey: !0,
bubbles: !0,
cancelable: !0,
changedTouches: !0,
ctrlKey: !0,
detail: !0,
eventPhase: !0,
metaKey: !0,
pageX: !0,
pageY: !0,
shiftKey: !0,
view: !0,
char: !0,
code: !0,
charCode: !0,
key: !0,
keyCode: !0,
button: !0,
buttons: !0,
clientX: !0,
clientY: !0,
offsetX: !0,
offsetY: !0,
pointerId: !0,
pointerType: !0,
screenX: !0,
screenY: !0,
targetTouches: !0,
toElement: !0,
touches: !0,
which: function(event) {
var button = event.button;
return(// Add which for key events
null == event.which && rkeyEvent.test(event.type) ? null != event.charCode ? event.charCode : event.keyCode : !event.which && void 0 !== button && rmouseEvent.test(event.type) ? 1 & button ? 1 : 2 & button ? 3 : 4 & button ? 2 : 0 : event.which);
}
}, jQuery.event.addProp), jQuery.each({
focus: "focusin",
blur: "focusout"
}, function(type, delegateType) {
jQuery.event.special[type] = {
// Utilize native event if possible so blur/focus sequence is correct
setup: function() {
// Return false to allow normal processing in the caller
return(// Claim the first handler
// dataPriv.set( this, "focus", ... )
// dataPriv.set( this, "blur", ... )
leverageNative(this, type, expectSync), !1);
},
trigger: function() {
// Return non-false to allow normal event-path propagation
return(// Force setup before trigger
leverageNative(this, type), !0);
},
delegateType: delegateType
};
}), // Create mouseenter/leave events using mouseover/out and event-time checks
// so that event delegation works in jQuery.
// Do the same for pointerenter/pointerleave and pointerover/pointerout
//
// Support: Safari 7 only
// Safari sends mouseenter too often; see:
// https://bugs.chromium.org/p/chromium/issues/detail?id=470258
// for the description of the bug (it existed in older Chrome versions as well).
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, function(orig, fix) {
jQuery.event.special[orig] = {
delegateType: fix,
bindType: fix,
handle: function(event) {
var ret, related = event.relatedTarget, handleObj = event.handleObj;
return related && (related === this || jQuery.contains(this, related)) || (event.type = handleObj.origType, ret = handleObj.handler.apply(this, arguments), event.type = fix), ret;
}
};
}), jQuery.fn.extend({
on: function(types, selector, data, fn) {
return on(this, types, selector, data, fn);
},
one: function(types, selector, data, fn) {
return on(this, types, selector, data, fn, 1);
},
off: function(types, selector, fn) {
var handleObj, type;
if (types && types.preventDefault && types.handleObj) return(// ( event ) dispatched jQuery.Event
handleObj = types.handleObj, jQuery(types.delegateTarget).off(handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler), this);
if ("object" == typeof types) {
// ( types-object [, selector] )
for(type in types)this.off(type, selector, types[type]);
return this;
}
return (!1 === selector || "function" == typeof selector) && (// ( types [, fn] )
fn = selector, selector = void 0), !1 === fn && (fn = returnFalse), this.each(function() {
jQuery.event.remove(this, types, fn, selector);
});
}
});
var // Support: IE <=10 - 11, Edge 12 - 13 only
// In IE/Edge using regex groups here causes severe slowdowns.
// See https://connect.microsoft.com/IE/feedback/details/1736512/
rnoInnerhtml = /<script|<style|<link/i, // checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;
// Prefer a tbody over its parent table for containing new rows
function manipulationTarget(elem, content) {
return nodeName(elem, "table") && nodeName(11 !== content.nodeType ? content : content.firstChild, "tr") && jQuery(elem).children("tbody")[0] || elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript(elem) {
return elem.type = (null !== elem.getAttribute("type")) + "/" + elem.type, elem;
}
function restoreScript(elem) {
return "true/" === (elem.type || "").slice(0, 5) ? elem.type = elem.type.slice(5) : elem.removeAttribute("type"), elem;
}
function cloneCopyEvent(src, dest) {
var i, l, type, udataOld, udataCur, events;
if (1 === dest.nodeType) {
// 1. Copy private data: events, handlers, etc.
if (dataPriv.hasData(src) && (events = dataPriv.get(src).events)) for(type in dataPriv.remove(dest, "handle events"), events)for(i = 0, l = events[type].length; i < l; i++)jQuery.event.add(dest, type, events[type][i]);
// 2. Copy user data
dataUser.hasData(src) && (udataOld = dataUser.access(src), udataCur = jQuery.extend({}, udataOld), dataUser.set(dest, udataCur));
}
}
function domManip(collection, args, callback, ignored) {
// Flatten any nested arrays
args = flat(args);
var fragment, first, scripts, hasScripts, node, doc, i = 0, l = collection.length, iNoClone = l - 1, value = args[0], valueIsFunction = isFunction(value);
// We can't cloneNode fragments that contain checked, in WebKit
if (valueIsFunction || l > 1 && "string" == typeof value && !support.checkClone && rchecked.test(value)) return collection.each(function(index) {
var self = collection.eq(index);
valueIsFunction && (args[0] = value.call(this, index, self.html())), domManip(self, args, callback, ignored);
});
if (l && (first = (fragment = buildFragment(args, collection[0].ownerDocument, !1, collection, ignored)).firstChild, 1 === fragment.childNodes.length && (fragment = first), first || ignored)) {
// Use the original fragment for the last item
// instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for(hasScripts = (scripts = jQuery.map(getAll(fragment, "script"), disableScript)).length; i < l; i++)node = fragment, i !== iNoClone && (node = jQuery.clone(node, !0, !0), hasScripts && // Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge(scripts, getAll(node, "script"))), callback.call(collection[i], node, i);
if (hasScripts) // Evaluate executable scripts on first document insertion
for(doc = scripts[scripts.length - 1].ownerDocument, // Reenable scripts
jQuery.map(scripts, restoreScript), i = 0; i < hasScripts; i++)node = scripts[i], rscriptType.test(node.type || "") && !dataPriv.access(node, "globalEval") && jQuery.contains(doc, node) && (node.src && "module" !== (node.type || "").toLowerCase() ? jQuery._evalUrl && !node.noModule && jQuery._evalUrl(node.src, {
nonce: node.nonce || node.getAttribute("nonce")
}, doc) : DOMEval(node.textContent.replace(rcleanScript, ""), node, doc));
}
return collection;
}
function remove(elem, selector, keepData) {
for(var node, nodes = selector ? jQuery.filter(selector, elem) : elem, i = 0; null != (node = nodes[i]); i++)keepData || 1 !== node.nodeType || jQuery.cleanData(getAll(node)), node.parentNode && (keepData && isAttached(node) && setGlobalEval(getAll(node, "script")), node.parentNode.removeChild(node));
return elem;
}
jQuery.extend({
htmlPrefilter: function(html) {
return html;
},
clone: function(elem, dataAndEvents, deepDataAndEvents) {
var i, l, srcElements, destElements, clone = elem.cloneNode(!0), inPage = isAttached(elem);
// Fix IE cloning issues
if (!support.noCloneChecked && (1 === elem.nodeType || 11 === elem.nodeType) && !jQuery.isXMLDoc(elem)) for(i = 0, // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2
destElements = getAll(clone), l = (srcElements = getAll(elem)).length; i < l; i++)!// Fix IE bugs, see support tests
function(src, dest) {
var nodeName = dest.nodeName.toLowerCase();
// Fails to persist the checked state of a cloned checkbox or radio button.
"input" === nodeName && rcheckableType.test(src.type) ? dest.checked = src.checked : ("input" === nodeName || "textarea" === nodeName) && (dest.defaultValue = src.defaultValue);
}(srcElements[i], destElements[i]);
// Copy the events from the original to the clone
if (dataAndEvents) {
if (deepDataAndEvents) for(i = 0, srcElements = srcElements || getAll(elem), destElements = destElements || getAll(clone), l = srcElements.length; i < l; i++)cloneCopyEvent(srcElements[i], destElements[i]);
else cloneCopyEvent(elem, clone);
}
// Return the cloned set
return(// Preserve script evaluation history
(destElements = getAll(clone, "script")).length > 0 && setGlobalEval(destElements, !inPage && getAll(elem, "script")), clone);
},
cleanData: function(elems) {
for(var data, elem, type, special = jQuery.event.special, i = 0; void 0 !== (elem = elems[i]); i++)if (acceptData(elem)) {
if (data = elem[dataPriv.expando]) {
if (data.events) for(type in data.events)special[type] ? jQuery.event.remove(elem, type) : jQuery.removeEvent(elem, type, data.handle);
// Support: Chrome <=35 - 45+
// Assign undefined instead of using delete, see Data#remove
elem[dataPriv.expando] = void 0;
}
elem[dataUser.expando] && // Support: Chrome <=35 - 45+
// Assign undefined instead of using delete, see Data#remove
(elem[dataUser.expando] = void 0);
}
}
}), jQuery.fn.extend({
detach: function(selector) {
return remove(this, selector, !0);
},
remove: function(selector) {
return remove(this, selector);
},
text: function(value) {
return access(this, function(value) {
return void 0 === value ? jQuery.text(this) : this.empty().each(function() {
(1 === this.nodeType || 11 === this.nodeType || 9 === this.nodeType) && (this.textContent = value);
});
}, null, value, arguments.length);
},
append: function() {
return domManip(this, arguments, function(elem) {
(1 === this.nodeType || 11 === this.nodeType || 9 === this.nodeType) && manipulationTarget(this, elem).appendChild(elem);
});
},
prepend: function() {
return domManip(this, arguments, function(elem) {
if (1 === this.nodeType || 11 === this.nodeType || 9 === this.nodeType) {
var target = manipulationTarget(this, elem);
target.insertBefore(elem, target.firstChild);
}
});
},
before: function() {
return domManip(this, arguments, function(elem) {
this.parentNode && this.parentNode.insertBefore(elem, this);
});
},
after: function() {
return domManip(this, arguments, function(elem) {
this.parentNode && this.parentNode.insertBefore(elem, this.nextSibling);
});
},
empty: function() {
for(var elem, i = 0; null != (elem = this[i]); i++)1 === elem.nodeType && (// Prevent memory leaks
jQuery.cleanData(getAll(elem, !1)), // Remove any remaining nodes
elem.textContent = "");
return this;
},
clone: function(dataAndEvents, deepDataAndEvents) {
return dataAndEvents = null != dataAndEvents && dataAndEvents, deepDataAndEvents = null == deepDataAndEvents ? dataAndEvents : deepDataAndEvents, this.map(function() {
return jQuery.clone(this, dataAndEvents, deepDataAndEvents);
});
},
html: function(value) {
return access(this, function(value) {
var elem = this[0] || {}, i = 0, l = this.length;
if (void 0 === value && 1 === elem.nodeType) return elem.innerHTML;
// See if we can take a shortcut and just use innerHTML
if ("string" == typeof value && !rnoInnerhtml.test(value) && !wrapMap[(rtagName.exec(value) || [
"",
""
])[1].toLowerCase()]) {
value = jQuery.htmlPrefilter(value);
try {
for(; i < l; i++)elem = this[i] || {}, 1 === elem.nodeType && (jQuery.cleanData(getAll(elem, !1)), elem.innerHTML = value);
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch (e) {}
}
elem && this.empty().append(value);
}, null, value, arguments.length);
},
replaceWith: function() {
var ignored = [];
// Make the changes, replacing each non-ignored context element with the new content
return domManip(this, arguments, function(elem) {
var parent = this.parentNode;
0 > jQuery.inArray(this, ignored) && (jQuery.cleanData(getAll(this)), parent && parent.replaceChild(elem, this));
// Force callback invocation
}, ignored);
}
}), jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function(name, original) {
jQuery.fn[name] = function(selector) {
for(var elems, ret = [], insert = jQuery(selector), last = insert.length - 1, i = 0; i <= last; i++)elems = i === last ? this : this.clone(!0), jQuery(insert[i])[original](elems), // Support: Android <=4.0 only, PhantomJS 1 only
// .get() because push.apply(_, arraylike) throws on ancient WebKit
push.apply(ret, elems.get());
return this.pushStack(ret);
};
});
var rnumnonpx = RegExp("^(" + pnum + ")(?!px)[a-z%]+$", "i"), getStyles = function(elem) {
// Support: IE <=11 only, Firefox <=30 (#15098, #14150)
// IE throws on elements created in popups
// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
var view = elem.ownerDocument.defaultView;
return view && view.opener || (view = window1), view.getComputedStyle(elem);
}, swap = function(elem, options, callback) {
var ret, name, old = {};
// Remember the old values, and insert the new ones
for(name in options)old[name] = elem.style[name], elem.style[name] = options[name];
// Revert the old values
for(name in ret = callback.call(elem), options)elem.style[name] = old[name];
return ret;
}, rboxStyle = RegExp(cssExpand.join("|"), "i");
function curCSS(elem, name, computed) {
var width, minWidth, maxWidth, ret, // Support: Firefox 51+
// Retrieving style before computed somehow
// fixes an issue with getting wrong values
// on detached elements
style = elem.style;
return (computed = computed || getStyles(elem)) && ("" !== (ret = computed.getPropertyValue(name) || computed[name]) || isAttached(elem) || (ret = jQuery.style(elem, name)), !support.pixelBoxStyles() && rnumnonpx.test(ret) && rboxStyle.test(name) && (// Remember the original values
width = style.width, minWidth = style.minWidth, maxWidth = style.maxWidth, // Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret, ret = computed.width, // Revert the changed values
style.width = width, style.minWidth = minWidth, style.maxWidth = maxWidth)), void 0 !== ret ? // Support: IE <=9 - 11 only
// IE returns zIndex value as an integer.
ret + "" : ret;
}
function addGetHookIf(conditionFn, hookFn) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function() {
if (conditionFn()) {
// Hook not needed (or it's not possible to use it due
// to missing dependency), remove it.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return (this.get = hookFn).apply(this, arguments);
}
};
}
!function() {
// Executing both pixelPosition & boxSizingReliable tests require only one layout
// so they're executed at the same time to save the second computation.
function computeStyleTests() {
// This is a singleton, we need to execute it only once
if (div) {
container.style.cssText = "position:absolute;left:-11111px;width:60px;margin-top:1px;padding:0;border:0", div.style.cssText = "position:relative;display:block;box-sizing:border-box;overflow:scroll;margin:auto;border:1px;padding:1px;width:60%;top:1%", documentElement.appendChild(container).appendChild(div);
var divStyle = window1.getComputedStyle(div);
pixelPositionVal = "1%" !== divStyle.top, // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44
reliableMarginLeftVal = 12 === roundPixelMeasures(divStyle.marginLeft), // Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3
// Some styles come back with percentage values, even though they shouldn't
div.style.right = "60%", pixelBoxStylesVal = 36 === roundPixelMeasures(divStyle.right), // Support: IE 9 - 11 only
// Detect misreporting of content dimensions for box-sizing:border-box elements
boxSizingReliableVal = 36 === roundPixelMeasures(divStyle.width), // Support: IE 9 only
// Detect overflow:scroll screwiness (gh-3699)
// Support: Chrome <=64
// Don't get tricked when zoom affects offsetWidth (gh-4029)
div.style.position = "absolute", scrollboxSizeVal = 12 === roundPixelMeasures(div.offsetWidth / 3), documentElement.removeChild(container), // Nullify the div so it wouldn't be stored in the memory and
// it will also be a sign that checks already performed
div = null;
}
}
function roundPixelMeasures(measure) {
return Math.round(parseFloat(measure));
}
var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal, reliableTrDimensionsVal, reliableMarginLeftVal, container = document.createElement("div"), div = document.createElement("div");
// Finish early in limited (non-browser) environments
div.style && (// Support: IE <=9 - 11 only
// Style of cloned element affects source element cloned (#8908)
div.style.backgroundClip = "content-box", div.cloneNode(!0).style.backgroundClip = "", support.clearCloneStyle = "content-box" === div.style.backgroundClip, jQuery.extend(support, {
boxSizingReliable: function() {
return computeStyleTests(), boxSizingReliableVal;
},
pixelBoxStyles: function() {
return computeStyleTests(), pixelBoxStylesVal;
},
pixelPosition: function() {
return computeStyleTests(), pixelPositionVal;
},
reliableMarginLeft: function() {
return computeStyleTests(), reliableMarginLeftVal;
},
scrollboxSize: function() {
return computeStyleTests(), scrollboxSizeVal;
},
// Support: IE 9 - 11+, Edge 15 - 18+
// IE/Edge misreport `getComputedStyle` of table rows with width/height
// set in CSS while `offset*` properties report correct values.
// Behavior in IE 9 is more subtle than in newer versions & it passes
// some versions of this test; make sure not to make it pass there!
reliableTrDimensions: function() {
var table, tr, trChild;
return null == reliableTrDimensionsVal && (table = document.createElement("table"), tr = document.createElement("tr"), trChild = document.createElement("div"), table.style.cssText = "position:absolute;left:-11111px", tr.style.height = "1px", trChild.style.height = "9px", documentElement.appendChild(table).appendChild(tr).appendChild(trChild), reliableTrDimensionsVal = parseInt(window1.getComputedStyle(tr).height) > 3, documentElement.removeChild(table)), reliableTrDimensionsVal;
}
}));
}();
var cssPrefixes = [
"Webkit",
"Moz",
"ms"
], emptyStyle = document.createElement("div").style, vendorProps = {};
// Return a potentially-mapped jQuery.cssProps or vendor prefixed property
function finalPropName(name) {
return jQuery.cssProps[name] || vendorProps[name] || (name in emptyStyle ? name : vendorProps[name] = // Return a vendor-prefixed property or undefined
function(name) {
for(// Check for vendor prefixed names
var capName = name[0].toUpperCase() + name.slice(1), i = cssPrefixes.length; i--;)if ((name = cssPrefixes[i] + capName) in emptyStyle) return name;
}(name) || name);
}
var // Swappable if display is none or starts with table
// except "table", "table-cell", or "table-caption"
// See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/, rcustomProp = /^--/, cssShow = {
position: "absolute",
visibility: "hidden",
display: "block"
}, cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
};
function setPositiveNumber(_elem, value, subtract) {
// Any relative (+/-) values have already been
// normalized at this point
var matches = rcssNum.exec(value);
return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max(0, matches[2] - (subtract || 0)) + (matches[3] || "px") : value;
}
function boxModelAdjustment(elem, dimension, box, isBorderBox, styles, computedVal) {
var i = +("width" === dimension), extra = 0, delta = 0;
// Adjustment may not be necessary
if (box === (isBorderBox ? "border" : "content")) return 0;
for(; i < 4; i += 2)"margin" === box && (delta += jQuery.css(elem, box + cssExpand[i], !0, styles)), isBorderBox ? ("content" === box && (delta -= jQuery.css(elem, "padding" + cssExpand[i], !0, styles)), "margin" !== box && (delta -= jQuery.css(elem, "border" + cssExpand[i] + "Width", !0, styles))) : (// Add padding
delta += jQuery.css(elem, "padding" + cssExpand[i], !0, styles), "padding" !== box ? delta += jQuery.css(elem, "border" + cssExpand[i] + "Width", !0, styles) : extra += jQuery.css(elem, "border" + cssExpand[i] + "Width", !0, styles));
return !isBorderBox && computedVal >= 0 && // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border
// Assuming integer scroll gutter, subtract the rest and round down
(delta += Math.max(0, Math.ceil(elem["offset" + dimension[0].toUpperCase() + dimension.slice(1)] - computedVal - delta - extra - 0.5)) || 0), delta;
}
function getWidthOrHeight(elem, dimension, extra) {
// Start with computed style
var styles = getStyles(elem), isBorderBox = (!support.boxSizingReliable() || extra) && "border-box" === jQuery.css(elem, "boxSizing", !1, styles), valueIsBorderBox = isBorderBox, val = curCSS(elem, dimension, styles), offsetProp = "offset" + dimension[0].toUpperCase() + dimension.slice(1);
// Support: Firefox <=54
// Return a confounding non-pixel value or feign ignorance, as appropriate.
if (rnumnonpx.test(val)) {
if (!extra) return val;
val = "auto";
}
// Adjust for the element's box model
return (!support.boxSizingReliable() && isBorderBox || // Support: IE 10 - 11+, Edge 15 - 18+
// IE/Edge misreport `getComputedStyle` of table rows with width/height
// set in CSS while `offset*` properties report correct values.
// Interestingly, in some cases IE 9 doesn't suffer from this issue.
!support.reliableTrDimensions() && nodeName(elem, "tr") || // Fall back to offsetWidth/offsetHeight when value is "auto"
// This happens for inline elements with no explicit setting (gh-3571)
"auto" === val || // Support: Android <=4.1 - 4.3 only
// Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602)
!parseFloat(val) && "inline" === jQuery.css(elem, "display", !1, styles)) && // Make sure the element is visible & connected
elem.getClientRects().length && (isBorderBox = "border-box" === jQuery.css(elem, "boxSizing", !1, styles), // Where available, offsetWidth/offsetHeight approximate border box dimensions.
// Where not available (e.g., SVG), assume unreliable box-sizing and interpret the
// retrieved value as a content box dimension.
(valueIsBorderBox = offsetProp in elem) && (val = elem[offsetProp])), // Normalize "" and auto
(val = parseFloat(val) || 0) + boxModelAdjustment(elem, dimension, extra || (isBorderBox ? "border" : "content"), valueIsBorderBox, styles, // Provide the current computed size to request scroll gutter calculation (gh-3589)
val) + "px";
}
function Tween(elem, options, prop, end, easing) {
return new Tween.prototype.init(elem, options, prop, end, easing);
}
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function(elem, computed) {
if (computed) {
// We should always get a number back from opacity
var ret = curCSS(elem, "opacity");
return "" === ret ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
animationIterationCount: !0,
columnCount: !0,
fillOpacity: !0,
flexGrow: !0,
flexShrink: !0,
fontWeight: !0,
gridArea: !0,
gridColumn: !0,
gridColumnEnd: !0,
gridColumnStart: !0,
gridRow: !0,
gridRowEnd: !0,
gridRowStart: !0,
lineHeight: !0,
opacity: !0,
order: !0,
orphans: !0,
widows: !0,
zIndex: !0,
zoom: !0
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {},
// Get and set the style property on a DOM Node
style: function(elem, name, value, extra) {
// Don't set styles on text and comment nodes
if (elem && 3 !== elem.nodeType && 8 !== elem.nodeType && elem.style) {
// Make sure that we're working with the right name
var ret, type, hooks, origName = camelCase(name), isCustomProp = rcustomProp.test(name), style = elem.style;
// Check if we're setting a value
if (isCustomProp || (name = finalPropName(origName)), // Gets hook for the prefixed version, then unprefixed version
hooks = jQuery.cssHooks[name] || jQuery.cssHooks[origName], void 0 === value) return(// If a hook was provided get the non-computed value from there
hooks && "get" in hooks && void 0 !== (ret = hooks.get(elem, !1, extra)) ? ret : style[name]);
// Make sure that null and NaN values aren't set (#7116)
"string" == (type = typeof value) && (ret = rcssNum.exec(value)) && ret[1] && (value = adjustCSS(elem, name, ret), // Fixes bug #9237
type = "number"), null != value && value == value && ("number" !== type || isCustomProp || (value += ret && ret[3] || (jQuery.cssNumber[origName] ? "" : "px")), support.clearCloneStyle || "" !== value || 0 !== name.indexOf("background") || (style[name] = "inherit"), hooks && "set" in hooks && void 0 === (value = hooks.set(elem, value, extra)) || (isCustomProp ? style.setProperty(name, value) : style[name] = value));
}
},
css: function(elem, name, extra, styles) {
var val, num, hooks, origName = camelCase(name);
return(// Make numeric if forced or a qualifier was provided and val looks numeric
(rcustomProp.test(name) || (name = finalPropName(origName)), // Try prefixed name followed by the unprefixed name
(hooks = jQuery.cssHooks[name] || jQuery.cssHooks[origName]) && "get" in hooks && (val = hooks.get(elem, !0, extra)), void 0 === val && (val = curCSS(elem, name, styles)), "normal" === val && name in cssNormalTransform && (val = cssNormalTransform[name]), "" === extra || extra) ? (num = parseFloat(val), !0 === extra || isFinite(num) ? num || 0 : val) : val);
}
}), jQuery.each([
"height",
"width"
], function(_i, dimension) {
jQuery.cssHooks[dimension] = {
get: function(elem, computed, extra) {
if (computed) // Certain elements can have dimension info if we invisibly show them
// but it must have a current display style that would benefit
return !rdisplayswap.test(jQuery.css(elem, "display")) || // Support: Safari 8+
// Table columns in Safari have non-zero offsetWidth & zero
// getBoundingClientRect().width unless display is changed.
// Support: IE <=11 only
// Running getBoundingClientRect on a disconnected node
// in IE throws an error.
elem.getClientRects().length && elem.getBoundingClientRect().width ? getWidthOrHeight(elem, dimension, extra) : swap(elem, cssShow, function() {
return getWidthOrHeight(elem, dimension, extra);
});
},
set: function(elem, value, extra) {
var matches, styles = getStyles(elem), // Only read styles.position if the test has a chance to fail
// to avoid forcing a reflow.
scrollboxSizeBuggy = !support.scrollboxSize() && "absolute" === styles.position, isBorderBox = (scrollboxSizeBuggy || extra) && "border-box" === jQuery.css(elem, "boxSizing", !1, styles), subtract = extra ? boxModelAdjustment(elem, dimension, extra, isBorderBox, styles) : 0;
return isBorderBox && scrollboxSizeBuggy && (subtract -= Math.ceil(elem["offset" + dimension[0].toUpperCase() + dimension.slice(1)] - parseFloat(styles[dimension]) - boxModelAdjustment(elem, dimension, "border", !1, styles) - 0.5)), subtract && (matches = rcssNum.exec(value)) && "px" !== (matches[3] || "px") && (elem.style[dimension] = value, value = jQuery.css(elem, dimension)), setPositiveNumber(elem, value, subtract);
}
};
}), jQuery.cssHooks.marginLeft = addGetHookIf(support.reliableMarginLeft, function(elem, computed) {
if (computed) return (parseFloat(curCSS(elem, "marginLeft")) || elem.getBoundingClientRect().left - swap(elem, {
marginLeft: 0
}, function() {
return elem.getBoundingClientRect().left;
})) + "px";
}), // These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function(prefix, suffix) {
jQuery.cssHooks[prefix + suffix] = {
expand: function(value) {
for(var i = 0, expanded = {}, // Assumes a single number if not a string
parts = "string" == typeof value ? value.split(" ") : [
value
]; i < 4; i++)expanded[prefix + cssExpand[i] + suffix] = parts[i] || parts[i - 2] || parts[0];
return expanded;
}
}, "margin" !== prefix && (jQuery.cssHooks[prefix + suffix].set = setPositiveNumber);
}), jQuery.fn.extend({
css: function(name, value) {
return access(this, function(elem, name, value) {
var styles, len, map = {}, i = 0;
if (Array.isArray(name)) {
for(styles = getStyles(elem), len = name.length; i < len; i++)map[name[i]] = jQuery.css(elem, name[i], !1, styles);
return map;
}
return void 0 !== value ? jQuery.style(elem, name, value) : jQuery.css(elem, name);
}, name, value, arguments.length > 1);
}
}), jQuery.Tween = Tween, Tween.prototype = {
constructor: Tween,
init: function(elem, options, prop, end, easing, unit) {
this.elem = elem, this.prop = prop, this.easing = easing || jQuery.easing._default, this.options = options, this.start = this.now = this.cur(), this.end = end, this.unit = unit || (jQuery.cssNumber[prop] ? "" : "px");
},
cur: function() {
var hooks = Tween.propHooks[this.prop];
return hooks && hooks.get ? hooks.get(this) : Tween.propHooks._default.get(this);
},
run: function(percent) {
var eased, hooks = Tween.propHooks[this.prop];
return this.options.duration ? this.pos = eased = jQuery.easing[this.easing](percent, this.options.duration * percent, 0, 1, this.options.duration) : this.pos = eased = percent, this.now = (this.end - this.start) * eased + this.start, this.options.step && this.options.step.call(this.elem, this.now, this), hooks && hooks.set ? hooks.set(this) : Tween.propHooks._default.set(this), this;
}
}, Tween.prototype.init.prototype = Tween.prototype, Tween.propHooks = {
_default: {
get: function(tween) {
var result;
return(// Use a property on the element directly when it is not a DOM element,
// or when there is no matching style property that exists.
1 !== tween.elem.nodeType || null != tween.elem[tween.prop] && null == tween.elem.style[tween.prop] ? tween.elem[tween.prop] : // Passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails.
// Simple values such as "10px" are parsed to Float;
// complex values such as "rotate(1rad)" are returned as-is.
(result = jQuery.css(tween.elem, tween.prop, "")) && "auto" !== result ? result : 0);
},
set: function(tween) {
// Use step hook for back compat.
// Use cssHook if its there.
// Use .style if available and use plain properties where available.
jQuery.fx.step[tween.prop] ? jQuery.fx.step[tween.prop](tween) : 1 === tween.elem.nodeType && (jQuery.cssHooks[tween.prop] || null != tween.elem.style[finalPropName(tween.prop)]) ? jQuery.style(tween.elem, tween.prop, tween.now + tween.unit) : tween.elem[tween.prop] = tween.now;
}
}
}, // Support: IE <=9 only
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function(tween) {
tween.elem.nodeType && tween.elem.parentNode && (tween.elem[tween.prop] = tween.now);
}
}, jQuery.easing = {
linear: function(p) {
return p;
},
swing: function(p) {
return 0.5 - Math.cos(p * Math.PI) / 2;
},
_default: "swing"
}, jQuery.fx = Tween.prototype.init, // Back compat <1.8 extension point
jQuery.fx.step = {};
var div, input, fxNow, inProgress, rfxtypes = /^(?:toggle|show|hide)$/, rrun = /queueHooks$/;
// Animations created synchronously will run synchronously
function createFxNow() {
return window1.setTimeout(function() {
fxNow = void 0;
}), fxNow = Date.now();
}
// Generate parameters to create a standard animation
function genFx(type, includeWidth) {
var which, i = 0, attrs = {
height: type
};
for(// If we include width, step value is 1 to do all cssExpand values,
// otherwise step value is 2 to skip over Left and Right
includeWidth = +!!includeWidth; i < 4; i += 2 - includeWidth)attrs["margin" + (which = cssExpand[i])] = attrs["padding" + which] = type;
return includeWidth && (attrs.opacity = attrs.width = type), attrs;
}
function createTween(value, prop, animation) {
for(var tween, collection = (Animation.tweeners[prop] || []).concat(Animation.tweeners["*"]), index = 0, length = collection.length; index < length; index++)if (tween = collection[index].call(animation, prop, value)) // We're done with this property
return tween;
}
function Animation(elem, properties, options) {
var result, stopped, index = 0, length = Animation.prefilters.length, deferred = jQuery.Deferred().always(function() {
// Don't match elem in the :animated selector
delete tick.elem;
}), tick = function() {
if (stopped) return !1;
for(var currentTime = fxNow || createFxNow(), remaining = Math.max(0, animation.startTime + animation.duration - currentTime), percent = 1 - (remaining / animation.duration || 0), index = 0, length = animation.tweens.length; index < length; index++)animation.tweens[index].run(percent);
return(// If there's more to do, yield
(deferred.notifyWith(elem, [
animation,
percent,
remaining
]), percent < 1 && length) ? remaining : (length || deferred.notifyWith(elem, [
animation,
1,
0
]), // Resolve the animation and report its conclusion
deferred.resolveWith(elem, [
animation
]), !1));
}, animation = deferred.promise({
elem: elem,
props: jQuery.extend({}, properties),
opts: jQuery.extend(!0, {
specialEasing: {},
easing: jQuery.easing._default
}, options),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function(prop, end) {
var tween = jQuery.Tween(elem, animation.opts, prop, end, animation.opts.specialEasing[prop] || animation.opts.easing);
return animation.tweens.push(tween), tween;
},
stop: function(gotoEnd) {
var index = 0, // If we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if (stopped) return this;
for(stopped = !0; index < length; index++)animation.tweens[index].run(1);
return gotoEnd ? (deferred.notifyWith(elem, [
animation,
1,
0
]), deferred.resolveWith(elem, [
animation,
gotoEnd
])) : deferred.rejectWith(elem, [
animation,
gotoEnd
]), this;
}
}), props = animation.props;
for(!function(props, specialEasing) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for(index in props)if (easing = specialEasing[name = camelCase(index)], Array.isArray(value = props[index]) && (easing = value[1], value = props[index] = value[0]), index !== name && (props[name] = value, delete props[index]), (hooks = jQuery.cssHooks[name]) && "expand" in hooks) // Not quite $.extend, this won't overwrite existing keys.
// Reusing 'index' because we have the correct "name"
for(index in value = hooks.expand(value), delete props[name], value)index in props || (props[index] = value[index], specialEasing[index] = easing);
else specialEasing[name] = easing;
}(props, animation.opts.specialEasing); index < length; index++)if (result = Animation.prefilters[index].call(animation, elem, props, animation.opts)) return isFunction(result.stop) && (jQuery._queueHooks(animation.elem, animation.opts.queue).stop = result.stop.bind(result)), result;
return jQuery.map(props, createTween, animation), isFunction(animation.opts.start) && animation.opts.start.call(elem, animation), // Attach callbacks from options
animation.progress(animation.opts.progress).done(animation.opts.done, animation.opts.complete).fail(animation.opts.fail).always(animation.opts.always), jQuery.fx.timer(jQuery.extend(tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})), animation;
}
jQuery.Animation = jQuery.extend(Animation, {
tweeners: {
"*": [
function(prop, value) {
var tween = this.createTween(prop, value);
return adjustCSS(tween.elem, prop, rcssNum.exec(value), tween), tween;
}
]
},
tweener: function(props, callback) {
isFunction(props) ? (callback = props, props = [
"*"
]) : props = props.match(rnothtmlwhite);
for(var prop, index = 0, length = props.length; index < length; index++)prop = props[index], Animation.tweeners[prop] = Animation.tweeners[prop] || [], Animation.tweeners[prop].unshift(callback);
},
prefilters: [
function(elem, props, opts) {
var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, isBox = "width" in props || "height" in props, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHiddenWithinTree(elem), dataShow = dataPriv.get(elem, "fxshow");
// Detect show/hide animations
for(prop in opts.queue || (null == (hooks = jQuery._queueHooks(elem, "fx")).unqueued && (hooks.unqueued = 0, oldfire = hooks.empty.fire, hooks.empty.fire = function() {
hooks.unqueued || oldfire();
}), hooks.unqueued++, anim.always(function() {
// Ensure the complete handler is called before this completes
anim.always(function() {
hooks.unqueued--, jQuery.queue(elem, "fx").length || hooks.empty.fire();
});
})), props)if (value = props[prop], rfxtypes.test(value)) {
if (delete props[prop], toggle = toggle || "toggle" === value, value === (hidden ? "hide" : "show")) {
// Pretend to be hidden if this is a "show" and
// there is still data from a stopped show/hide
if ("show" !== value || !dataShow || void 0 === dataShow[prop]) continue;
hidden = !0;
}
orig[prop] = dataShow && dataShow[prop] || jQuery.style(elem, prop);
}
if (!(!// Bail out if this is a no-op like .hide().hide()
(propTween = !jQuery.isEmptyObject(props)) && jQuery.isEmptyObject(orig))) for(prop in isBox && 1 === elem.nodeType && (// Support: IE <=9 - 11, Edge 12 - 15
// Record all 3 overflow attributes because IE does not infer the shorthand
// from identically-valued overflowX and overflowY and Edge just mirrors
// the overflowX value there.
opts.overflow = [
style.overflow,
style.overflowX,
style.overflowY
], null == // Identify a display type, preferring old show/hide data over the CSS cascade
(restoreDisplay = dataShow && dataShow.display) && (restoreDisplay = dataPriv.get(elem, "display")), "none" === (display = jQuery.css(elem, "display")) && (restoreDisplay ? display = restoreDisplay : (// Get nonempty value(s) by temporarily forcing visibility
showHide([
elem
], !0), restoreDisplay = elem.style.display || restoreDisplay, display = jQuery.css(elem, "display"), showHide([
elem
]))), ("inline" === display || "inline-block" === display && null != restoreDisplay) && "none" === jQuery.css(elem, "float") && (propTween || (anim.done(function() {
style.display = restoreDisplay;
}), null != restoreDisplay || (restoreDisplay = "none" === (display = style.display) ? "" : display)), style.display = "inline-block")), opts.overflow && (style.overflow = "hidden", anim.always(function() {
style.overflow = opts.overflow[0], style.overflowX = opts.overflow[1], style.overflowY = opts.overflow[2];
})), // Implement show/hide animations
propTween = !1, orig)propTween || (dataShow ? "hidden" in dataShow && (hidden = dataShow.hidden) : dataShow = dataPriv.access(elem, "fxshow", {
display: restoreDisplay
}), toggle && (dataShow.hidden = !hidden), hidden && showHide([
elem
], !0), /* eslint-disable no-loop-func */ anim.done(function() {
for(prop in hidden || showHide([
elem
]), dataPriv.remove(elem, "fxshow"), orig)jQuery.style(elem, prop, orig[prop]);
})), // Per-property setup
propTween = createTween(hidden ? dataShow[prop] : 0, prop, anim), prop in dataShow || (dataShow[prop] = propTween.start, hidden && (propTween.end = propTween.start, propTween.start = 0));
}
],
prefilter: function(callback, prepend) {
prepend ? Animation.prefilters.unshift(callback) : Animation.prefilters.push(callback);
}
}), jQuery.speed = function(speed, easing, fn) {
var opt = speed && "object" == typeof speed ? jQuery.extend({}, speed) : {
complete: fn || !fn && easing || isFunction(speed) && speed,
duration: speed,
easing: fn && easing || easing && !isFunction(easing) && easing
};
return jQuery.fx.off ? opt.duration = 0 : "number" != typeof opt.duration && (opt.duration in jQuery.fx.speeds ? opt.duration = jQuery.fx.speeds[opt.duration] : opt.duration = jQuery.fx.speeds._default), (null == opt.queue || !0 === opt.queue) && (opt.queue = "fx"), // Queueing
opt.old = opt.complete, opt.complete = function() {
isFunction(opt.old) && opt.old.call(this), opt.queue && jQuery.dequeue(this, opt.queue);
}, opt;
}, jQuery.fn.extend({
fadeTo: function(speed, to, easing, callback) {
// Show any hidden elements after setting opacity to 0
return this.filter(isHiddenWithinTree).css("opacity", 0).show()// Animate to the value specified
.end().animate({
opacity: to
}, speed, easing, callback);
},
animate: function(prop, speed, easing, callback) {
var empty = jQuery.isEmptyObject(prop), optall = jQuery.speed(speed, easing, callback), doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation(this, jQuery.extend({}, prop), optall);
// Empty animations, or finishing resolves immediately
(empty || dataPriv.get(this, "finish")) && anim.stop(!0);
};
return doAnimation.finish = doAnimation, empty || !1 === optall.queue ? this.each(doAnimation) : this.queue(optall.queue, doAnimation);
},
stop: function(type, clearQueue, gotoEnd) {
var stopQueue = function(hooks) {
var stop = hooks.stop;
delete hooks.stop, stop(gotoEnd);
};
return "string" != typeof type && (gotoEnd = clearQueue, clearQueue = type, type = void 0), clearQueue && this.queue(type || "fx", []), this.each(function() {
var dequeue = !0, index = null != type && type + "queueHooks", timers = jQuery.timers, data = dataPriv.get(this);
if (index) data[index] && data[index].stop && stopQueue(data[index]);
else for(index in data)data[index] && data[index].stop && rrun.test(index) && stopQueue(data[index]);
for(index = timers.length; index--;)timers[index].elem === this && (null == type || timers[index].queue === type) && (timers[index].anim.stop(gotoEnd), dequeue = !1, timers.splice(index, 1));
// Start the next in the queue if the last step wasn't forced.
// Timers currently will call their complete callbacks, which
// will dequeue but only if they were gotoEnd.
(dequeue || !gotoEnd) && jQuery.dequeue(this, type);
});
},
finish: function(type) {
return !1 !== type && (type = type || "fx"), this.each(function() {
var index, data = dataPriv.get(this), queue = data[type + "queue"], hooks = data[type + "queueHooks"], timers = jQuery.timers, length = queue ? queue.length : 0;
// Look for any active animations, and finish them
for(// Enable finishing flag on private data
data.finish = !0, // Empty the queue first
jQuery.queue(this, type, []), hooks && hooks.stop && hooks.stop.call(this, !0), index = timers.length; index--;)timers[index].elem === this && timers[index].queue === type && (timers[index].anim.stop(!0), timers.splice(index, 1));
// Look for any animations in the old queue and finish them
for(index = 0; index < length; index++)queue[index] && queue[index].finish && queue[index].finish.call(this);
// Turn off finishing flag
delete data.finish;
});
}
}), jQuery.each([
"toggle",
"show",
"hide"
], function(_i, name) {
var cssFn = jQuery.fn[name];
jQuery.fn[name] = function(speed, easing, callback) {
return null == speed || "boolean" == typeof speed ? cssFn.apply(this, arguments) : this.animate(genFx(name, !0), speed, easing, callback);
};
}), // Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: {
opacity: "show"
},
fadeOut: {
opacity: "hide"
},
fadeToggle: {
opacity: "toggle"
}
}, function(name, props) {
jQuery.fn[name] = function(speed, easing, callback) {
return this.animate(props, speed, easing, callback);
};
}), jQuery.timers = [], jQuery.fx.tick = function() {
var timer, i = 0, timers = jQuery.timers;
for(fxNow = Date.now(); i < timers.length; i++)// Run the timer and safely remove it when done (allowing for external removal)
(timer = timers[i])() || timers[i] !== timer || timers.splice(i--, 1);
timers.length || jQuery.fx.stop(), fxNow = void 0;
}, jQuery.fx.timer = function(timer) {
jQuery.timers.push(timer), jQuery.fx.start();
}, jQuery.fx.interval = 13, jQuery.fx.start = function() {
inProgress || (inProgress = !0, function schedule() {
inProgress && (!1 === document.hidden && window1.requestAnimationFrame ? window1.requestAnimationFrame(schedule) : window1.setTimeout(schedule, jQuery.fx.interval), jQuery.fx.tick());
}());
}, jQuery.fx.stop = function() {
inProgress = null;
}, jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
}, // Based off of the plugin by Clint Helfers, with permission.
// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function(time, type) {
return time = jQuery.fx && jQuery.fx.speeds[time] || time, type = type || "fx", this.queue(type, function(next, hooks) {
var timeout = window1.setTimeout(next, time);
hooks.stop = function() {
window1.clearTimeout(timeout);
};
});
}, input1 = document.createElement("input"), opt = document.createElement("select").appendChild(document.createElement("option")), input1.type = "checkbox", // Support: Android <=4.3 only
// Default value for a checkbox should be "on"
support.checkOn = "" !== input1.value, // Support: IE <=11 only
// Must access selectedIndex to make default options select
support.optSelected = opt.selected, // Support: IE <=11 only
// An input loses its value after becoming a radio
(input1 = document.createElement("input")).value = "t", input1.type = "radio", support.radioValue = "t" === input1.value;
var input1, opt, boolHook, attrHandle = jQuery.expr.attrHandle;
jQuery.fn.extend({
attr: function(name, value) {
return access(this, jQuery.attr, name, value, arguments.length > 1);
},
removeAttr: function(name) {
return this.each(function() {
jQuery.removeAttr(this, name);
});
}
}), jQuery.extend({
attr: function(elem, name, value) {
var ret, hooks, nType = elem.nodeType;
// Don't get/set attributes on text, comment and attribute nodes
if (3 !== nType && 8 !== nType && 2 !== nType) {
// Fallback to prop when attributes are not supported
if (void 0 === elem.getAttribute) return jQuery.prop(elem, name, value);
if (1 === nType && jQuery.isXMLDoc(elem) || (hooks = jQuery.attrHooks[name.toLowerCase()] || (jQuery.expr.match.bool.test(name) ? boolHook : void 0)), void 0 !== value) {
if (null === value) {
jQuery.removeAttr(elem, name);
return;
}
return hooks && "set" in hooks && void 0 !== (ret = hooks.set(elem, value, name)) ? ret : (elem.setAttribute(name, value + ""), value);
}
return hooks && "get" in hooks && null !== (ret = hooks.get(elem, name)) ? ret : null == (ret = jQuery.find.attr(elem, name)) ? void 0 : ret;
}
},
attrHooks: {
type: {
set: function(elem, value) {
if (!support.radioValue && "radio" === value && nodeName(elem, "input")) {
var val = elem.value;
return elem.setAttribute("type", value), val && (elem.value = val), value;
}
}
}
},
removeAttr: function(elem, value) {
var name, i = 0, // Attribute names can contain non-HTML whitespace characters
// https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
attrNames = value && value.match(rnothtmlwhite);
if (attrNames && 1 === elem.nodeType) for(; name = attrNames[i++];)elem.removeAttribute(name);
}
}), // Hooks for boolean attributes
boolHook = {
set: function(elem, value, name) {
return !1 === value ? // Remove boolean attributes when set to false
jQuery.removeAttr(elem, name) : elem.setAttribute(name, name), name;
}
}, jQuery.each(jQuery.expr.match.bool.source.match(/\w+/g), function(_i, name) {
var getter = attrHandle[name] || jQuery.find.attr;
attrHandle[name] = function(elem, name, isXML) {
var ret, handle, lowercaseName = name.toLowerCase();
return isXML || (// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[lowercaseName], attrHandle[lowercaseName] = ret, ret = null != getter(elem, name, isXML) ? lowercaseName : null, attrHandle[lowercaseName] = handle), ret;
};
});
var rfocusable = /^(?:input|select|textarea|button)$/i, rclickable = /^(?:a|area)$/i;
// Strip and collapse whitespace according to HTML spec
// https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace
function stripAndCollapse(value) {
return (value.match(rnothtmlwhite) || []).join(" ");
}
function getClass(elem) {
return elem.getAttribute && elem.getAttribute("class") || "";
}
function classesToArray(value) {
return Array.isArray(value) ? value : "string" == typeof value && value.match(rnothtmlwhite) || [];
}
jQuery.fn.extend({
prop: function(name, value) {
return access(this, jQuery.prop, name, value, arguments.length > 1);
},
removeProp: function(name) {
return this.each(function() {
delete this[jQuery.propFix[name] || name];
});
}
}), jQuery.extend({
prop: function(elem, name, value) {
var ret, hooks, nType = elem.nodeType;
// Don't get/set properties on text, comment and attribute nodes
if (3 !== nType && 8 !== nType && 2 !== nType) return (1 === nType && jQuery.isXMLDoc(elem) || (// Fix name and attach hooks
name = jQuery.propFix[name] || name, hooks = jQuery.propHooks[name]), void 0 !== value) ? hooks && "set" in hooks && void 0 !== (ret = hooks.set(elem, value, name)) ? ret : elem[name] = value : hooks && "get" in hooks && null !== (ret = hooks.get(elem, name)) ? ret : elem[name];
},
propHooks: {
tabIndex: {
get: function(elem) {
// Support: IE <=9 - 11 only
// elem.tabIndex doesn't always return the
// correct value when it hasn't been explicitly set
// https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr(elem, "tabindex");
return tabindex ? parseInt(tabindex, 10) : rfocusable.test(elem.nodeName) || rclickable.test(elem.nodeName) && elem.href ? 0 : -1;
}
}
},
propFix: {
for: "htmlFor",
class: "className"
}
}), support.optSelected || (jQuery.propHooks.selected = {
get: function(elem) {
/* eslint no-unused-expressions: "off" */ var parent = elem.parentNode;
return parent && parent.parentNode && parent.parentNode.selectedIndex, null;
},
set: function(elem) {
/* eslint no-unused-expressions: "off" */ var parent = elem.parentNode;
parent && (parent.selectedIndex, parent.parentNode && parent.parentNode.selectedIndex);
}
}), jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[this.toLowerCase()] = this;
}), jQuery.fn.extend({
addClass: function(value) {
var classes, elem, cur, curValue, clazz, j, finalValue, i = 0;
if (isFunction(value)) return this.each(function(j) {
jQuery(this).addClass(value.call(this, j, getClass(this)));
});
if ((classes = classesToArray(value)).length) {
for(; elem = this[i++];)if (curValue = getClass(elem), cur = 1 === elem.nodeType && " " + stripAndCollapse(curValue) + " ") {
for(j = 0; clazz = classes[j++];)0 > cur.indexOf(" " + clazz + " ") && (cur += clazz + " ");
curValue !== // Only assign if different to avoid unneeded rendering.
(finalValue = stripAndCollapse(cur)) && elem.setAttribute("class", finalValue);
}
}
return this;
},
removeClass: function(value) {
var classes, elem, cur, curValue, clazz, j, finalValue, i = 0;
if (isFunction(value)) return this.each(function(j) {
jQuery(this).removeClass(value.call(this, j, getClass(this)));
});
if (!arguments.length) return this.attr("class", "");
if ((classes = classesToArray(value)).length) {
for(; elem = this[i++];)if (curValue = getClass(elem), // This expression is here for better compressibility (see addClass)
cur = 1 === elem.nodeType && " " + stripAndCollapse(curValue) + " ") {
for(j = 0; clazz = classes[j++];)// Remove *all* instances
for(; cur.indexOf(" " + clazz + " ") > -1;)cur = cur.replace(" " + clazz + " ", " ");
curValue !== // Only assign if different to avoid unneeded rendering.
(finalValue = stripAndCollapse(cur)) && elem.setAttribute("class", finalValue);
}
}
return this;
},
toggleClass: function(value, stateVal) {
var type = typeof value, isValidValue = "string" === type || Array.isArray(value);
return "boolean" == typeof stateVal && isValidValue ? stateVal ? this.addClass(value) : this.removeClass(value) : isFunction(value) ? this.each(function(i) {
jQuery(this).toggleClass(value.call(this, i, getClass(this), stateVal), stateVal);
}) : this.each(function() {
var className, i, self, classNames;
if (isValidValue) for(// Toggle individual class names
i = 0, self = jQuery(this), classNames = classesToArray(value); className = classNames[i++];)// Check each className given, space separated list
self.hasClass(className) ? self.removeClass(className) : self.addClass(className);
else (void 0 === value || "boolean" === type) && ((className = getClass(this)) && // Store className if set
dataPriv.set(this, "__className__", className), this.setAttribute && this.setAttribute("class", className || !1 === value ? "" : dataPriv.get(this, "__className__") || ""));
});
},
hasClass: function(selector) {
var className, elem, i = 0;
for(className = " " + selector + " "; elem = this[i++];)if (1 === elem.nodeType && (" " + stripAndCollapse(getClass(elem)) + " ").indexOf(className) > -1) return !0;
return !1;
}
});
var rreturn = /\r/g;
jQuery.fn.extend({
val: function(value) {
var hooks, ret, valueIsFunction, elem = this[0];
return arguments.length ? (valueIsFunction = isFunction(value), this.each(function(i) {
var val;
1 === this.nodeType && (null == (val = valueIsFunction ? value.call(this, i, jQuery(this).val()) : value) ? val = "" : "number" == typeof val ? val += "" : Array.isArray(val) && (val = jQuery.map(val, function(value) {
return null == value ? "" : value + "";
})), (hooks = jQuery.valHooks[this.type] || jQuery.valHooks[this.nodeName.toLowerCase()]) && "set" in hooks && void 0 !== hooks.set(this, val, "value") || (this.value = val));
})) : elem ? (hooks = jQuery.valHooks[elem.type] || jQuery.valHooks[elem.nodeName.toLowerCase()]) && "get" in hooks && void 0 !== (ret = hooks.get(elem, "value")) ? ret : "string" == typeof (ret = elem.value) ? ret.replace(rreturn, "") : null == ret ? "" : ret : void 0;
}
}), jQuery.extend({
valHooks: {
option: {
get: function(elem) {
var val = jQuery.find.attr(elem, "value");
return null != val ? val : // Support: IE <=10 - 11 only
// option.text throws exceptions (#14686, #14858)
// Strip and collapse whitespace
// https://html.spec.whatwg.org/#strip-and-collapse-whitespace
stripAndCollapse(jQuery.text(elem));
}
},
select: {
get: function(elem) {
var value, option, i, options = elem.options, index = elem.selectedIndex, one = "select-one" === elem.type, values = one ? null : [], max = one ? index + 1 : options.length;
// Loop through all the selected options
for(i = index < 0 ? max : one ? index : 0; i < max; i++)// Support: IE <=9 only
// IE8-9 doesn't update selected after form reset (#2551)
if (((option = options[i]).selected || i === index) && // Don't return options that are disabled or in a disabled optgroup
!option.disabled && (!option.parentNode.disabled || !nodeName(option.parentNode, "optgroup"))) {
// We don't need an array for one selects
if (// Get the specific value for the option
value = jQuery(option).val(), one) return value;
// Multi-Selects return an array
values.push(value);
}
return values;
},
set: function(elem, value) {
for(var optionSet, option, options = elem.options, values = jQuery.makeArray(value), i = options.length; i--;)/* eslint-disable no-cond-assign */ ((option = options[i]).selected = jQuery.inArray(jQuery.valHooks.option.get(option), values) > -1) && (optionSet = !0);
return optionSet || (elem.selectedIndex = -1), values;
}
}
}
}), // Radios and checkboxes getter/setter
jQuery.each([
"radio",
"checkbox"
], function() {
jQuery.valHooks[this] = {
set: function(elem, value) {
if (Array.isArray(value)) return elem.checked = jQuery.inArray(jQuery(elem).val(), value) > -1;
}
}, support.checkOn || (jQuery.valHooks[this].get = function(elem) {
return null === elem.getAttribute("value") ? "on" : elem.value;
});
}), // Return jQuery for attributes-only inclusion
support.focusin = "onfocusin" in window1;
var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, stopPropagationCallback = function(e) {
e.stopPropagation();
};
jQuery.extend(jQuery.event, {
trigger: function(event, data, elem, onlyHandlers) {
var i, cur, tmp, bubbleType, ontype, handle, special, lastElement, eventPath = [
elem || document
], type = hasOwn.call(event, "type") ? event.type : event, namespaces = hasOwn.call(event, "namespace") ? event.namespace.split(".") : [];
// Don't do events on text and comment nodes
if (cur = lastElement = tmp = elem = elem || document, !(3 === elem.nodeType || 8 === elem.nodeType || rfocusMorph.test(type + jQuery.event.triggered)) && (type.indexOf(".") > -1 && (type = // Namespaced trigger; create a regexp to match event type in handle()
(namespaces = type.split(".")).shift(), namespaces.sort()), ontype = 0 > type.indexOf(":") && "on" + type, // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
// Caller can pass in a jQuery.Event object, Object, or just an event type string
(event = event[jQuery.expando] ? event : new jQuery.Event(type, "object" == typeof event && event)).isTrigger = onlyHandlers ? 2 : 3, event.namespace = namespaces.join("."), event.rnamespace = event.namespace ? RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null, // Clean up the event in case it is being reused
event.result = void 0, event.target || (event.target = elem), // Clone any incoming data and prepend the event, creating the handler arg list
data = null == data ? [
event
] : jQuery.makeArray(data, [
event
]), // Allow special events to draw outside the lines
special = jQuery.event.special[type] || {}, onlyHandlers || !special.trigger || !1 !== special.trigger.apply(elem, data))) {
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if (!onlyHandlers && !special.noBubble && !isWindow(elem)) {
for(bubbleType = special.delegateType || type, rfocusMorph.test(bubbleType + type) || (cur = cur.parentNode); cur; cur = cur.parentNode)eventPath.push(cur), tmp = cur;
tmp === (elem.ownerDocument || document) && eventPath.push(tmp.defaultView || tmp.parentWindow || window1);
}
for(// Fire handlers on the event path
i = 0; (cur = eventPath[i++]) && !event.isPropagationStopped();)lastElement = cur, event.type = i > 1 ? bubbleType : special.bindType || type, // jQuery handler
(handle = (dataPriv.get(cur, "events") || Object.create(null))[event.type] && dataPriv.get(cur, "handle")) && handle.apply(cur, data), // Native handler
(handle = ontype && cur[ontype]) && handle.apply && acceptData(cur) && (event.result = handle.apply(cur, data), !1 === event.result && event.preventDefault());
return event.type = type, !onlyHandlers && !event.isDefaultPrevented() && (!special._default || !1 === special._default.apply(eventPath.pop(), data)) && acceptData(elem) && ontype && isFunction(elem[type]) && !isWindow(elem) && (// Don't re-trigger an onFOO event when we call its FOO() method
(tmp = elem[ontype]) && (elem[ontype] = null), // Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type, event.isPropagationStopped() && lastElement.addEventListener(type, stopPropagationCallback), elem[type](), event.isPropagationStopped() && lastElement.removeEventListener(type, stopPropagationCallback), jQuery.event.triggered = void 0, tmp && (elem[ontype] = tmp)), event.result;
}
},
// Piggyback on a donor event to simulate a different one
// Used only for `focus(in | out)` events
simulate: function(type, elem, event) {
var e = jQuery.extend(new jQuery.Event(), event, {
type: type,
isSimulated: !0
});
jQuery.event.trigger(e, null, elem);
}
}), jQuery.fn.extend({
trigger: function(type, data) {
return this.each(function() {
jQuery.event.trigger(type, data, this);
});
},
triggerHandler: function(type, data) {
var elem = this[0];
if (elem) return jQuery.event.trigger(type, data, elem, !0);
}
}), support.focusin || jQuery.each({
focus: "focusin",
blur: "focusout"
}, function(orig, fix) {
// Attach a single capturing handler on the document while someone wants focusin/focusout
var handler = function(event) {
jQuery.event.simulate(fix, event.target, jQuery.event.fix(event));
};
jQuery.event.special[fix] = {
setup: function() {
// Handle: regular nodes (via `this.ownerDocument`), window
// (via `this.document`) & document (via `this`).
var doc = this.ownerDocument || this.document || this, attaches = dataPriv.access(doc, fix);
attaches || doc.addEventListener(orig, handler, !0), dataPriv.access(doc, fix, (attaches || 0) + 1);
},
teardown: function() {
var doc = this.ownerDocument || this.document || this, attaches = dataPriv.access(doc, fix) - 1;
attaches ? dataPriv.access(doc, fix, attaches) : (doc.removeEventListener(orig, handler, !0), dataPriv.remove(doc, fix));
}
};
});
var location = window1.location, nonce = {
guid: Date.now()
}, rquery = /\?/;
// Cross-browser xml parsing
jQuery.parseXML = function(data) {
var xml;
if (!data || "string" != typeof data) return null;
// Support: IE 9 - 11 only
// IE throws on parseFromString with invalid input.
try {
xml = new window1.DOMParser().parseFromString(data, "text/xml");
} catch (e) {
xml = void 0;
}
return (!xml || xml.getElementsByTagName("parsererror").length) && jQuery.error("Invalid XML: " + data), xml;
};
var rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i;
// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function(a, traditional) {
var prefix, s = [], add = function(key, valueOrFunction) {
// If value is a function, invoke it and use its return value
var value = isFunction(valueOrFunction) ? valueOrFunction() : valueOrFunction;
s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(null == value ? "" : value);
};
if (null == a) return "";
// If an array was passed in, assume that it is an array of form elements.
if (Array.isArray(a) || a.jquery && !jQuery.isPlainObject(a)) // Serialize the form elements
jQuery.each(a, function() {
add(this.name, this.value);
});
else // If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for(prefix in a)!function buildParams(prefix, obj, traditional, add) {
var name;
if (Array.isArray(obj)) // Serialize array item.
jQuery.each(obj, function(i, v) {
traditional || rbracket.test(prefix) ? // Treat each array item as a scalar.
add(prefix, v) : // Item is non-scalar (array or object), encode its numeric index.
buildParams(prefix + "[" + ("object" == typeof v && null != v ? i : "") + "]", v, traditional, add);
});
else if (traditional || "object" !== toType(obj)) // Serialize scalar item.
add(prefix, obj);
else // Serialize object item.
for(name in obj)buildParams(prefix + "[" + name + "]", obj[name], traditional, add);
}(prefix, a[prefix], traditional, add);
// Return the resulting serialization
return s.join("&");
}, jQuery.fn.extend({
serialize: function() {
return jQuery.param(this.serializeArray());
},
serializeArray: function() {
return this.map(function() {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop(this, "elements");
return elements ? jQuery.makeArray(elements) : this;
}).filter(function() {
var type = this.type;
// Use .is( ":disabled" ) so that fieldset[disabled] works
return this.name && !jQuery(this).is(":disabled") && rsubmittable.test(this.nodeName) && !rsubmitterTypes.test(type) && (this.checked || !rcheckableType.test(type));
}).map(function(_i, elem) {
var val = jQuery(this).val();
return null == val ? null : Array.isArray(val) ? jQuery.map(val, function(val) {
return {
name: elem.name,
value: val.replace(rCRLF, "\r\n")
};
}) : {
name: elem.name,
value: val.replace(rCRLF, "\r\n")
};
}).get();
}
});
var r20 = /%20/g, rhash = /#.*$/, rantiCache = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, /* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/ prefilters = {}, /* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat("*"), // Anchor tag for parsing the document origin
originAnchor = document.createElement("a");
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports(structure) {
// dataTypeExpression is optional and defaults to "*"
return function(dataTypeExpression, func) {
"string" != typeof dataTypeExpression && (func = dataTypeExpression, dataTypeExpression = "*");
var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match(rnothtmlwhite) || [];
if (isFunction(func)) // For each dataType in the dataTypeExpression
for(; dataType = dataTypes[i++];)// Prepend if requested
"+" === dataType[0] ? (structure[dataType = dataType.slice(1) || "*"] = structure[dataType] || []).unshift(func) : (structure[dataType] = structure[dataType] || []).push(func);
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports(structure, options, originalOptions, jqXHR) {
var inspected = {}, seekingTransport = structure === transports;
function inspect(dataType) {
var selected;
return inspected[dataType] = !0, jQuery.each(structure[dataType] || [], function(_, prefilterOrFactory) {
var dataTypeOrTransport = prefilterOrFactory(options, originalOptions, jqXHR);
return "string" != typeof dataTypeOrTransport || seekingTransport || inspected[dataTypeOrTransport] ? seekingTransport ? !(selected = dataTypeOrTransport) : void 0 : (options.dataTypes.unshift(dataTypeOrTransport), inspect(dataTypeOrTransport), !1);
}), selected;
}
return inspect(options.dataTypes[0]) || !inspected["*"] && inspect("*");
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend(target, src) {
var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {};
for(key in src)void 0 !== src[key] && ((flatOptions[key] ? target : deep || (deep = {}))[key] = src[key]);
return deep && jQuery.extend(!0, target, deep), target;
}
originAnchor.href = location.href, jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: location.href,
type: "GET",
isLocal: /^(?:about|app|app-storage|.+-extension|file|res|widget):$/.test(location.protocol),
global: !0,
processData: !0,
async: !0,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/ accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /\bxml\b/,
html: /\bhtml/,
json: /\bjson\b/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": !0,
// Evaluate text as a json expression
"text json": JSON.parse,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: !0,
context: !0
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function(target, settings) {
return settings ? // Building a settings object
ajaxExtend(ajaxExtend(target, jQuery.ajaxSettings), settings) : // Extending ajaxSettings
ajaxExtend(jQuery.ajaxSettings, target);
},
ajaxPrefilter: addToPrefiltersOrTransports(prefilters),
ajaxTransport: addToPrefiltersOrTransports(transports),
// Main method
ajax: function(url, options) {
"object" == typeof url && (options = url, url = void 0), // Force options to be an object
options = options || {};
var transport, // URL without anti-cache param
cacheURL, // Response headers
responseHeadersString, responseHeaders, // timeout handle
timeoutTimer, // Url cleanup var
urlAnchor, // Request state (becomes false upon send and true upon completion)
completed, // To know if global events are to be dispatched
fireGlobals, // Loop variable
i, // uncached part of the url
uncached, // Create the final options object
s = jQuery.ajaxSetup({}, options), // Callbacks context
callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && (callbackContext.nodeType || callbackContext.jquery) ? jQuery(callbackContext) : jQuery.event, // Deferreds
deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks
statusCode = s.statusCode || {}, // Headers (they are sent all at once)
requestHeaders = {}, requestHeadersNames = {}, // Default abort message
strAbort = "canceled", // Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function(key) {
var match;
if (completed) {
if (!responseHeaders) for(responseHeaders = {}; match = rheaders.exec(responseHeadersString);)responseHeaders[match[1].toLowerCase() + " "] = (responseHeaders[match[1].toLowerCase() + " "] || []).concat(match[2]);
match = responseHeaders[key.toLowerCase() + " "];
}
return null == match ? null : match.join(", ");
},
// Raw string
getAllResponseHeaders: function() {
return completed ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function(name, value) {
return null == completed && (requestHeaders[name = requestHeadersNames[name.toLowerCase()] = requestHeadersNames[name.toLowerCase()] || name] = value), this;
},
// Overrides response content-type header
overrideMimeType: function(type) {
return null == completed && (s.mimeType = type), this;
},
// Status-dependent callbacks
statusCode: function(map) {
var code;
if (map) {
if (completed) // Execute the appropriate callbacks
jqXHR.always(map[jqXHR.status]);
else // Lazy-add the new callbacks in a way that preserves old ones
for(code in map)statusCode[code] = [
statusCode[code],
map[code]
];
}
return this;
},
// Cancel the request
abort: function(statusText) {
var finalText = statusText || strAbort;
return transport && transport.abort(finalText), done(0, finalText), this;
}
};
// A cross-domain request is in order when the origin doesn't match the current origin.
if (// Attach deferreds
deferred.promise(jqXHR), // Add protocol if not provided (prefilters might expect it)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ((url || s.url || location.href) + "").replace(rprotocol, location.protocol + "//"), // Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type, // Extract dataTypes list
s.dataTypes = (s.dataType || "*").toLowerCase().match(rnothtmlwhite) || [
""
], null == s.crossDomain) {
urlAnchor = document.createElement("a");
// Support: IE <=8 - 11, Edge 12 - 15
// IE throws exception on accessing the href property if url is malformed,
// e.g. http://example.com:80x/
try {
urlAnchor.href = s.url, // Support: IE <=8 - 11 only
// Anchor's host property isn't correctly set when s.url is relative
urlAnchor.href = urlAnchor.href, s.crossDomain = originAnchor.protocol + "//" + originAnchor.host != urlAnchor.protocol + "//" + urlAnchor.host;
} catch (e) {
// If there is an error parsing the URL, assume it is crossDomain,
// it can be rejected by the transport if it is invalid
s.crossDomain = !0;
}
}
// If request was aborted inside a prefilter, stop there
if (s.data && s.processData && "string" != typeof s.data && (s.data = jQuery.param(s.data, s.traditional)), // Apply prefilters
inspectPrefiltersOrTransports(prefilters, s, options, jqXHR), completed) return jqXHR;
// Check for headers option
for(i in // We can fire global events as of now if asked to
// Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
(fireGlobals = jQuery.event && s.global) && 0 == jQuery.active++ && jQuery.event.trigger("ajaxStart"), // Uppercase the type
s.type = s.type.toUpperCase(), // Determine if request has content
s.hasContent = !rnoContent.test(s.type), // Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
// Remove hash to simplify url manipulation
cacheURL = s.url.replace(rhash, ""), s.hasContent ? s.data && s.processData && 0 === (s.contentType || "").indexOf("application/x-www-form-urlencoded") && (s.data = s.data.replace(r20, "+")) : (// Remember the hash so we can put it back
uncached = s.url.slice(cacheURL.length), s.data && (s.processData || "string" == typeof s.data) && (cacheURL += (rquery.test(cacheURL) ? "&" : "?") + s.data, // #9682: remove data so that it's not used in an eventual retry
delete s.data), !1 === s.cache && (cacheURL = cacheURL.replace(rantiCache, "$1"), uncached = (rquery.test(cacheURL) ? "&" : "?") + "_=" + nonce.guid++ + uncached), // Put hash and anti-cache on the URL that will be requested (gh-1732)
s.url = cacheURL + uncached), s.ifModified && (jQuery.lastModified[cacheURL] && jqXHR.setRequestHeader("If-Modified-Since", jQuery.lastModified[cacheURL]), jQuery.etag[cacheURL] && jqXHR.setRequestHeader("If-None-Match", jQuery.etag[cacheURL])), (s.data && s.hasContent && !1 !== s.contentType || options.contentType) && jqXHR.setRequestHeader("Content-Type", s.contentType), // Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader("Accept", s.dataTypes[0] && s.accepts[s.dataTypes[0]] ? s.accepts[s.dataTypes[0]] + ("*" !== s.dataTypes[0] ? ", " + allTypes + "; q=0.01" : "") : s.accepts["*"]), s.headers)jqXHR.setRequestHeader(i, s.headers[i]);
// Allow custom headers/mimetypes and early abort
if (s.beforeSend && (!1 === s.beforeSend.call(callbackContext, jqXHR, s) || completed)) // Abort if not done already and return
return jqXHR.abort();
// If no transport, we auto-abort
if (// Aborting is no longer a cancellation
strAbort = "abort", // Install callbacks on deferreds
completeDeferred.add(s.complete), jqXHR.done(s.success), jqXHR.fail(s.error), // Get transport
transport = inspectPrefiltersOrTransports(transports, s, options, jqXHR)) {
// If request was aborted inside ajaxSend, stop there
if (jqXHR.readyState = 1, fireGlobals && globalEventContext.trigger("ajaxSend", [
jqXHR,
s
]), completed) return jqXHR;
s.async && s.timeout > 0 && (timeoutTimer = window1.setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout));
try {
completed = !1, transport.send(requestHeaders, done);
} catch (e) {
// Rethrow post-completion exceptions
if (completed) throw e;
// Propagate others as results
done(-1, e);
}
} else done(-1, "No Transport");
// Callback for when everything is done
function done(status, nativeStatusText, responses, headers) {
var isSuccess, success, error, response, modified, statusText = nativeStatusText;
// Ignore repeat invocations
!completed && (completed = !0, timeoutTimer && window1.clearTimeout(timeoutTimer), // Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = void 0, // Cache response headers
responseHeadersString = headers || "", // Set readyState
jqXHR.readyState = 4 * (status > 0), // Determine if successful
isSuccess = status >= 200 && status < 300 || 304 === status, responses && (response = /* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/ function(s, jqXHR, responses) {
// Remove auto dataType and get content-type in the process
for(var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; "*" === dataTypes[0];)dataTypes.shift(), void 0 === ct && (ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"));
// Check if we're dealing with a known content-type
if (ct) {
for(type in contents)if (contents[type] && contents[type].test(ct)) {
dataTypes.unshift(type);
break;
}
}
// Check to see if we have a response for the expected dataType
if (dataTypes[0] in responses) finalDataType = dataTypes[0];
else {
// Try convertible dataTypes
for(type in responses){
if (!dataTypes[0] || s.converters[type + " " + dataTypes[0]]) {
finalDataType = type;
break;
}
firstDataType || (firstDataType = type);
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if (finalDataType) return finalDataType !== dataTypes[0] && dataTypes.unshift(finalDataType), responses[finalDataType];
}(s, jqXHR, responses)), !isSuccess && jQuery.inArray("script", s.dataTypes) > -1 && (s.converters["text script"] = function() {}), // Convert no matter what (that way responseXXX fields are always set)
response = /* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/ function(s, response, jqXHR, isSuccess) {
var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if (dataTypes[1]) for(conv in s.converters)converters[conv.toLowerCase()] = s.converters[conv];
// Convert to each sequential dataType
for(current = dataTypes.shift(); current;)if (s.responseFields[current] && (jqXHR[s.responseFields[current]] = response), !prev && isSuccess && s.dataFilter && (response = s.dataFilter(response, s.dataType)), prev = current, current = dataTypes.shift()) {
// There's only work to do if current dataType is non-auto
if ("*" === current) current = prev;
else if ("*" !== prev && prev !== current) {
// If none found, seek a pair
if (!// Seek a direct converter
(conv = converters[prev + " " + current] || converters["* " + current])) {
for(conv2 in converters)if (// If conv2 outputs current
(tmp = conv2.split(" "))[1] === current && // If prev can be converted to accepted input
(conv = converters[prev + " " + tmp[0]] || converters["* " + tmp[0]])) {
// Condense equivalence converters
!0 === conv ? conv = converters[conv2] : !0 !== converters[conv2] && (current = tmp[0], dataTypes.unshift(tmp[1]));
break;
}
}
// Apply converter (if not an equivalence)
if (!0 !== conv) {
// Unless errors are allowed to bubble, catch and return them
if (conv && s.throws) response = conv(response);
else try {
response = conv(response);
} catch (e) {
return {
state: "parsererror",
error: conv ? e : "No conversion from " + prev + " to " + current
};
}
}
}
}
return {
state: "success",
data: response
};
}(s, response, jqXHR, isSuccess), isSuccess ? (s.ifModified && ((modified = jqXHR.getResponseHeader("Last-Modified")) && (jQuery.lastModified[cacheURL] = modified), (modified = jqXHR.getResponseHeader("etag")) && (jQuery.etag[cacheURL] = modified)), 204 === status || "HEAD" === s.type ? statusText = "nocontent" : 304 === status ? statusText = "notmodified" : (statusText = response.state, success = response.data, isSuccess = !(error = response.error))) : (// Extract error from statusText and normalize for non-aborts
error = statusText, (status || !statusText) && (statusText = "error", status < 0 && (status = 0))), // Set data for the fake xhr object
jqXHR.status = status, jqXHR.statusText = (nativeStatusText || statusText) + "", isSuccess ? deferred.resolveWith(callbackContext, [
success,
statusText,
jqXHR
]) : deferred.rejectWith(callbackContext, [
jqXHR,
statusText,
error
]), // Status-dependent callbacks
jqXHR.statusCode(statusCode), statusCode = void 0, fireGlobals && globalEventContext.trigger(isSuccess ? "ajaxSuccess" : "ajaxError", [
jqXHR,
s,
isSuccess ? success : error
]), // Complete
completeDeferred.fireWith(callbackContext, [
jqXHR,
statusText
]), !fireGlobals || (globalEventContext.trigger("ajaxComplete", [
jqXHR,
s
]), --jQuery.active || jQuery.event.trigger("ajaxStop")));
}
return jqXHR;
},
getJSON: function(url, data, callback) {
return jQuery.get(url, data, callback, "json");
},
getScript: function(url, callback) {
return jQuery.get(url, void 0, callback, "script");
}
}), jQuery.each([
"get",
"post"
], function(_i, method) {
jQuery[method] = function(url, data, callback, type) {
// The url can be an options object (which then must have .url)
return isFunction(data) && (type = type || callback, callback = data, data = void 0), jQuery.ajax(jQuery.extend({
url: url,
type: method,
dataType: type,
data: data,
success: callback
}, jQuery.isPlainObject(url) && url));
};
}), jQuery.ajaxPrefilter(function(s) {
var i;
for(i in s.headers)"content-type" === i.toLowerCase() && (s.contentType = s.headers[i] || "");
}), jQuery._evalUrl = function(url, options, doc) {
return jQuery.ajax({
url: url,
// Make this explicit, since user can override this through ajaxSetup (#11264)
type: "GET",
dataType: "script",
cache: !0,
async: !1,
global: !1,
// Only evaluate the response if it is successful (gh-4126)
// dataFilter is not invoked for failure responses, so using it instead
// of the default converter is kludgy but it works.
converters: {
"text script": function() {}
},
dataFilter: function(response) {
jQuery.globalEval(response, options, doc);
}
});
}, jQuery.fn.extend({
wrapAll: function(html) {
var wrap;
return this[0] && (isFunction(html) && (html = html.call(this[0])), // The elements to wrap the target around
wrap = jQuery(html, this[0].ownerDocument).eq(0).clone(!0), this[0].parentNode && wrap.insertBefore(this[0]), wrap.map(function() {
for(var elem = this; elem.firstElementChild;)elem = elem.firstElementChild;
return elem;
}).append(this)), this;
},
wrapInner: function(html) {
return isFunction(html) ? this.each(function(i) {
jQuery(this).wrapInner(html.call(this, i));
}) : this.each(function() {
var self = jQuery(this), contents = self.contents();
contents.length ? contents.wrapAll(html) : self.append(html);
});
},
wrap: function(html) {
var htmlIsFunction = isFunction(html);
return this.each(function(i) {
jQuery(this).wrapAll(htmlIsFunction ? html.call(this, i) : html);
});
},
unwrap: function(selector) {
return this.parent(selector).not("body").each(function() {
jQuery(this).replaceWith(this.childNodes);
}), this;
}
}), jQuery.expr.pseudos.hidden = function(elem) {
return !jQuery.expr.pseudos.visible(elem);
}, jQuery.expr.pseudos.visible = function(elem) {
return !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length);
}, jQuery.ajaxSettings.xhr = function() {
try {
return new window1.XMLHttpRequest();
} catch (e) {}
};
var xhrSuccessStatus = {
// File protocol always yields status code 0, assume 200
0: 200,
// Support: IE <=9 only
// #1450: sometimes IE returns 1223 when it should be 204
1223: 204
}, xhrSupported = jQuery.ajaxSettings.xhr();
support.cors = !!xhrSupported && "withCredentials" in xhrSupported, support.ajax = xhrSupported = !!xhrSupported, jQuery.ajaxTransport(function(options) {
var callback, errorCallback;
// Cross domain only allowed if supported through XMLHttpRequest
if (support.cors || xhrSupported && !options.crossDomain) return {
send: function(headers, complete) {
var i, xhr = options.xhr();
// Apply custom fields if provided
if (xhr.open(options.type, options.url, options.async, options.username, options.password), options.xhrFields) for(i in options.xhrFields)xhr[i] = options.xhrFields[i];
// Set headers
for(i in options.mimeType && xhr.overrideMimeType && xhr.overrideMimeType(options.mimeType), options.crossDomain || headers["X-Requested-With"] || (headers["X-Requested-With"] = "XMLHttpRequest"), headers)xhr.setRequestHeader(i, headers[i]);
// Callback
callback = function(type) {
return function() {
callback && (callback = errorCallback = xhr.onload = xhr.onerror = xhr.onabort = xhr.ontimeout = xhr.onreadystatechange = null, "abort" === type ? xhr.abort() : "error" === type ? "number" != typeof xhr.status ? complete(0, "error") : complete(// File: protocol always yields status 0; see #8605, #14207
xhr.status, xhr.statusText) : complete(xhrSuccessStatus[xhr.status] || xhr.status, xhr.statusText, "text" !== // Support: IE <=9 only
// IE9 has no XHR2 but throws on binary (trac-11426)
// For XHR2 non-text, let the caller handle it (gh-2498)
(xhr.responseType || "text") || "string" != typeof xhr.responseText ? {
binary: xhr.response
} : {
text: xhr.responseText
}, xhr.getAllResponseHeaders()));
};
}, // Listen to events
xhr.onload = callback(), errorCallback = xhr.onerror = xhr.ontimeout = callback("error"), void 0 !== xhr.onabort ? xhr.onabort = errorCallback : xhr.onreadystatechange = function() {
// Check readyState before timeout as it changes
4 === xhr.readyState && // Allow onerror to be called first,
// but that will not handle a native abort
// Also, save errorCallback to a variable
// as xhr.onerror cannot be accessed
window1.setTimeout(function() {
callback && errorCallback();
});
}, // Create the abort callback
callback = callback("abort");
try {
// Do send the request (this may raise an exception)
xhr.send(options.hasContent && options.data || null);
} catch (e) {
// #14683: Only rethrow if this hasn't been notified as an error yet
if (callback) throw e;
}
},
abort: function() {
callback && callback();
}
};
}), // Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432)
jQuery.ajaxPrefilter(function(s) {
s.crossDomain && (s.contents.script = !1);
}), // Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /\b(?:java|ecma)script\b/
},
converters: {
"text script": function(text) {
return jQuery.globalEval(text), text;
}
}
}), // Handle cache's special case and crossDomain
jQuery.ajaxPrefilter("script", function(s) {
void 0 === s.cache && (s.cache = !1), s.crossDomain && (s.type = "GET");
}), // Bind script tag hack transport
jQuery.ajaxTransport("script", function(s) {
// This transport only deals with cross domain or forced-by-attrs requests
if (s.crossDomain || s.scriptAttrs) {
var script, callback;
return {
send: function(_, complete) {
script = jQuery("<script>").attr(s.scriptAttrs || {}).prop({
charset: s.scriptCharset,
src: s.url
}).on("load error", callback = function(evt) {
script.remove(), callback = null, evt && complete("error" === evt.type ? 404 : 200, evt.type);
}), // Use native DOM manipulation to avoid our domManip AJAX trickery
document.head.appendChild(script[0]);
},
abort: function() {
callback && callback();
}
};
}
});
var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || jQuery.expando + "_" + nonce.guid++;
return this[callback] = !0, callback;
}
}), // Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter("json jsonp", function(s, originalSettings, jqXHR) {
var callbackName, overwritten, responseContainer, jsonProp = !1 !== s.jsonp && (rjsonp.test(s.url) ? "url" : "string" == typeof s.data && 0 === (s.contentType || "").indexOf("application/x-www-form-urlencoded") && rjsonp.test(s.data) && "data");
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if (jsonProp || "jsonp" === s.dataTypes[0]) // Delegate to script
return(// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = isFunction(s.jsonpCallback) ? s.jsonpCallback() : s.jsonpCallback, jsonProp ? s[jsonProp] = s[jsonProp].replace(rjsonp, "$1" + callbackName) : !1 !== s.jsonp && (s.url += (rquery.test(s.url) ? "&" : "?") + s.jsonp + "=" + callbackName), // Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
return responseContainer || jQuery.error(callbackName + " was not called"), responseContainer[0];
}, // Force json dataType
s.dataTypes[0] = "json", // Install callback
overwritten = window1[callbackName], window1[callbackName] = function() {
responseContainer = arguments;
}, // Clean-up function (fires after converters)
jqXHR.always(function() {
void 0 === overwritten ? jQuery(window1).removeProp(callbackName) : window1[callbackName] = overwritten, s[callbackName] && (// Make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback, // Save the callback name for future use
oldCallbacks.push(callbackName)), responseContainer && isFunction(overwritten) && overwritten(responseContainer[0]), responseContainer = overwritten = void 0;
}), "script");
}), (body = document.implementation.createHTMLDocument("").body).innerHTML = "<form></form><form></form>", // Support: Safari 8 only
// In Safari 8 documents created via document.implementation.createHTMLDocument
// collapse sibling forms: the second one becomes a child of the first one.
// Because of that, this security measure has to be disabled in Safari 8.
// https://bugs.webkit.org/show_bug.cgi?id=137337
support.createHTMLDocument = 2 === body.childNodes.length, // Argument "data" should be string of html
// context (optional): If specified, the fragment will be created in this context,
// defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function(data, context, keepScripts) {
var base, parsed, scripts;
return "string" != typeof data ? [] : ("boolean" == typeof context && (keepScripts = context, context = !1), context || (support.createHTMLDocument ? (// Set the base href for the created document
// so any parsed elements with URLs
// are based on the document's URL (gh-2965)
(base = (context = document.implementation.createHTMLDocument("")).createElement("base")).href = document.location.href, context.head.appendChild(base)) : context = document), parsed = rsingleTag.exec(data), scripts = !keepScripts && [], parsed) ? [
context.createElement(parsed[1])
] : (parsed = buildFragment([
data
], context, scripts), scripts && scripts.length && jQuery(scripts).remove(), jQuery.merge([], parsed.childNodes));
}, /**
* Load a url into a page
*/ jQuery.fn.load = function(url, params, callback) {
var selector, type, response, self = this, off = url.indexOf(" ");
return off > -1 && (selector = stripAndCollapse(url.slice(off)), url = url.slice(0, off)), isFunction(params) ? (// We assume that it's the callback
callback = params, params = void 0) : params && "object" == typeof params && (type = "POST"), self.length > 0 && jQuery.ajax({
url: url,
// If "type" variable is undefined, then "GET" method will be used.
// Make value of this field explicit since
// user can override it through ajaxSetup method
type: type || "GET",
dataType: "html",
data: params
}).done(function(responseText) {
// Save response for use in complete callback
response = arguments, self.html(selector ? // If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector) : // Otherwise use the full result
responseText);
// If the request succeeds, this function gets "data", "status", "jqXHR"
// but they are ignored because response was set above.
// If it fails, this function gets "jqXHR", "status", "error"
}).always(callback && function(jqXHR, status) {
self.each(function() {
callback.apply(this, response || [
jqXHR.responseText,
status,
jqXHR
]);
});
}), this;
}, jQuery.expr.pseudos.animated = function(elem) {
return jQuery.grep(jQuery.timers, function(fn) {
return elem === fn.elem;
}).length;
}, jQuery.offset = {
setOffset: function(elem, options, i) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, position = jQuery.css(elem, "position"), curElem = jQuery(elem), props = {};
"static" === position && (elem.style.position = "relative"), curOffset = curElem.offset(), curCSSTop = jQuery.css(elem, "top"), curCSSLeft = jQuery.css(elem, "left"), ("absolute" === position || "fixed" === position) && (curCSSTop + curCSSLeft).indexOf("auto") > -1 ? (curTop = (curPosition = curElem.position()).top, curLeft = curPosition.left) : (curTop = parseFloat(curCSSTop) || 0, curLeft = parseFloat(curCSSLeft) || 0), isFunction(options) && // Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
(options = options.call(elem, i, jQuery.extend({}, curOffset))), null != options.top && (props.top = options.top - curOffset.top + curTop), null != options.left && (props.left = options.left - curOffset.left + curLeft), "using" in options ? options.using.call(elem, props) : ("number" == typeof props.top && (props.top += "px"), "number" == typeof props.left && (props.left += "px"), curElem.css(props));
}
}, jQuery.fn.extend({
// offset() relates an element's border box to the document origin
offset: function(options) {
// Preserve chaining for setter
if (arguments.length) return void 0 === options ? this : this.each(function(i) {
jQuery.offset.setOffset(this, options, i);
});
var rect, win, elem = this[0];
return elem ? elem.getClientRects().length ? (// Get document-relative position by adding viewport scroll to viewport-relative gBCR
rect = elem.getBoundingClientRect(), win = elem.ownerDocument.defaultView, {
top: rect.top + win.pageYOffset,
left: rect.left + win.pageXOffset
}) : {
top: 0,
left: 0
} : void 0;
},
// position() relates an element's margin box to its offset parent's padding box
// This corresponds to the behavior of CSS absolute positioning
position: function() {
if (this[0]) {
var offsetParent, offset, doc, elem = this[0], parentOffset = {
top: 0,
left: 0
};
// position:fixed elements are offset from the viewport, which itself always has zero offset
if ("fixed" === jQuery.css(elem, "position")) // Assume position:fixed implies availability of getBoundingClientRect
offset = elem.getBoundingClientRect();
else {
for(offset = this.offset(), // Account for the *real* offset parent, which can be the document or its root element
// when a statically positioned element is identified
doc = elem.ownerDocument, offsetParent = elem.offsetParent || doc.documentElement; offsetParent && (offsetParent === doc.body || offsetParent === doc.documentElement) && "static" === jQuery.css(offsetParent, "position");)offsetParent = offsetParent.parentNode;
offsetParent && offsetParent !== elem && 1 === offsetParent.nodeType && (// Incorporate borders into its offset, since they are outside its content origin
parentOffset = jQuery(offsetParent).offset(), parentOffset.top += jQuery.css(offsetParent, "borderTopWidth", !0), parentOffset.left += jQuery.css(offsetParent, "borderLeftWidth", !0));
}
// Subtract parent offsets and element margins
return {
top: offset.top - parentOffset.top - jQuery.css(elem, "marginTop", !0),
left: offset.left - parentOffset.left - jQuery.css(elem, "marginLeft", !0)
};
}
},
// This method will return documentElement in the following cases:
// 1) For the element inside the iframe without offsetParent, this method will return
// documentElement of the parent window
// 2) For the hidden or detached element
// 3) For body or html element, i.e. in case of the html node - it will return itself
//
// but those exceptions were never presented as a real life use-cases
// and might be considered as more preferable results.
//
// This logic, however, is not guaranteed and can change at any point in the future
offsetParent: function() {
return this.map(function() {
for(var offsetParent = this.offsetParent; offsetParent && "static" === jQuery.css(offsetParent, "position");)offsetParent = offsetParent.offsetParent;
return offsetParent || documentElement;
});
}
}), // Create scrollLeft and scrollTop methods
jQuery.each({
scrollLeft: "pageXOffset",
scrollTop: "pageYOffset"
}, function(method, prop) {
var top = "pageYOffset" === prop;
jQuery.fn[method] = function(val) {
return access(this, function(elem, method, val) {
// Coalesce documents and windows
var win;
if (isWindow(elem) ? win = elem : 9 === elem.nodeType && (win = elem.defaultView), void 0 === val) return win ? win[prop] : elem[method];
win ? win.scrollTo(top ? win.pageXOffset : val, top ? val : win.pageYOffset) : elem[method] = val;
}, method, val, arguments.length);
};
}), // Support: Safari <=7 - 9.1, Chrome <=37 - 49
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347
// getComputedStyle returns percent when specified for top/left/bottom/right;
// rather than make the css module depend on the offset module, just check for it here
jQuery.each([
"top",
"left"
], function(_i, prop) {
jQuery.cssHooks[prop] = addGetHookIf(support.pixelPosition, function(elem, computed) {
if (computed) // If curCSS returns percentage, fallback to offset
return computed = curCSS(elem, prop), rnumnonpx.test(computed) ? jQuery(elem).position()[prop] + "px" : computed;
});
}), // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each({
Height: "height",
Width: "width"
}, function(name, type) {
jQuery.each({
padding: "inner" + name,
content: type,
"": "outer" + name
}, function(defaultExtra, funcName) {
// Margin is only for outerHeight, outerWidth
jQuery.fn[funcName] = function(margin, value) {
var chainable = arguments.length && (defaultExtra || "boolean" != typeof margin), extra = defaultExtra || (!0 === margin || !0 === value ? "margin" : "border");
return access(this, function(elem, type, value) {
var doc;
return isWindow(elem) ? 0 === funcName.indexOf("outer") ? elem["inner" + name] : elem.document.documentElement["client" + name] : 9 === elem.nodeType ? (doc = elem.documentElement, Math.max(elem.body["scroll" + name], doc["scroll" + name], elem.body["offset" + name], doc["offset" + name], doc["client" + name])) : void 0 === value ? // Get width or height on the element, requesting but not forcing parseFloat
jQuery.css(elem, type, extra) : // Set width or height on the element
jQuery.style(elem, type, value, extra);
}, type, chainable ? margin : void 0, chainable);
};
});
}), jQuery.each([
"ajaxStart",
"ajaxStop",
"ajaxComplete",
"ajaxError",
"ajaxSuccess",
"ajaxSend"
], function(_i, type) {
jQuery.fn[type] = function(fn) {
return this.on(type, fn);
};
}), jQuery.fn.extend({
bind: function(types, data, fn) {
return this.on(types, null, data, fn);
},
unbind: function(types, fn) {
return this.off(types, null, fn);
},
delegate: function(selector, types, data, fn) {
return this.on(types, selector, data, fn);
},
undelegate: function(selector, types, fn) {
// ( namespace ) or ( selector, types [, fn] )
return 1 == arguments.length ? this.off(selector, "**") : this.off(types, selector || "**", fn);
},
hover: function(fnOver, fnOut) {
return this.mouseenter(fnOver).mouseleave(fnOut || fnOver);
}
}), jQuery.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "), function(_i, name) {
// Handle event binding
jQuery.fn[name] = function(data, fn) {
return arguments.length > 0 ? this.on(name, null, data, fn) : this.trigger(name);
};
});
// Support: Android <=4.0 only
// Make sure we trim BOM and NBSP
var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
// Bind a function to a context, optionally partially applying any
// arguments.
// jQuery.proxy is deprecated to promote standards (specifically Function#bind)
// However, it is not slated for removal any time soon
jQuery.proxy = function(fn, context) {
var tmp, args, proxy;
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ("string" == typeof context && (tmp = fn[context], context = fn, fn = tmp), isFunction(fn)) return(// Simulated bind
args = slice.call(arguments, 2), // Set the guid of unique handler to the same of original handler, so it can be removed
(proxy = function() {
return fn.apply(context || this, args.concat(slice.call(arguments)));
}).guid = fn.guid = fn.guid || jQuery.guid++, proxy);
}, jQuery.holdReady = function(hold) {
hold ? jQuery.readyWait++ : jQuery.ready(!0);
}, jQuery.isArray = Array.isArray, jQuery.parseJSON = JSON.parse, jQuery.nodeName = nodeName, jQuery.isFunction = isFunction, jQuery.isWindow = isWindow, jQuery.camelCase = camelCase, jQuery.type = toType, jQuery.now = Date.now, jQuery.isNumeric = function(obj) {
// As of jQuery 3.0, isNumeric is limited to
// strings and numbers (primitives or objects)
// that can be coerced to finite numbers (gh-2662)
var type = jQuery.type(obj);
return ("number" === type || "string" === type) && // parseFloat NaNs numeric-cast false positives ("")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
!isNaN(obj - parseFloat(obj));
}, jQuery.trim = function(text) {
return null == text ? "" : (text + "").replace(rtrim, "");
}, "function" == typeof define && define.amd && define("jquery", [], function() {
return jQuery;
});
var // Map over jQuery in case of overwrite
_jQuery = window1.jQuery, // Map over the $ in case of overwrite
_$ = window1.$;
return jQuery.noConflict = function(deep) {
return window1.$ === jQuery && (window1.$ = _$), deep && window1.jQuery === jQuery && (window1.jQuery = _jQuery), jQuery;
}, void 0 === noGlobal && (window1.jQuery = window1.$ = jQuery), jQuery;
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/benches-full/lodash.js | JavaScript | /**
* @license
* Lodash <https://lodash.com/>
* Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/ (function() {
/** Error message constants. */ var undefined, FUNC_ERROR_TEXT = 'Expected a function', HASH_UNDEFINED = '__lodash_hash_undefined__', PLACEHOLDER = '__lodash_placeholder__', INFINITY = 1 / 0, NAN = 0 / 0, wrapFlags = [
[
'ary',
128
],
[
'bind',
1
],
[
'bindKey',
2
],
[
'curry',
8
],
[
'curryRight',
16
],
[
'flip',
512
],
[
'partial',
32
],
[
'partialRight',
64
],
[
'rearg',
256
]
], argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', promiseTag = '[object Promise]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', weakMapTag = '[object WeakMap]', arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]', reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g, reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source), reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g, reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g, reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source), reTrimStart = /^\s+/, reWhitespace = /\s/, reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /, reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g, reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/, reEscapeChar = /\\(\\)?/g, reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g, reFlags = /\w*$/, reIsBadHex = /^[-+]0x[0-9a-f]+$/i, reIsBinary = /^0b[01]+$/i, reIsHostCtor = /^\[object .+?Constructor\]$/, reIsOctal = /^0o[0-7]+$/i, reIsUint = /^(?:0|[1-9]\d*)$/, reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g, reNoMatch = /($^)/, reUnescapedString = /['\n\r\u2028\u2029\\]/g, rsAstralRange = '\\ud800-\\udfff', rsComboRange = "\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff", rsDingbatRange = '\\u2700-\\u27bf', rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', rsVarRange = '\\ufe0e\\ufe0f', rsBreakRange = "\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000", rsApos = "['\u2019]", rsBreak = '[' + rsBreakRange + ']', rsCombo = '[' + rsComboRange + ']', rsLower = '[' + rsLowerRange + ']', rsMisc = '[^' + rsAstralRange + rsBreakRange + '\\d+' + rsDingbatRange + rsLowerRange + rsUpperRange + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsUpper = '[' + rsUpperRange + ']', rsZWJ = '\\u200d', rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', reOptMod = '(?:' + rsCombo + '|' + rsFitz + ")?", rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' + rsZWJ + '(?:' + [
rsNonAstral,
rsRegional,
rsSurrPair
].join('|') + ')' + rsOptVar + reOptMod + ')*', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = '(?:' + [
'[' + rsDingbatRange + ']',
rsRegional,
rsSurrPair
].join('|') + ')' + rsSeq, rsSymbol = '(?:' + [
rsNonAstral + rsCombo + '?',
rsCombo,
rsRegional,
rsSurrPair,
'[' + rsAstralRange + ']'
].join('|') + ')', reApos = RegExp(rsApos, 'g'), reComboMark = RegExp(rsCombo, 'g'), reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'), reUnicodeWord = RegExp([
rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [
rsBreak,
rsUpper,
'$'
].join('|') + ')',
rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [
rsBreak,
rsUpper + rsMiscLower,
'$'
].join('|') + ')',
rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,
rsUpper + '+' + rsOptContrUpper,
'\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])',
'\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])',
'\\d+',
rsEmoji
].join('|'), 'g'), reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'), reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/, contextProps = [
'Array',
'Buffer',
'DataView',
'Date',
'Error',
'Float32Array',
'Float64Array',
'Function',
'Int8Array',
'Int16Array',
'Int32Array',
'Map',
'Math',
'Object',
'Promise',
'RegExp',
'Set',
'String',
'Symbol',
'TypeError',
'Uint8Array',
'Uint8ClampedArray',
'Uint16Array',
'Uint32Array',
'WeakMap',
'_',
'clearTimeout',
'isFinite',
'parseInt',
'setTimeout'
], templateCounter = -1, typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = !0, typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = !1;
/** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {};
cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = !0, cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = !1;
/** Used to escape characters for inclusion in compiled string literals. */ var stringEscapes = {
'\\': '\\',
"'": "'",
'\n': 'n',
'\r': 'r',
'\u2028': 'u2028',
'\u2029': 'u2029'
}, freeParseFloat = parseFloat, freeParseInt = parseInt, freeGlobal = 'object' == typeof global && global && global.Object === Object && global, freeSelf = 'object' == typeof self && self && self.Object === Object && self, root = freeGlobal || freeSelf || Function('return this')(), freeExports = 'object' == typeof exports && exports && !exports.nodeType && exports, freeModule = freeExports && 'object' == typeof module && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports, freeProcess = moduleExports && freeGlobal.process, nodeUtil = function() {
try {
// Use `util.types` for Node.js 10+.
var types = freeModule && freeModule.require && freeModule.require('util').types;
if (types) return types;
// Legacy `process.binding('util')` for Node.js < 10.
return freeProcess && freeProcess.binding && freeProcess.binding('util');
} catch (e) {}
}(), nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
/*--------------------------------------------------------------------------*/ /**
* A faster alternative to `Function#apply`, this function invokes `func`
* with the `this` binding of `thisArg` and the arguments of `args`.
*
* @private
* @param {Function} func The function to invoke.
* @param {*} thisArg The `this` binding of `func`.
* @param {Array} args The arguments to invoke `func` with.
* @returns {*} Returns the result of `func`.
*/ function apply(func, thisArg, args) {
switch(args.length){
case 0:
return func.call(thisArg);
case 1:
return func.call(thisArg, args[0]);
case 2:
return func.call(thisArg, args[0], args[1]);
case 3:
return func.call(thisArg, args[0], args[1], args[2]);
}
return func.apply(thisArg, args);
}
/**
* A specialized version of `baseAggregator` for arrays.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform keys.
* @param {Object} accumulator The initial aggregated object.
* @returns {Function} Returns `accumulator`.
*/ function arrayAggregator(array, setter, iteratee, accumulator) {
for(var index = -1, length = null == array ? 0 : array.length; ++index < length;){
var value = array[index];
setter(accumulator, value, iteratee(value), array);
}
return accumulator;
}
/**
* A specialized version of `_.forEach` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/ function arrayEach(array, iteratee) {
for(var index = -1, length = null == array ? 0 : array.length; ++index < length && !1 !== iteratee(array[index], index, array););
return array;
}
/**
* A specialized version of `_.every` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
*/ function arrayEvery(array, predicate) {
for(var index = -1, length = null == array ? 0 : array.length; ++index < length;)if (!predicate(array[index], index, array)) return !1;
return !0;
}
/**
* A specialized version of `_.filter` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/ function arrayFilter(array, predicate) {
for(var index = -1, length = null == array ? 0 : array.length, resIndex = 0, result = []; ++index < length;){
var value = array[index];
predicate(value, index, array) && (result[resIndex++] = value);
}
return result;
}
/**
* A specialized version of `_.includes` for arrays without support for
* specifying an index to search from.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/ function arrayIncludes(array, value) {
return !!(null == array ? 0 : array.length) && baseIndexOf(array, value, 0) > -1;
}
/**
* This function is like `arrayIncludes` except that it accepts a comparator.
*
* @private
* @param {Array} [array] The array to inspect.
* @param {*} target The value to search for.
* @param {Function} comparator The comparator invoked per element.
* @returns {boolean} Returns `true` if `target` is found, else `false`.
*/ function arrayIncludesWith(array, value, comparator) {
for(var index = -1, length = null == array ? 0 : array.length; ++index < length;)if (comparator(value, array[index])) return !0;
return !1;
}
/**
* A specialized version of `_.map` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/ function arrayMap(array, iteratee) {
for(var index = -1, length = null == array ? 0 : array.length, result = Array(length); ++index < length;)result[index] = iteratee(array[index], index, array);
return result;
}
/**
* Appends the elements of `values` to `array`.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to append.
* @returns {Array} Returns `array`.
*/ function arrayPush(array, values) {
for(var index = -1, length = values.length, offset = array.length; ++index < length;)array[offset + index] = values[index];
return array;
}
/**
* A specialized version of `_.reduce` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the first element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/ function arrayReduce(array, iteratee, accumulator, initAccum) {
var index = -1, length = null == array ? 0 : array.length;
for(initAccum && length && (accumulator = array[++index]); ++index < length;)accumulator = iteratee(accumulator, array[index], index, array);
return accumulator;
}
/**
* A specialized version of `_.reduceRight` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @param {boolean} [initAccum] Specify using the last element of `array` as
* the initial value.
* @returns {*} Returns the accumulated value.
*/ function arrayReduceRight(array, iteratee, accumulator, initAccum) {
var length = null == array ? 0 : array.length;
for(initAccum && length && (accumulator = array[--length]); length--;)accumulator = iteratee(accumulator, array[length], length, array);
return accumulator;
}
/**
* A specialized version of `_.some` for arrays without support for iteratee
* shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/ function arraySome(array, predicate) {
for(var index = -1, length = null == array ? 0 : array.length; ++index < length;)if (predicate(array[index], index, array)) return !0;
return !1;
}
/**
* Gets the size of an ASCII `string`.
*
* @private
* @param {string} string The string inspect.
* @returns {number} Returns the string size.
*/ var asciiSize = baseProperty('length');
/**
* The base implementation of methods like `_.findKey` and `_.findLastKey`,
* without support for iteratee shorthands, which iterates over `collection`
* using `eachFunc`.
*
* @private
* @param {Array|Object} collection The collection to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {Function} eachFunc The function to iterate over `collection`.
* @returns {*} Returns the found element or its key, else `undefined`.
*/ function baseFindKey(collection, predicate, eachFunc) {
var result;
return eachFunc(collection, function(value, key, collection) {
if (predicate(value, key, collection)) return result = key, !1;
}), result;
}
/**
* The base implementation of `_.findIndex` and `_.findLastIndex` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} predicate The function invoked per iteration.
* @param {number} fromIndex The index to search from.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {number} Returns the index of the matched value, else `-1`.
*/ function baseFindIndex(array, predicate, fromIndex, fromRight) {
for(var length = array.length, index = fromIndex + (fromRight ? 1 : -1); fromRight ? index-- : ++index < length;)if (predicate(array[index], index, array)) return index;
return -1;
}
/**
* The base implementation of `_.indexOf` without `fromIndex` bounds checks.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/ function baseIndexOf(array, value, fromIndex) {
return value == value ? /**
* A specialized version of `_.indexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/ function(array, value, fromIndex) {
for(var index = fromIndex - 1, length = array.length; ++index < length;)if (array[index] === value) return index;
return -1;
}(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex);
}
/**
* This function is like `baseIndexOf` except that it accepts a comparator.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @param {Function} comparator The comparator invoked per element.
* @returns {number} Returns the index of the matched value, else `-1`.
*/ function baseIndexOfWith(array, value, fromIndex, comparator) {
for(var index = fromIndex - 1, length = array.length; ++index < length;)if (comparator(array[index], value)) return index;
return -1;
}
/**
* The base implementation of `_.isNaN` without support for number objects.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
*/ function baseIsNaN(value) {
return value != value;
}
/**
* The base implementation of `_.mean` and `_.meanBy` without support for
* iteratee shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {number} Returns the mean.
*/ function baseMean(array, iteratee) {
var length = null == array ? 0 : array.length;
return length ? baseSum(array, iteratee) / length : NAN;
}
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new accessor function.
*/ function baseProperty(key) {
return function(object) {
return null == object ? undefined : object[key];
};
}
/**
* The base implementation of `_.propertyOf` without support for deep paths.
*
* @private
* @param {Object} object The object to query.
* @returns {Function} Returns the new accessor function.
*/ function basePropertyOf(object) {
return function(key) {
return null == object ? undefined : object[key];
};
}
/**
* The base implementation of `_.reduce` and `_.reduceRight`, without support
* for iteratee shorthands, which iterates over `collection` using `eachFunc`.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {*} accumulator The initial value.
* @param {boolean} initAccum Specify using the first or last element of
* `collection` as the initial value.
* @param {Function} eachFunc The function to iterate over `collection`.
* @returns {*} Returns the accumulated value.
*/ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
return eachFunc(collection, function(value, index, collection) {
accumulator = initAccum ? (initAccum = !1, value) : iteratee(accumulator, value, index, collection);
}), accumulator;
}
/**
* The base implementation of `_.sum` and `_.sumBy` without support for
* iteratee shorthands.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {number} Returns the sum.
*/ function baseSum(array, iteratee) {
for(var result, index = -1, length = array.length; ++index < length;){
var current = iteratee(array[index]);
undefined !== current && (result = undefined === result ? current : result + current);
}
return result;
}
/**
* The base implementation of `_.times` without support for iteratee shorthands
* or max array length checks.
*
* @private
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the array of results.
*/ function baseTimes(n, iteratee) {
for(var index = -1, result = Array(n); ++index < n;)result[index] = iteratee(index);
return result;
}
/**
* The base implementation of `_.trim`.
*
* @private
* @param {string} string The string to trim.
* @returns {string} Returns the trimmed string.
*/ function baseTrim(string) {
return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') : string;
}
/**
* The base implementation of `_.unary` without support for storing metadata.
*
* @private
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
*/ function baseUnary(func) {
return function(value) {
return func(value);
};
}
/**
* The base implementation of `_.values` and `_.valuesIn` which creates an
* array of `object` property values corresponding to the property names
* of `props`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} props The property names to get values for.
* @returns {Object} Returns the array of property values.
*/ function baseValues(object, props) {
return arrayMap(props, function(key) {
return object[key];
});
}
/**
* Checks if a `cache` value for `key` exists.
*
* @private
* @param {Object} cache The cache to query.
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/ function cacheHas(cache, key) {
return cache.has(key);
}
/**
* Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the first unmatched string symbol.
*/ function charsStartIndex(strSymbols, chrSymbols) {
for(var index = -1, length = strSymbols.length; ++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1;);
return index;
}
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
* that is not found in the character symbols.
*
* @private
* @param {Array} strSymbols The string symbols to inspect.
* @param {Array} chrSymbols The character symbols to find.
* @returns {number} Returns the index of the last unmatched string symbol.
*/ function charsEndIndex(strSymbols, chrSymbols) {
for(var index = strSymbols.length; index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1;);
return index;
}
/**
* Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
* letters to basic Latin letters.
*
* @private
* @param {string} letter The matched letter to deburr.
* @returns {string} Returns the deburred letter.
*/ var deburrLetter = basePropertyOf({
// Latin-1 Supplement block.
À: 'A',
Á: 'A',
Â: 'A',
Ã: 'A',
Ä: 'A',
Å: 'A',
à: 'a',
á: 'a',
â: 'a',
ã: 'a',
ä: 'a',
å: 'a',
Ç: 'C',
ç: 'c',
Ð: 'D',
ð: 'd',
È: 'E',
É: 'E',
Ê: 'E',
Ë: 'E',
è: 'e',
é: 'e',
ê: 'e',
ë: 'e',
Ì: 'I',
Í: 'I',
Î: 'I',
Ï: 'I',
ì: 'i',
í: 'i',
î: 'i',
ï: 'i',
Ñ: 'N',
ñ: 'n',
Ò: 'O',
Ó: 'O',
Ô: 'O',
Õ: 'O',
Ö: 'O',
Ø: 'O',
ò: 'o',
ó: 'o',
ô: 'o',
õ: 'o',
ö: 'o',
ø: 'o',
Ù: 'U',
Ú: 'U',
Û: 'U',
Ü: 'U',
ù: 'u',
ú: 'u',
û: 'u',
ü: 'u',
Ý: 'Y',
ý: 'y',
ÿ: 'y',
Æ: 'Ae',
æ: 'ae',
Þ: 'Th',
þ: 'th',
ß: 'ss',
// Latin Extended-A block.
Ā: 'A',
Ă: 'A',
Ą: 'A',
ā: 'a',
ă: 'a',
ą: 'a',
Ć: 'C',
Ĉ: 'C',
Ċ: 'C',
Č: 'C',
ć: 'c',
ĉ: 'c',
ċ: 'c',
č: 'c',
Ď: 'D',
Đ: 'D',
ď: 'd',
đ: 'd',
Ē: 'E',
Ĕ: 'E',
Ė: 'E',
Ę: 'E',
Ě: 'E',
ē: 'e',
ĕ: 'e',
ė: 'e',
ę: 'e',
ě: 'e',
Ĝ: 'G',
Ğ: 'G',
Ġ: 'G',
Ģ: 'G',
ĝ: 'g',
ğ: 'g',
ġ: 'g',
ģ: 'g',
Ĥ: 'H',
Ħ: 'H',
ĥ: 'h',
ħ: 'h',
Ĩ: 'I',
Ī: 'I',
Ĭ: 'I',
Į: 'I',
İ: 'I',
ĩ: 'i',
ī: 'i',
ĭ: 'i',
į: 'i',
ı: 'i',
Ĵ: 'J',
ĵ: 'j',
Ķ: 'K',
ķ: 'k',
ĸ: 'k',
Ĺ: 'L',
Ļ: 'L',
Ľ: 'L',
Ŀ: 'L',
Ł: 'L',
ĺ: 'l',
ļ: 'l',
ľ: 'l',
ŀ: 'l',
ł: 'l',
Ń: 'N',
Ņ: 'N',
Ň: 'N',
Ŋ: 'N',
ń: 'n',
ņ: 'n',
ň: 'n',
ŋ: 'n',
Ō: 'O',
Ŏ: 'O',
Ő: 'O',
ō: 'o',
ŏ: 'o',
ő: 'o',
Ŕ: 'R',
Ŗ: 'R',
Ř: 'R',
ŕ: 'r',
ŗ: 'r',
ř: 'r',
Ś: 'S',
Ŝ: 'S',
Ş: 'S',
Š: 'S',
ś: 's',
ŝ: 's',
ş: 's',
š: 's',
Ţ: 'T',
Ť: 'T',
Ŧ: 'T',
ţ: 't',
ť: 't',
ŧ: 't',
Ũ: 'U',
Ū: 'U',
Ŭ: 'U',
Ů: 'U',
Ű: 'U',
Ų: 'U',
ũ: 'u',
ū: 'u',
ŭ: 'u',
ů: 'u',
ű: 'u',
ų: 'u',
Ŵ: 'W',
ŵ: 'w',
Ŷ: 'Y',
ŷ: 'y',
Ÿ: 'Y',
Ź: 'Z',
Ż: 'Z',
Ž: 'Z',
ź: 'z',
ż: 'z',
ž: 'z',
IJ: 'IJ',
ij: 'ij',
Œ: 'Oe',
œ: 'oe',
ʼn: "'n",
ſ: 's'
}), escapeHtmlChar = basePropertyOf({
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
});
/**
* Used by `_.template` to escape characters for inclusion in compiled string literals.
*
* @private
* @param {string} chr The matched character to escape.
* @returns {string} Returns the escaped character.
*/ function escapeStringChar(chr) {
return '\\' + stringEscapes[chr];
}
/**
* Checks if `string` contains Unicode symbols.
*
* @private
* @param {string} string The string to inspect.
* @returns {boolean} Returns `true` if a symbol is found, else `false`.
*/ function hasUnicode(string) {
return reHasUnicode.test(string);
}
/**
* Converts `map` to its key-value pairs.
*
* @private
* @param {Object} map The map to convert.
* @returns {Array} Returns the key-value pairs.
*/ function mapToArray(map) {
var index = -1, result = Array(map.size);
return map.forEach(function(value, key) {
result[++index] = [
key,
value
];
}), result;
}
/**
* Creates a unary function that invokes `func` with its argument transformed.
*
* @private
* @param {Function} func The function to wrap.
* @param {Function} transform The argument transform.
* @returns {Function} Returns the new function.
*/ function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
/**
* Replaces all `placeholder` elements in `array` with an internal placeholder
* and returns an array of their indexes.
*
* @private
* @param {Array} array The array to modify.
* @param {*} placeholder The placeholder to replace.
* @returns {Array} Returns the new array of placeholder indexes.
*/ function replaceHolders(array, placeholder) {
for(var index = -1, length = array.length, resIndex = 0, result = []; ++index < length;){
var value = array[index];
(value === placeholder || value === PLACEHOLDER) && (array[index] = PLACEHOLDER, result[resIndex++] = index);
}
return result;
}
/**
* Converts `set` to an array of its values.
*
* @private
* @param {Object} set The set to convert.
* @returns {Array} Returns the values.
*/ function setToArray(set) {
var index = -1, result = Array(set.size);
return set.forEach(function(value) {
result[++index] = value;
}), result;
}
/**
* Gets the number of symbols in `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the string size.
*/ function stringSize(string) {
return hasUnicode(string) ? /**
* Gets the size of a Unicode `string`.
*
* @private
* @param {string} string The string inspect.
* @returns {number} Returns the string size.
*/ function(string) {
for(var result = reUnicode.lastIndex = 0; reUnicode.test(string);)++result;
return result;
}(string) : asciiSize(string);
}
/**
* Converts `string` to an array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the converted array.
*/ function stringToArray(string) {
return hasUnicode(string) ? string.match(reUnicode) || [] : string.split('');
}
/**
* Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
* character of `string`.
*
* @private
* @param {string} string The string to inspect.
* @returns {number} Returns the index of the last non-whitespace character.
*/ function trimmedEndIndex(string) {
for(var index = string.length; index-- && reWhitespace.test(string.charAt(index)););
return index;
}
/**
* Used by `_.unescape` to convert HTML entities to characters.
*
* @private
* @param {string} chr The matched character to unescape.
* @returns {string} Returns the unescaped character.
*/ var unescapeHtmlChar = basePropertyOf({
'&': '&',
'<': '<',
'>': '>',
'"': '"',
''': "'"
}), _ = function runInContext(context) {
/** Built-in constructor references. */ var uid, result, cache, source, Array1 = (context = null == context ? root : _.defaults(root.Object(), context, _.pick(root, contextProps))).Array, Date = context.Date, Error = context.Error, Function1 = context.Function, Math = context.Math, Object1 = context.Object, RegExp1 = context.RegExp, String = context.String, TypeError = context.TypeError, arrayProto = Array1.prototype, funcProto = Function1.prototype, objectProto = Object1.prototype, coreJsData = context['__core-js_shared__'], funcToString = funcProto.toString, hasOwnProperty = objectProto.hasOwnProperty, idCounter = 0, maskSrcKey = (uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '')) ? 'Symbol(src)_1.' + uid : '', nativeObjectToString = objectProto.toString, objectCtorString = funcToString.call(Object1), oldDash = root._, reIsNative = RegExp1('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'), Buffer = moduleExports ? context.Buffer : undefined, Symbol = context.Symbol, Uint8Array = context.Uint8Array, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, getPrototype = overArg(Object1.getPrototypeOf, Object1), objectCreate = Object1.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, symIterator = Symbol ? Symbol.iterator : undefined, symToStringTag = Symbol ? Symbol.toStringTag : undefined, defineProperty = function() {
try {
var func = getNative(Object1, 'defineProperty');
return func({}, '', {}), func;
} catch (e) {}
}(), ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date && Date.now !== root.Date.now && Date.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout, nativeCeil = Math.ceil, nativeFloor = Math.floor, nativeGetSymbols = Object1.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object1.keys, Object1), nativeMax = Math.max, nativeMin = Math.min, nativeNow = Date.now, nativeParseInt = context.parseInt, nativeRandom = Math.random, nativeReverse = arrayProto.reverse, DataView = getNative(context, 'DataView'), Map = getNative(context, 'Map'), Promise = getNative(context, 'Promise'), Set = getNative(context, 'Set'), WeakMap = getNative(context, 'WeakMap'), nativeCreate = getNative(Object1, 'create'), metaMap = WeakMap && new WeakMap, realNames = {}, dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap), symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined;
/*------------------------------------------------------------------------*/ /**
* Creates a `lodash` object which wraps `value` to enable implicit method
* chain sequences. Methods that operate on and return arrays, collections,
* and functions can be chained together. Methods that retrieve a single value
* or may return a primitive value will automatically end the chain sequence
* and return the unwrapped value. Otherwise, the value must be unwrapped
* with `_#value`.
*
* Explicit chain sequences, which must be unwrapped with `_#value`, may be
* enabled using `_.chain`.
*
* The execution of chained methods is lazy, that is, it's deferred until
* `_#value` is implicitly or explicitly called.
*
* Lazy evaluation allows several methods to support shortcut fusion.
* Shortcut fusion is an optimization to merge iteratee calls; this avoids
* the creation of intermediate arrays and can greatly reduce the number of
* iteratee executions. Sections of a chain sequence qualify for shortcut
* fusion if the section is applied to an array and iteratees accept only
* one argument. The heuristic for whether a section qualifies for shortcut
* fusion is subject to change.
*
* Chaining is supported in custom builds as long as the `_#value` method is
* directly or indirectly included in the build.
*
* In addition to lodash methods, wrappers have `Array` and `String` methods.
*
* The wrapper `Array` methods are:
* `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
*
* The wrapper `String` methods are:
* `replace` and `split`
*
* The wrapper methods that support shortcut fusion are:
* `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
* `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
* `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
*
* The chainable wrapper methods are:
* `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
* `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
* `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
* `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
* `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
* `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
* `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
* `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
* `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
* `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
* `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
* `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
* `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
* `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
* `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
* `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
* `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
* `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
* `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
* `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
* `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
* `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
* `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
* `zipObject`, `zipObjectDeep`, and `zipWith`
*
* The wrapper methods that are **not** chainable by default are:
* `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
* `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
* `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
* `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
* `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
* `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
* `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
* `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
* `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
* `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
* `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
* `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
* `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
* `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
* `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
* `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
* `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
* `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
* `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
* `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
* `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
* `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
* `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
* `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
* `upperFirst`, `value`, and `words`
*
* @name _
* @constructor
* @category Seq
* @param {*} value The value to wrap in a `lodash` instance.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var wrapped = _([1, 2, 3]);
*
* // Returns an unwrapped value.
* wrapped.reduce(_.add);
* // => 6
*
* // Returns a wrapped value.
* var squares = wrapped.map(square);
*
* _.isArray(squares);
* // => false
*
* _.isArray(squares.value());
* // => true
*/ function lodash(value) {
if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
if (value instanceof LodashWrapper) return value;
if (hasOwnProperty.call(value, '__wrapped__')) return wrapperClone(value);
}
return new LodashWrapper(value);
}
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} proto The object to inherit from.
* @returns {Object} Returns the new object.
*/ var baseCreate = function() {
function object() {}
return function(proto) {
if (!isObject(proto)) return {};
if (objectCreate) return objectCreate(proto);
object.prototype = proto;
var result = new object;
return object.prototype = undefined, result;
};
}();
/**
* The function whose prototype chain sequence wrappers inherit from.
*
* @private
*/ function baseLodash() {
// No operation performed.
}
/**
* The base constructor for creating `lodash` wrapper objects.
*
* @private
* @param {*} value The value to wrap.
* @param {boolean} [chainAll] Enable explicit method chain sequences.
*/ function LodashWrapper(value, chainAll) {
this.__wrapped__ = value, this.__actions__ = [], this.__chain__ = !!chainAll, this.__index__ = 0, this.__values__ = undefined;
}
/*------------------------------------------------------------------------*/ /**
* Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
*
* @private
* @constructor
* @param {*} value The value to wrap.
*/ function LazyWrapper(value) {
this.__wrapped__ = value, this.__actions__ = [], this.__dir__ = 1, this.__filtered__ = !1, this.__iteratees__ = [], this.__takeCount__ = 4294967295, this.__views__ = [];
}
/*------------------------------------------------------------------------*/ /**
* Creates a hash object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/ function Hash(entries) {
var index = -1, length = null == entries ? 0 : entries.length;
for(this.clear(); ++index < length;){
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/*------------------------------------------------------------------------*/ /**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/ function ListCache(entries) {
var index = -1, length = null == entries ? 0 : entries.length;
for(this.clear(); ++index < length;){
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/*------------------------------------------------------------------------*/ /**
* Creates a map cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/ function MapCache(entries) {
var index = -1, length = null == entries ? 0 : entries.length;
for(this.clear(); ++index < length;){
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
/*------------------------------------------------------------------------*/ /**
*
* Creates an array cache object to store unique values.
*
* @private
* @constructor
* @param {Array} [values] The values to cache.
*/ function SetCache(values) {
var index = -1, length = null == values ? 0 : values.length;
for(this.__data__ = new MapCache; ++index < length;)this.add(values[index]);
}
/*------------------------------------------------------------------------*/ /**
* Creates a stack cache object to store key-value pairs.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/ function Stack(entries) {
var data = this.__data__ = new ListCache(entries);
this.size = data.size;
}
/*------------------------------------------------------------------------*/ /**
* Creates an array of the enumerable property names of the array-like `value`.
*
* @private
* @param {*} value The value to query.
* @param {boolean} inherited Specify returning inherited property names.
* @returns {Array} Returns the array of property names.
*/ function arrayLikeKeys(value, inherited) {
var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length;
for(var key in value)(inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode.
('length' == key || // Node.js 0.10 has enumerable non-index properties on buffers.
isBuff && ('offset' == key || 'parent' == key) || // PhantomJS 2 has enumerable non-index properties on typed arrays.
isType && ('buffer' == key || 'byteLength' == key || 'byteOffset' == key) || // Skip index properties.
isIndex(key, length))) && result.push(key);
return result;
}
/**
* A specialized version of `_.sample` for arrays.
*
* @private
* @param {Array} array The array to sample.
* @returns {*} Returns the random element.
*/ function arraySample(array) {
var length = array.length;
return length ? array[baseRandom(0, length - 1)] : undefined;
}
/**
* This function is like `assignValue` except that it doesn't assign
* `undefined` values.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/ function assignMergeValue(object, key, value) {
(undefined === value || eq(object[key], value)) && (undefined !== value || key in object) || baseAssignValue(object, key, value);
}
/**
* Assigns `value` to `key` of `object` if the existing value is not equivalent
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/ function assignValue(object, key, value) {
var objValue = object[key];
hasOwnProperty.call(object, key) && eq(objValue, value) && (undefined !== value || key in object) || baseAssignValue(object, key, value);
}
/**
* Gets the index at which the `key` is found in `array` of key-value pairs.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} key The key to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
*/ function assocIndexOf(array, key) {
for(var length = array.length; length--;)if (eq(array[length][0], key)) return length;
return -1;
}
/**
* Aggregates elements of `collection` on `accumulator` with keys transformed
* by `iteratee` and values set by `setter`.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} setter The function to set `accumulator` values.
* @param {Function} iteratee The iteratee to transform keys.
* @param {Object} accumulator The initial aggregated object.
* @returns {Function} Returns `accumulator`.
*/ function baseAggregator(collection, setter, iteratee, accumulator) {
return baseEach(collection, function(value, key, collection) {
setter(accumulator, value, iteratee(value), collection);
}), accumulator;
}
/**
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/ function baseAssign(object, source) {
return object && copyObject(source, keys(source), object);
}
/**
* The base implementation of `assignValue` and `assignMergeValue` without
* value checks.
*
* @private
* @param {Object} object The object to modify.
* @param {string} key The key of the property to assign.
* @param {*} value The value to assign.
*/ function baseAssignValue(object, key, value) {
'__proto__' == key && defineProperty ? defineProperty(object, key, {
configurable: !0,
enumerable: !0,
value: value,
writable: !0
}) : object[key] = value;
}
/**
* The base implementation of `_.at` without support for individual paths.
*
* @private
* @param {Object} object The object to iterate over.
* @param {string[]} paths The property paths to pick.
* @returns {Array} Returns the picked elements.
*/ function baseAt(object, paths) {
for(var index = -1, length = paths.length, result = Array1(length), skip = null == object; ++index < length;)result[index] = skip ? undefined : get(object, paths[index]);
return result;
}
/**
* The base implementation of `_.clamp` which doesn't coerce arguments.
*
* @private
* @param {number} number The number to clamp.
* @param {number} [lower] The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the clamped number.
*/ function baseClamp(number, lower, upper) {
return number == number && (undefined !== upper && (number = number <= upper ? number : upper), undefined !== lower && (number = number >= lower ? number : lower)), number;
}
/**
* The base implementation of `_.clone` and `_.cloneDeep` which tracks
* traversed objects.
*
* @private
* @param {*} value The value to clone.
* @param {boolean} bitmask The bitmask flags.
* 1 - Deep clone
* 2 - Flatten inherited properties
* 4 - Clone symbols
* @param {Function} [customizer] The function to customize cloning.
* @param {string} [key] The key of `value`.
* @param {Object} [object] The parent object of `value`.
* @param {Object} [stack] Tracks traversed objects and their clone counterparts.
* @returns {*} Returns the cloned value.
*/ function baseClone(value, bitmask, customizer, key, object, stack) {
var result, isDeep = 1 & bitmask, isFlat = 2 & bitmask, isFull = 4 & bitmask;
if (customizer && (result = object ? customizer(value, key, object, stack) : customizer(value)), undefined !== result) return result;
if (!isObject(value)) return value;
var isArr = isArray(value);
if (isArr) {
if (length = value.length, result1 = new value.constructor(length), length && 'string' == typeof value[0] && hasOwnProperty.call(value, 'index') && (result1.index = value.index, result1.input = value.input), result = result1, !isDeep) return copyArray(value, result);
} else {
var length, result1, object1, object2, object3, tag = getTag(value), isFunc = tag == funcTag || tag == genTag;
if (isBuffer(value)) return cloneBuffer(value, isDeep);
if (tag == objectTag || tag == argsTag || isFunc && !object) {
if (result = isFlat || isFunc ? {} : initCloneObject(value), !isDeep) return isFlat ? (object1 = (object3 = result) && copyObject(value, keysIn(value), object3), copyObject(value, getSymbolsIn(value), object1)) : (object2 = baseAssign(result, value), copyObject(value, getSymbols(value), object2));
} else {
if (!cloneableTags[tag]) return object ? value : {};
result = /**
* Initializes an object clone based on its `toStringTag`.
*
* **Note:** This function only supports cloning values with tags of
* `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
*
* @private
* @param {Object} object The object to clone.
* @param {string} tag The `toStringTag` of the object to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the initialized clone.
*/ function(object, tag, isDeep) {
var buffer, result, Ctor = object.constructor;
switch(tag){
case arrayBufferTag:
return cloneArrayBuffer(object);
case boolTag:
case dateTag:
return new Ctor(+object);
case dataViewTag:
return buffer = isDeep ? cloneArrayBuffer(object.buffer) : object.buffer, new object.constructor(buffer, object.byteOffset, object.byteLength);
case float32Tag:
case float64Tag:
case int8Tag:
case int16Tag:
case int32Tag:
case uint8Tag:
case uint8ClampedTag:
case uint16Tag:
case uint32Tag:
return cloneTypedArray(object, isDeep);
case mapTag:
return new Ctor;
case numberTag:
case stringTag:
return new Ctor(object);
case regexpTag:
return (result = new object.constructor(object.source, reFlags.exec(object))).lastIndex = object.lastIndex, result;
case setTag:
return new Ctor;
case symbolTag:
return symbolValueOf ? Object1(symbolValueOf.call(object)) : {};
}
}(value, tag, isDeep);
}
}
// Check for circular references and return its corresponding clone.
stack || (stack = new Stack);
var stacked = stack.get(value);
if (stacked) return stacked;
stack.set(value, result), isSet(value) ? value.forEach(function(subValue) {
result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
}) : isMap(value) && value.forEach(function(subValue, key) {
result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
});
var keysFunc = isFull ? isFlat ? getAllKeysIn : getAllKeys : isFlat ? keysIn : keys, props = isArr ? undefined : keysFunc(value);
return arrayEach(props || value, function(subValue, key) {
props && (subValue = value[key = subValue]), // Recursively populate clone (susceptible to call stack limits).
assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
}), result;
}
/**
* The base implementation of `_.conformsTo` which accepts `props` to check.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property predicates to conform to.
* @returns {boolean} Returns `true` if `object` conforms, else `false`.
*/ function baseConformsTo(object, source, props) {
var length = props.length;
if (null == object) return !length;
for(object = Object1(object); length--;){
var key = props[length], predicate = source[key], value = object[key];
if (undefined === value && !(key in object) || !predicate(value)) return !1;
}
return !0;
}
/**
* The base implementation of `_.delay` and `_.defer` which accepts `args`
* to provide to `func`.
*
* @private
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @param {Array} args The arguments to provide to `func`.
* @returns {number|Object} Returns the timer id or timeout object.
*/ function baseDelay(func, wait, args) {
if ('function' != typeof func) throw new TypeError(FUNC_ERROR_TEXT);
return setTimeout(function() {
func.apply(undefined, args);
}, wait);
}
/**
* The base implementation of methods like `_.difference` without support
* for excluding multiple arrays or iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Array} values The values to exclude.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
*/ function baseDifference(array, values, iteratee, comparator) {
var index = -1, includes = arrayIncludes, isCommon = !0, length = array.length, result = [], valuesLength = values.length;
if (!length) return result;
iteratee && (values = arrayMap(values, baseUnary(iteratee))), comparator ? (includes = arrayIncludesWith, isCommon = !1) : values.length >= 200 && (includes = cacheHas, isCommon = !1, values = new SetCache(values));
outer: for(; ++index < length;){
var value = array[index], computed = null == iteratee ? value : iteratee(value);
if (value = comparator || 0 !== value ? value : 0, isCommon && computed == computed) {
for(var valuesIndex = valuesLength; valuesIndex--;)if (values[valuesIndex] === computed) continue outer;
result.push(value);
} else includes(values, computed, comparator) || result.push(value);
}
return result;
}
/**
* By default, the template delimiters used by lodash are like those in
* embedded Ruby (ERB) as well as ES2015 template strings. Change the
* following template settings to use alternative delimiters.
*
* @static
* @memberOf _
* @type {Object}
*/ lodash.templateSettings = {
/**
* Used to detect `data` property values to be HTML-escaped.
*
* @memberOf _.templateSettings
* @type {RegExp}
*/ escape: reEscape,
/**
* Used to detect code to be evaluated.
*
* @memberOf _.templateSettings
* @type {RegExp}
*/ evaluate: reEvaluate,
/**
* Used to detect `data` property values to inject.
*
* @memberOf _.templateSettings
* @type {RegExp}
*/ interpolate: reInterpolate,
/**
* Used to reference the data object in the template text.
*
* @memberOf _.templateSettings
* @type {string}
*/ variable: '',
/**
* Used to import variables into the compiled template.
*
* @memberOf _.templateSettings
* @type {Object}
*/ imports: {
/**
* A reference to the `lodash` function.
*
* @memberOf _.templateSettings.imports
* @type {Function}
*/ _: lodash
}
}, // Ensure wrappers are instances of `baseLodash`.
lodash.prototype = baseLodash.prototype, lodash.prototype.constructor = lodash, LodashWrapper.prototype = baseCreate(baseLodash.prototype), LodashWrapper.prototype.constructor = LodashWrapper, // Ensure `LazyWrapper` is an instance of `baseLodash`.
LazyWrapper.prototype = baseCreate(baseLodash.prototype), LazyWrapper.prototype.constructor = LazyWrapper, // Add methods to `Hash`.
Hash.prototype.clear = /**
* Removes all key-value entries from the hash.
*
* @private
* @name clear
* @memberOf Hash
*/ function() {
this.__data__ = nativeCreate ? nativeCreate(null) : {}, this.size = 0;
}, Hash.prototype.delete = /**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/ function(key) {
var result = this.has(key) && delete this.__data__[key];
return this.size -= +!!result, result;
}, Hash.prototype.get = /**
* Gets the hash value for `key`.
*
* @private
* @name get
* @memberOf Hash
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/ function(key) {
var data = this.__data__;
if (nativeCreate) {
var result = data[key];
return result === HASH_UNDEFINED ? undefined : result;
}
return hasOwnProperty.call(data, key) ? data[key] : undefined;
}, Hash.prototype.has = /**
* Checks if a hash value for `key` exists.
*
* @private
* @name has
* @memberOf Hash
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/ function(key) {
var data = this.__data__;
return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key);
}, Hash.prototype.set = /**
* Sets the hash `key` to `value`.
*
* @private
* @name set
* @memberOf Hash
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the hash instance.
*/ function(key, value) {
var data = this.__data__;
return this.size += +!this.has(key), data[key] = nativeCreate && undefined === value ? HASH_UNDEFINED : value, this;
}, // Add methods to `ListCache`.
ListCache.prototype.clear = /**
* Removes all key-value entries from the list cache.
*
* @private
* @name clear
* @memberOf ListCache
*/ function() {
this.__data__ = [], this.size = 0;
}, ListCache.prototype.delete = /**
* Removes `key` and its value from the list cache.
*
* @private
* @name delete
* @memberOf ListCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/ function(key) {
var data = this.__data__, index = assocIndexOf(data, key);
return !(index < 0) && (index == data.length - 1 ? data.pop() : splice.call(data, index, 1), --this.size, !0);
}, ListCache.prototype.get = /**
* Gets the list cache value for `key`.
*
* @private
* @name get
* @memberOf ListCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/ function(key) {
var data = this.__data__, index = assocIndexOf(data, key);
return index < 0 ? undefined : data[index][1];
}, ListCache.prototype.has = /**
* Checks if a list cache value for `key` exists.
*
* @private
* @name has
* @memberOf ListCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/ function(key) {
return assocIndexOf(this.__data__, key) > -1;
}, ListCache.prototype.set = /**
* Sets the list cache `key` to `value`.
*
* @private
* @name set
* @memberOf ListCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the list cache instance.
*/ function(key, value) {
var data = this.__data__, index = assocIndexOf(data, key);
return index < 0 ? (++this.size, data.push([
key,
value
])) : data[index][1] = value, this;
}, // Add methods to `MapCache`.
MapCache.prototype.clear = /**
* Removes all key-value entries from the map.
*
* @private
* @name clear
* @memberOf MapCache
*/ function() {
this.size = 0, this.__data__ = {
hash: new Hash,
map: new (Map || ListCache),
string: new Hash
};
}, MapCache.prototype.delete = /**
* Removes `key` and its value from the map.
*
* @private
* @name delete
* @memberOf MapCache
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/ function(key) {
var result = getMapData(this, key).delete(key);
return this.size -= +!!result, result;
}, MapCache.prototype.get = /**
* Gets the map value for `key`.
*
* @private
* @name get
* @memberOf MapCache
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/ function(key) {
return getMapData(this, key).get(key);
}, MapCache.prototype.has = /**
* Checks if a map value for `key` exists.
*
* @private
* @name has
* @memberOf MapCache
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/ function(key) {
return getMapData(this, key).has(key);
}, MapCache.prototype.set = /**
* Sets the map `key` to `value`.
*
* @private
* @name set
* @memberOf MapCache
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the map cache instance.
*/ function(key, value) {
var data = getMapData(this, key), size = data.size;
return data.set(key, value), this.size += +(data.size != size), this;
}, // Add methods to `SetCache`.
SetCache.prototype.add = SetCache.prototype.push = /**
* Adds `value` to the array cache.
*
* @private
* @name add
* @memberOf SetCache
* @alias push
* @param {*} value The value to cache.
* @returns {Object} Returns the cache instance.
*/ function(value) {
return this.__data__.set(value, HASH_UNDEFINED), this;
}, SetCache.prototype.has = /**
* Checks if `value` is in the array cache.
*
* @private
* @name has
* @memberOf SetCache
* @param {*} value The value to search for.
* @returns {number} Returns `true` if `value` is found, else `false`.
*/ function(value) {
return this.__data__.has(value);
}, // Add methods to `Stack`.
Stack.prototype.clear = /**
* Removes all key-value entries from the stack.
*
* @private
* @name clear
* @memberOf Stack
*/ function() {
this.__data__ = new ListCache, this.size = 0;
}, Stack.prototype.delete = /**
* Removes `key` and its value from the stack.
*
* @private
* @name delete
* @memberOf Stack
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/ function(key) {
var data = this.__data__, result = data.delete(key);
return this.size = data.size, result;
}, Stack.prototype.get = /**
* Gets the stack value for `key`.
*
* @private
* @name get
* @memberOf Stack
* @param {string} key The key of the value to get.
* @returns {*} Returns the entry value.
*/ function(key) {
return this.__data__.get(key);
}, Stack.prototype.has = /**
* Checks if a stack value for `key` exists.
*
* @private
* @name has
* @memberOf Stack
* @param {string} key The key of the entry to check.
* @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
*/ function(key) {
return this.__data__.has(key);
}, Stack.prototype.set = /**
* Sets the stack `key` to `value`.
*
* @private
* @name set
* @memberOf Stack
* @param {string} key The key of the value to set.
* @param {*} value The value to set.
* @returns {Object} Returns the stack cache instance.
*/ function(key, value) {
var data = this.__data__;
if (data instanceof ListCache) {
var pairs = data.__data__;
if (!Map || pairs.length < 199) return pairs.push([
key,
value
]), this.size = ++data.size, this;
data = this.__data__ = new MapCache(pairs);
}
return data.set(key, value), this.size = data.size, this;
};
/**
* The base implementation of `_.forEach` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
*/ var baseEach = createBaseEach(baseForOwn), baseEachRight = createBaseEach(baseForOwnRight, !0);
/**
* The base implementation of `_.every` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`
*/ function baseEvery(collection, predicate) {
var result = !0;
return baseEach(collection, function(value, index, collection) {
return result = !!predicate(value, index, collection);
}), result;
}
/**
* The base implementation of methods like `_.max` and `_.min` which accepts a
* `comparator` to determine the extremum value.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The iteratee invoked per iteration.
* @param {Function} comparator The comparator used to compare values.
* @returns {*} Returns the extremum value.
*/ function baseExtremum(array, iteratee, comparator) {
for(var index = -1, length = array.length; ++index < length;){
var value = array[index], current = iteratee(value);
if (null != current && (undefined === computed ? current == current && !isSymbol(current) : comparator(current, computed))) var computed = current, result = value;
}
return result;
}
/**
* The base implementation of `_.filter` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
*/ function baseFilter(collection, predicate) {
var result = [];
return baseEach(collection, function(value, index, collection) {
predicate(value, index, collection) && result.push(value);
}), result;
}
/**
* The base implementation of `_.flatten` with support for restricting flattening.
*
* @private
* @param {Array} array The array to flatten.
* @param {number} depth The maximum recursion depth.
* @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
* @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened array.
*/ function baseFlatten(array, depth, predicate, isStrict, result) {
var index = -1, length = array.length;
for(predicate || (predicate = isFlattenable), result || (result = []); ++index < length;){
var value = array[index];
depth > 0 && predicate(value) ? depth > 1 ? // Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value, depth - 1, predicate, isStrict, result) : arrayPush(result, value) : isStrict || (result[result.length] = value);
}
return result;
}
/**
* The base implementation of `baseForOwn` which iterates over `object`
* properties returned by `keysFunc` and invokes `iteratee` for each property.
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/ var baseFor = createBaseFor(), baseForRight = createBaseFor(!0);
/**
* The base implementation of `_.forOwn` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/ function baseForOwn(object, iteratee) {
return object && baseFor(object, iteratee, keys);
}
/**
* The base implementation of `_.forOwnRight` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/ function baseForOwnRight(object, iteratee) {
return object && baseForRight(object, iteratee, keys);
}
/**
* The base implementation of `_.functions` which creates an array of
* `object` function property names filtered from `props`.
*
* @private
* @param {Object} object The object to inspect.
* @param {Array} props The property names to filter.
* @returns {Array} Returns the function names.
*/ function baseFunctions(object, props) {
return arrayFilter(props, function(key) {
return isFunction(object[key]);
});
}
/**
* The base implementation of `_.get` without support for default values.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @returns {*} Returns the resolved value.
*/ function baseGet(object, path) {
path = castPath(path, object);
for(var index = 0, length = path.length; null != object && index < length;)object = object[toKey(path[index++])];
return index && index == length ? object : undefined;
}
/**
* The base implementation of `getAllKeys` and `getAllKeysIn` which uses
* `keysFunc` and `symbolsFunc` to get the enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Function} keysFunc The function to get the keys of `object`.
* @param {Function} symbolsFunc The function to get the symbols of `object`.
* @returns {Array} Returns the array of property names and symbols.
*/ function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
}
/**
* The base implementation of `getTag` without fallbacks for buggy environments.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the `toStringTag`.
*/ function baseGetTag(value) {
return null == value ? undefined === value ? '[object Undefined]' : '[object Null]' : symToStringTag && symToStringTag in Object1(value) ? /**
* A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
*
* @private
* @param {*} value The value to query.
* @returns {string} Returns the raw `toStringTag`.
*/ function(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
try {
value[symToStringTag] = undefined;
var unmasked = !0;
} catch (e) {}
var result = nativeObjectToString.call(value);
return unmasked && (isOwn ? value[symToStringTag] = tag : delete value[symToStringTag]), result;
}(value) : nativeObjectToString.call(value);
}
/**
* The base implementation of `_.gt` which doesn't coerce arguments.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is greater than `other`,
* else `false`.
*/ function baseGt(value, other) {
return value > other;
}
/**
* The base implementation of `_.has` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/ function baseHas(object, key) {
return null != object && hasOwnProperty.call(object, key);
}
/**
* The base implementation of `_.hasIn` without support for deep paths.
*
* @private
* @param {Object} [object] The object to query.
* @param {Array|string} key The key to check.
* @returns {boolean} Returns `true` if `key` exists, else `false`.
*/ function baseHasIn(object, key) {
return null != object && key in Object1(object);
}
/**
* The base implementation of methods like `_.intersection`, without support
* for iteratee shorthands, that accepts an array of arrays to inspect.
*
* @private
* @param {Array} arrays The arrays to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of shared values.
*/ function baseIntersection(arrays, iteratee, comparator) {
for(var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array1(othLength), maxLength = 1 / 0, result = []; othIndex--;){
var array = arrays[othIndex];
othIndex && iteratee && (array = arrayMap(array, baseUnary(iteratee))), maxLength = nativeMin(array.length, maxLength), caches[othIndex] = !comparator && (iteratee || length >= 120 && array.length >= 120) ? new SetCache(othIndex && array) : undefined;
}
array = arrays[0];
var index = -1, seen = caches[0];
outer: for(; ++index < length && result.length < maxLength;){
var value = array[index], computed = iteratee ? iteratee(value) : value;
if (value = comparator || 0 !== value ? value : 0, !(seen ? cacheHas(seen, computed) : includes(result, computed, comparator))) {
for(othIndex = othLength; --othIndex;){
var cache = caches[othIndex];
if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator))) continue outer;
}
seen && seen.push(computed), result.push(value);
}
}
return result;
}
/**
* The base implementation of `_.invoke` without support for individual
* method arguments.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path of the method to invoke.
* @param {Array} args The arguments to invoke the method with.
* @returns {*} Returns the result of the invoked method.
*/ function baseInvoke(object, path, args) {
path = castPath(path, object);
var func = null == (object = parent(object, path)) ? object : object[toKey(last(path))];
return null == func ? undefined : apply(func, object, args);
}
/**
* The base implementation of `_.isArguments`.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
*/ function baseIsArguments(value) {
return isObjectLike(value) && baseGetTag(value) == argsTag;
}
/**
* The base implementation of `_.isEqual` which supports partial comparisons
* and tracks traversed objects.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {boolean} bitmask The bitmask flags.
* 1 - Unordered comparison
* 2 - Partial comparison
* @param {Function} [customizer] The function to customize comparisons.
* @param {Object} [stack] Tracks traversed `value` and `other` objects.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
*/ function baseIsEqual(value, other, bitmask, customizer, stack) {
return value === other || (null != value && null != other && (isObjectLike(value) || isObjectLike(other)) ? /**
* A specialized version of `baseIsEqual` for arrays and objects which performs
* deep comparisons and tracks traversed objects enabling objects with circular
* references to be compared.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} [stack] Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/ function(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other);
objTag = objTag == argsTag ? objectTag : objTag, othTag = othTag == argsTag ? objectTag : othTag;
var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag;
if (isSameTag && isBuffer(object)) {
if (!isBuffer(other)) return !1;
objIsArr = !0, objIsObj = !1;
}
if (isSameTag && !objIsObj) return stack || (stack = new Stack), objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : /**
* A specialized version of `baseIsEqualDeep` for comparing objects of
* the same `toStringTag`.
*
* **Note:** This function only supports comparing values with tags of
* `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {string} tag The `toStringTag` of the objects to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/ function(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch(tag){
case dataViewTag:
if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) break;
object = object.buffer, other = other.buffer;
case arrayBufferTag:
if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array(object), new Uint8Array(other))) break;
return !0;
case boolTag:
case dateTag:
case numberTag:
// Coerce booleans to `1` or `0` and dates to milliseconds.
// Invalid dates are coerced to `NaN`.
return eq(+object, +other);
case errorTag:
return object.name == other.name && object.message == other.message;
case regexpTag:
case stringTag:
// Coerce regexes to strings and treat strings, primitives and objects,
// as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
// for more details.
return object == other + '';
case mapTag:
var convert = mapToArray;
case setTag:
var isPartial = 1 & bitmask;
if (convert || (convert = setToArray), object.size != other.size && !isPartial) break;
// Assume cyclic values are equal.
var stacked = stack.get(object);
if (stacked) return stacked == other;
bitmask |= 2, // Recursively compare objects (susceptible to call stack limits).
stack.set(object, other);
var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
return stack.delete(object), result;
case symbolTag:
if (symbolValueOf) return symbolValueOf.call(object) == symbolValueOf.call(other);
}
return !1;
}(object, other, objTag, bitmask, customizer, equalFunc, stack);
if (!(1 & bitmask)) {
var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other;
return stack || (stack = new Stack), equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
return !!isSameTag && (stack || (stack = new Stack), /**
* A specialized version of `baseIsEqualDeep` for objects with support for
* partial deep comparisons.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `object` and `other` objects.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/ function(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = 1 & bitmask, objProps = getAllKeys(object), objLength = objProps.length;
if (objLength != getAllKeys(other).length && !isPartial) return !1;
for(var index = objLength; index--;){
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) return !1;
}
// Check that cyclic values are equal.
var objStacked = stack.get(object), othStacked = stack.get(other);
if (objStacked && othStacked) return objStacked == other && othStacked == object;
var result = !0;
stack.set(object, other), stack.set(other, object);
for(var skipCtor = isPartial; ++index < objLength;){
var objValue = object[key = objProps[index]], othValue = other[key];
if (customizer) var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
// Recursively compare objects (susceptible to call stack limits).
if (!(undefined === compared ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
result = !1;
break;
}
skipCtor || (skipCtor = 'constructor' == key);
}
if (result && !skipCtor) {
var objCtor = object.constructor, othCtor = other.constructor;
// Non `Object` object instances with different constructors are not equal.
objCtor != othCtor && 'constructor' in object && 'constructor' in other && !('function' == typeof objCtor && objCtor instanceof objCtor && 'function' == typeof othCtor && othCtor instanceof othCtor) && (result = !1);
}
return stack.delete(object), stack.delete(other), result;
}(object, other, bitmask, customizer, equalFunc, stack));
}(value, other, bitmask, customizer, baseIsEqual, stack) : value != value && other != other);
}
/**
* The base implementation of `_.isMatch` without support for iteratee shorthands.
*
* @private
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Array} matchData The property names, values, and compare flags to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
*/ function baseIsMatch(object, source, matchData, customizer) {
var index = matchData.length, length = index, noCustomizer = !customizer;
if (null == object) return !length;
for(object = Object1(object); index--;){
var data = matchData[index];
if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) return !1;
}
for(; ++index < length;){
var key = (data = matchData[index])[0], objValue = object[key], srcValue = data[1];
if (noCustomizer && data[2]) {
if (undefined === objValue && !(key in object)) return !1;
} else {
var stack = new Stack;
if (customizer) var result = customizer(objValue, srcValue, key, object, source, stack);
if (!(undefined === result ? baseIsEqual(srcValue, objValue, 3, customizer, stack) : result)) return !1;
}
}
return !0;
}
/**
* The base implementation of `_.isNative` without bad shim checks.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
*/ function baseIsNative(value) {
return !(!isObject(value) || maskSrcKey && maskSrcKey in value) && (isFunction(value) ? reIsNative : reIsHostCtor).test(toSource(value));
}
/**
* The base implementation of `_.iteratee`.
*
* @private
* @param {*} [value=_.identity] The value to convert to an iteratee.
* @returns {Function} Returns the iteratee.
*/ function baseIteratee(value) {
return(// Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
// See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
'function' == typeof value ? value : null == value ? identity : 'object' == typeof value ? isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value) : property(value));
}
/**
* The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/ function baseKeys(object) {
if (!isPrototype(object)) return nativeKeys(object);
var result = [];
for(var key in Object1(object))hasOwnProperty.call(object, key) && 'constructor' != key && result.push(key);
return result;
}
/**
* The base implementation of `_.lt` which doesn't coerce arguments.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is less than `other`,
* else `false`.
*/ function baseLt(value, other) {
return value < other;
}
/**
* The base implementation of `_.map` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
*/ function baseMap(collection, iteratee) {
var index = -1, result = isArrayLike(collection) ? Array1(collection.length) : [];
return baseEach(collection, function(value, key, collection) {
result[++index] = iteratee(value, key, collection);
}), result;
}
/**
* The base implementation of `_.matches` which doesn't clone `source`.
*
* @private
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
*/ function baseMatches(source) {
var matchData = getMatchData(source);
return 1 == matchData.length && matchData[0][2] ? matchesStrictComparable(matchData[0][0], matchData[0][1]) : function(object) {
return object === source || baseIsMatch(object, source, matchData);
};
}
/**
* The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
*
* @private
* @param {string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/ function baseMatchesProperty(path, srcValue) {
var value;
return isKey(path) && (value = srcValue) == value && !isObject(value) ? matchesStrictComparable(toKey(path), srcValue) : function(object) {
var objValue = get(object, path);
return undefined === objValue && objValue === srcValue ? hasIn(object, path) : baseIsEqual(srcValue, objValue, 3);
};
}
/**
* The base implementation of `_.merge` without support for multiple sources.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {number} srcIndex The index of `source`.
* @param {Function} [customizer] The function to customize merged values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/ function baseMerge(object, source, srcIndex, customizer, stack) {
object !== source && baseFor(source, function(srcValue, key) {
if (stack || (stack = new Stack), isObject(srcValue)) !/**
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {number} srcIndex The index of `source`.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize assigned values.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
*/ function(object, source, key, srcIndex, mergeFunc, customizer, stack) {
var objValue = safeGet(object, key), srcValue = safeGet(source, key), stacked = stack.get(srcValue);
if (stacked) {
assignMergeValue(object, key, stacked);
return;
}
var newValue = customizer ? customizer(objValue, srcValue, key + '', object, source, stack) : undefined, isCommon = undefined === newValue;
if (isCommon) {
var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue);
newValue = srcValue, isArr || isBuff || isTyped ? isArray(objValue) ? newValue = objValue : isArrayLikeObject(objValue) ? newValue = copyArray(objValue) : isBuff ? (isCommon = !1, newValue = cloneBuffer(srcValue, !0)) : isTyped ? (isCommon = !1, newValue = cloneTypedArray(srcValue, !0)) : newValue = [] : isPlainObject(srcValue) || isArguments(srcValue) ? (newValue = objValue, isArguments(objValue) ? newValue = toPlainObject(objValue) : (!isObject(objValue) || isFunction(objValue)) && (newValue = initCloneObject(srcValue))) : isCommon = !1;
}
isCommon && (// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, newValue), mergeFunc(newValue, srcValue, srcIndex, customizer, stack), stack.delete(srcValue)), assignMergeValue(object, key, newValue);
}(object, source, key, srcIndex, baseMerge, customizer, stack);
else {
var newValue = customizer ? customizer(safeGet(object, key), srcValue, key + '', object, source, stack) : undefined;
undefined === newValue && (newValue = srcValue), assignMergeValue(object, key, newValue);
}
}, keysIn);
}
/**
* The base implementation of `_.nth` which doesn't coerce arguments.
*
* @private
* @param {Array} array The array to query.
* @param {number} n The index of the element to return.
* @returns {*} Returns the nth element of `array`.
*/ function baseNth(array, n) {
var length = array.length;
if (length) return isIndex(n += n < 0 ? length : 0, length) ? array[n] : undefined;
}
/**
* The base implementation of `_.orderBy` without param guards.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
* @param {string[]} orders The sort orders of `iteratees`.
* @returns {Array} Returns the new sorted array.
*/ function baseOrderBy(collection, iteratees, orders) {
iteratees = iteratees.length ? arrayMap(iteratees, function(iteratee) {
return isArray(iteratee) ? function(value) {
return baseGet(value, 1 === iteratee.length ? iteratee[0] : iteratee);
} : iteratee;
}) : [
identity
];
var index = -1;
return iteratees = arrayMap(iteratees, baseUnary(getIteratee())), /**
* The base implementation of `_.sortBy` which uses `comparer` to define the
* sort order of `array` and replaces criteria objects with their corresponding
* values.
*
* @private
* @param {Array} array The array to sort.
* @param {Function} comparer The function to define sort order.
* @returns {Array} Returns `array`.
*/ function(array, comparer) {
var length = array.length;
for(array.sort(comparer); length--;)array[length] = array[length].value;
return array;
}(baseMap(collection, function(value, key, collection) {
return {
criteria: arrayMap(iteratees, function(iteratee) {
return iteratee(value);
}),
index: ++index,
value: value
};
}), function(object, other) {
return(/**
* Used by `_.orderBy` to compare multiple properties of a value to another
* and stable sort them.
*
* If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
* specify an order of "desc" for descending or "asc" for ascending sort order
* of corresponding values.
*
* @private
* @param {Object} object The object to compare.
* @param {Object} other The other object to compare.
* @param {boolean[]|string[]} orders The order to sort by for each property.
* @returns {number} Returns the sort order indicator for `object`.
*/ function(object, other, orders) {
for(var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; ++index < length;){
var result = compareAscending(objCriteria[index], othCriteria[index]);
if (result) {
if (index >= ordersLength) return result;
return result * ('desc' == orders[index] ? -1 : 1);
}
}
// Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
// that causes it, under certain circumstances, to provide the same value for
// `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
// for more details.
//
// This also ensures a stable sort in V8 and other engines.
// See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
return object.index - other.index;
}(object, other, orders));
});
}
/**
* The base implementation of `_.pickBy` without support for iteratee shorthands.
*
* @private
* @param {Object} object The source object.
* @param {string[]} paths The property paths to pick.
* @param {Function} predicate The function invoked per property.
* @returns {Object} Returns the new object.
*/ function basePickBy(object, paths, predicate) {
for(var index = -1, length = paths.length, result = {}; ++index < length;){
var path = paths[index], value = baseGet(object, path);
predicate(value, path) && baseSet(result, castPath(path, object), value);
}
return result;
}
/**
* The base implementation of `_.pullAllBy` without support for iteratee
* shorthands.
*
* @private
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns `array`.
*/ function basePullAll(array, values, iteratee, comparator) {
var indexOf = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values.length, seen = array;
for(array === values && (values = copyArray(values)), iteratee && (seen = arrayMap(array, baseUnary(iteratee))); ++index < length;)for(var fromIndex = 0, value = values[index], computed = iteratee ? iteratee(value) : value; (fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1;)seen !== array && splice.call(seen, fromIndex, 1), splice.call(array, fromIndex, 1);
return array;
}
/**
* The base implementation of `_.pullAt` without support for individual
* indexes or capturing the removed elements.
*
* @private
* @param {Array} array The array to modify.
* @param {number[]} indexes The indexes of elements to remove.
* @returns {Array} Returns `array`.
*/ function basePullAt(array, indexes) {
for(var length = array ? indexes.length : 0, lastIndex = length - 1; length--;){
var index = indexes[length];
if (length == lastIndex || index !== previous) {
var previous = index;
isIndex(index) ? splice.call(array, index, 1) : baseUnset(array, index);
}
}
return array;
}
/**
* The base implementation of `_.random` without support for returning
* floating-point numbers.
*
* @private
* @param {number} lower The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the random number.
*/ function baseRandom(lower, upper) {
return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
}
/**
* The base implementation of `_.repeat` which doesn't coerce arguments.
*
* @private
* @param {string} string The string to repeat.
* @param {number} n The number of times to repeat the string.
* @returns {string} Returns the repeated string.
*/ function baseRepeat(string, n) {
var result = '';
if (!string || n < 1 || n > 9007199254740991) return result;
// Leverage the exponentiation by squaring algorithm for a faster repeat.
// See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
do n % 2 && (result += string), (n = nativeFloor(n / 2)) && (string += string);
while (n)
return result;
}
/**
* The base implementation of `_.rest` which doesn't validate or coerce arguments.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
*/ function baseRest(func, start) {
return setToString(overRest(func, start, identity), func + '');
}
/**
* The base implementation of `_.set`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @param {Function} [customizer] The function to customize path creation.
* @returns {Object} Returns `object`.
*/ function baseSet(object, path, value, customizer) {
if (!isObject(object)) return object;
path = castPath(path, object);
for(var index = -1, length = path.length, lastIndex = length - 1, nested = object; null != nested && ++index < length;){
var key = toKey(path[index]), newValue = value;
if ('__proto__' === key || 'constructor' === key || 'prototype' === key) break;
if (index != lastIndex) {
var objValue = nested[key];
newValue = customizer ? customizer(objValue, key, nested) : undefined, undefined === newValue && (newValue = isObject(objValue) ? objValue : isIndex(path[index + 1]) ? [] : {});
}
assignValue(nested, key, newValue), nested = nested[key];
}
return object;
}
/**
* The base implementation of `setData` without support for hot loop shorting.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/ var baseSetData = metaMap ? function(func, data) {
return metaMap.set(func, data), func;
} : identity, baseSetToString = defineProperty ? function(func, string) {
return defineProperty(func, 'toString', {
configurable: !0,
enumerable: !1,
value: constant(string),
writable: !0
});
} : identity;
/**
* The base implementation of `_.slice` without an iteratee call guard.
*
* @private
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/ function baseSlice(array, start, end) {
var index = -1, length = array.length;
start < 0 && (start = -start > length ? 0 : length + start), (end = end > length ? length : end) < 0 && (end += length), length = start > end ? 0 : end - start >>> 0, start >>>= 0;
for(var result = Array1(length); ++index < length;)result[index] = array[index + start];
return result;
}
/**
* The base implementation of `_.some` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} predicate The function invoked per iteration.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
*/ function baseSome(collection, predicate) {
var result;
return baseEach(collection, function(value, index, collection) {
return !(result = predicate(value, index, collection));
}), !!result;
}
/**
* The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which
* performs a binary search of `array` to determine the index at which `value`
* should be inserted into `array` in order to maintain its sort order.
*
* @private
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {boolean} [retHighest] Specify returning the highest qualified index.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
*/ function baseSortedIndex(array, value, retHighest) {
var low = 0, high = null == array ? low : array.length;
if ('number' == typeof value && value == value && high <= 2147483647) {
for(; low < high;){
var mid = low + high >>> 1, computed = array[mid];
null !== computed && !isSymbol(computed) && (retHighest ? computed <= value : computed < value) ? low = mid + 1 : high = mid;
}
return high;
}
return baseSortedIndexBy(array, value, identity, retHighest);
}
/**
* The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`
* which invokes `iteratee` for `value` and each element of `array` to compute
* their sort ranking. The iteratee is invoked with one argument; (value).
*
* @private
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function} iteratee The iteratee invoked per element.
* @param {boolean} [retHighest] Specify returning the highest qualified index.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
*/ function baseSortedIndexBy(array, value, iteratee, retHighest) {
var low = 0, high = null == array ? 0 : array.length;
if (0 === high) return 0;
for(var valIsNaN = (value = iteratee(value)) != value, valIsNull = null === value, valIsSymbol = isSymbol(value), valIsUndefined = undefined === value; low < high;){
var mid = nativeFloor((low + high) / 2), computed = iteratee(array[mid]), othIsDefined = undefined !== computed, othIsNull = null === computed, othIsReflexive = computed == computed, othIsSymbol = isSymbol(computed);
if (valIsNaN) var setLow = retHighest || othIsReflexive;
else setLow = valIsUndefined ? othIsReflexive && (retHighest || othIsDefined) : valIsNull ? othIsReflexive && othIsDefined && (retHighest || !othIsNull) : valIsSymbol ? othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol) : !othIsNull && !othIsSymbol && (retHighest ? computed <= value : computed < value);
setLow ? low = mid + 1 : high = mid;
}
return nativeMin(high, 4294967294);
}
/**
* The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without
* support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @returns {Array} Returns the new duplicate free array.
*/ function baseSortedUniq(array, iteratee) {
for(var index = -1, length = array.length, resIndex = 0, result = []; ++index < length;){
var value = array[index], computed = iteratee ? iteratee(value) : value;
if (!index || !eq(computed, seen)) {
var seen = computed;
result[resIndex++] = 0 === value ? 0 : value;
}
}
return result;
}
/**
* The base implementation of `_.toNumber` which doesn't ensure correct
* conversions of binary, hexadecimal, or octal string values.
*
* @private
* @param {*} value The value to process.
* @returns {number} Returns the number.
*/ function baseToNumber(value) {
return 'number' == typeof value ? value : isSymbol(value) ? NAN : +value;
}
/**
* The base implementation of `_.toString` which doesn't convert nullish
* values to empty strings.
*
* @private
* @param {*} value The value to process.
* @returns {string} Returns the string.
*/ function baseToString(value) {
// Exit early for strings to avoid a performance hit in some environments.
if ('string' == typeof value) return value;
if (isArray(value)) // Recursively convert values (susceptible to call stack limits).
return arrayMap(value, baseToString) + '';
if (isSymbol(value)) return symbolToString ? symbolToString.call(value) : '';
var result = value + '';
return '0' == result && 1 / value == -INFINITY ? '-0' : result;
}
/**
* The base implementation of `_.uniqBy` without support for iteratee shorthands.
*
* @private
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new duplicate free array.
*/ function baseUniq(array, iteratee, comparator) {
var index = -1, includes = arrayIncludes, length = array.length, isCommon = !0, result = [], seen = result;
if (comparator) isCommon = !1, includes = arrayIncludesWith;
else if (length >= 200) {
var set = iteratee ? null : createSet(array);
if (set) return setToArray(set);
isCommon = !1, includes = cacheHas, seen = new SetCache;
} else seen = iteratee ? [] : result;
outer: for(; ++index < length;){
var value = array[index], computed = iteratee ? iteratee(value) : value;
if (value = comparator || 0 !== value ? value : 0, isCommon && computed == computed) {
for(var seenIndex = seen.length; seenIndex--;)if (seen[seenIndex] === computed) continue outer;
iteratee && seen.push(computed), result.push(value);
} else includes(seen, computed, comparator) || (seen !== result && seen.push(computed), result.push(value));
}
return result;
}
/**
* The base implementation of `_.unset`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The property path to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
*/ function baseUnset(object, path) {
return path = castPath(path, object), null == (object = parent(object, path)) || delete object[toKey(last(path))];
}
/**
* The base implementation of `_.update`.
*
* @private
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to update.
* @param {Function} updater The function to produce the updated value.
* @param {Function} [customizer] The function to customize path creation.
* @returns {Object} Returns `object`.
*/ function baseUpdate(object, path, updater, customizer) {
return baseSet(object, path, updater(baseGet(object, path)), customizer);
}
/**
* The base implementation of methods like `_.dropWhile` and `_.takeWhile`
* without support for iteratee shorthands.
*
* @private
* @param {Array} array The array to query.
* @param {Function} predicate The function invoked per iteration.
* @param {boolean} [isDrop] Specify dropping elements instead of taking them.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Array} Returns the slice of `array`.
*/ function baseWhile(array, predicate, isDrop, fromRight) {
for(var length = array.length, index = fromRight ? length : -1; (fromRight ? index-- : ++index < length) && predicate(array[index], index, array););
return isDrop ? baseSlice(array, fromRight ? 0 : index, fromRight ? index + 1 : length) : baseSlice(array, fromRight ? index + 1 : 0, fromRight ? length : index);
}
/**
* The base implementation of `wrapperValue` which returns the result of
* performing a sequence of actions on the unwrapped `value`, where each
* successive action is supplied the return value of the previous.
*
* @private
* @param {*} value The unwrapped value.
* @param {Array} actions Actions to perform to resolve the unwrapped value.
* @returns {*} Returns the resolved value.
*/ function baseWrapperValue(value, actions) {
var result = value;
return result instanceof LazyWrapper && (result = result.value()), arrayReduce(actions, function(result, action) {
return action.func.apply(action.thisArg, arrayPush([
result
], action.args));
}, result);
}
/**
* The base implementation of methods like `_.xor`, without support for
* iteratee shorthands, that accepts an array of arrays to inspect.
*
* @private
* @param {Array} arrays The arrays to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of values.
*/ function baseXor(arrays, iteratee, comparator) {
var length = arrays.length;
if (length < 2) return length ? baseUniq(arrays[0]) : [];
for(var index = -1, result = Array1(length); ++index < length;)for(var array = arrays[index], othIndex = -1; ++othIndex < length;)othIndex != index && (result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator));
return baseUniq(baseFlatten(result, 1), iteratee, comparator);
}
/**
* This base implementation of `_.zipObject` which assigns values using `assignFunc`.
*
* @private
* @param {Array} props The property identifiers.
* @param {Array} values The property values.
* @param {Function} assignFunc The function to assign values.
* @returns {Object} Returns the new object.
*/ function baseZipObject(props, values, assignFunc) {
for(var index = -1, length = props.length, valsLength = values.length, result = {}; ++index < length;){
var value = index < valsLength ? values[index] : undefined;
assignFunc(result, props[index], value);
}
return result;
}
/**
* Casts `value` to an empty array if it's not an array like object.
*
* @private
* @param {*} value The value to inspect.
* @returns {Array|Object} Returns the cast array-like object.
*/ function castArrayLikeObject(value) {
return isArrayLikeObject(value) ? value : [];
}
/**
* Casts `value` to `identity` if it's not a function.
*
* @private
* @param {*} value The value to inspect.
* @returns {Function} Returns cast function.
*/ function castFunction(value) {
return 'function' == typeof value ? value : identity;
}
/**
* Casts `value` to a path array if it's not one.
*
* @private
* @param {*} value The value to inspect.
* @param {Object} [object] The object to query keys on.
* @returns {Array} Returns the cast property path array.
*/ function castPath(value, object) {
return isArray(value) ? value : isKey(value, object) ? [
value
] : stringToPath(toString(value));
}
/**
* Casts `array` to a slice if it's needed.
*
* @private
* @param {Array} array The array to inspect.
* @param {number} start The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the cast slice.
*/ function castSlice(array, start, end) {
var length = array.length;
return end = undefined === end ? length : end, !start && end >= length ? array : baseSlice(array, start, end);
}
/**
* A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout).
*
* @private
* @param {number|Object} id The timer id or timeout object of the timer to clear.
*/ var clearTimeout = ctxClearTimeout || function(id) {
return root.clearTimeout(id);
};
/**
* Creates a clone of `buffer`.
*
* @private
* @param {Buffer} buffer The buffer to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Buffer} Returns the cloned buffer.
*/ function cloneBuffer(buffer, isDeep) {
if (isDeep) return buffer.slice();
var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
return buffer.copy(result), result;
}
/**
* Creates a clone of `arrayBuffer`.
*
* @private
* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/ function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
return new Uint8Array(result).set(new Uint8Array(arrayBuffer)), result;
}
/**
* Creates a clone of `typedArray`.
*
* @private
* @param {Object} typedArray The typed array to clone.
* @param {boolean} [isDeep] Specify a deep clone.
* @returns {Object} Returns the cloned typed array.
*/ function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
/**
* Compares values to sort them in ascending order.
*
* @private
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {number} Returns the sort order indicator for `value`.
*/ function compareAscending(value, other) {
if (value !== other) {
var valIsDefined = undefined !== value, valIsNull = null === value, valIsReflexive = value == value, valIsSymbol = isSymbol(value), othIsDefined = undefined !== other, othIsNull = null === other, othIsReflexive = other == other, othIsSymbol = isSymbol(other);
if (!othIsNull && !othIsSymbol && !valIsSymbol && value > other || valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol || valIsNull && othIsDefined && othIsReflexive || !valIsDefined && othIsReflexive || !valIsReflexive) return 1;
if (!valIsNull && !valIsSymbol && !othIsSymbol && value < other || othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol || othIsNull && valIsDefined && valIsReflexive || !othIsDefined && valIsReflexive || !othIsReflexive) return -1;
}
return 0;
}
/**
* Creates an array that is the composition of partially applied arguments,
* placeholders, and provided arguments into a single array of arguments.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to prepend to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/ function composeArgs(args, partials, holders, isCurried) {
for(var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array1(leftLength + rangeLength), isUncurried = !isCurried; ++leftIndex < leftLength;)result[leftIndex] = partials[leftIndex];
for(; ++argsIndex < holdersLength;)(isUncurried || argsIndex < argsLength) && (result[holders[argsIndex]] = args[argsIndex]);
for(; rangeLength--;)result[leftIndex++] = args[argsIndex++];
return result;
}
/**
* This function is like `composeArgs` except that the arguments composition
* is tailored for `_.partialRight`.
*
* @private
* @param {Array} args The provided arguments.
* @param {Array} partials The arguments to append to those provided.
* @param {Array} holders The `partials` placeholder indexes.
* @params {boolean} [isCurried] Specify composing for a curried function.
* @returns {Array} Returns the new array of composed arguments.
*/ function composeArgsRight(args, partials, holders, isCurried) {
for(var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array1(rangeLength + rightLength), isUncurried = !isCurried; ++argsIndex < rangeLength;)result[argsIndex] = args[argsIndex];
for(var offset = argsIndex; ++rightIndex < rightLength;)result[offset + rightIndex] = partials[rightIndex];
for(; ++holdersIndex < holdersLength;)(isUncurried || argsIndex < argsLength) && (result[offset + holders[holdersIndex]] = args[argsIndex++]);
return result;
}
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/ function copyArray(source, array) {
var index = -1, length = source.length;
for(array || (array = Array1(length)); ++index < length;)array[index] = source[index];
return array;
}
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property identifiers to copy.
* @param {Object} [object={}] The object to copy properties to.
* @param {Function} [customizer] The function to customize copied values.
* @returns {Object} Returns `object`.
*/ function copyObject(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
for(var index = -1, length = props.length; ++index < length;){
var key = props[index], newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined;
undefined === newValue && (newValue = source[key]), isNew ? baseAssignValue(object, key, newValue) : assignValue(object, key, newValue);
}
return object;
}
/**
* Creates a function like `_.groupBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} [initializer] The accumulator object initializer.
* @returns {Function} Returns the new aggregator function.
*/ function createAggregator(setter, initializer) {
return function(collection, iteratee) {
var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {};
return func(collection, setter, getIteratee(iteratee, 2), accumulator);
};
}
/**
* Creates a function like `_.assign`.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/ function createAssigner(assigner) {
return baseRest(function(object, sources) {
var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined;
for(customizer = assigner.length > 3 && 'function' == typeof customizer ? (length--, customizer) : undefined, guard && isIterateeCall(sources[0], sources[1], guard) && (customizer = length < 3 ? undefined : customizer, length = 1), object = Object1(object); ++index < length;){
var source = sources[index];
source && assigner(object, source, index, customizer);
}
return object;
});
}
/**
* Creates a `baseEach` or `baseEachRight` function.
*
* @private
* @param {Function} eachFunc The function to iterate over a collection.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/ function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
if (null == collection) return collection;
if (!isArrayLike(collection)) return eachFunc(collection, iteratee);
for(var length = collection.length, index = fromRight ? length : -1, iterable = Object1(collection); (fromRight ? index-- : ++index < length) && !1 !== iteratee(iterable[index], index, iterable););
return collection;
};
}
/**
* Creates a base function for methods like `_.forIn` and `_.forOwn`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/ function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
for(var index = -1, iterable = Object1(object), props = keysFunc(object), length = props.length; length--;){
var key = props[fromRight ? length : ++index];
if (!1 === iteratee(iterable[key], key, iterable)) break;
}
return object;
};
}
/**
* Creates a function like `_.lowerFirst`.
*
* @private
* @param {string} methodName The name of the `String` case method to use.
* @returns {Function} Returns the new case function.
*/ function createCaseFirst(methodName) {
return function(string) {
var strSymbols = hasUnicode(string = toString(string)) ? stringToArray(string) : undefined, chr = strSymbols ? strSymbols[0] : string.charAt(0), trailing = strSymbols ? castSlice(strSymbols, 1).join('') : string.slice(1);
return chr[methodName]() + trailing;
};
}
/**
* Creates a function like `_.camelCase`.
*
* @private
* @param {Function} callback The function to combine each word.
* @returns {Function} Returns the new compounder function.
*/ function createCompounder(callback) {
return function(string) {
return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
};
}
/**
* Creates a function that produces an instance of `Ctor` regardless of
* whether it was invoked as part of a `new` expression or by `call` or `apply`.
*
* @private
* @param {Function} Ctor The constructor to wrap.
* @returns {Function} Returns the new wrapped function.
*/ function createCtor(Ctor) {
return function() {
// Use a `switch` statement to work with class constructors. See
// http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
// for more details.
var args = arguments;
switch(args.length){
case 0:
return new Ctor;
case 1:
return new Ctor(args[0]);
case 2:
return new Ctor(args[0], args[1]);
case 3:
return new Ctor(args[0], args[1], args[2]);
case 4:
return new Ctor(args[0], args[1], args[2], args[3]);
case 5:
return new Ctor(args[0], args[1], args[2], args[3], args[4]);
case 6:
return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
case 7:
return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
}
var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args);
// Mimic the constructor's `return` behavior.
// See https://es5.github.io/#x13.2.2 for more details.
return isObject(result) ? result : thisBinding;
};
}
/**
* Creates a `_.find` or `_.findLast` function.
*
* @private
* @param {Function} findIndexFunc The function to find the collection index.
* @returns {Function} Returns the new find function.
*/ function createFind(findIndexFunc) {
return function(collection, predicate, fromIndex) {
var iterable = Object1(collection);
if (!isArrayLike(collection)) {
var iteratee = getIteratee(predicate, 3);
collection = keys(collection), predicate = function(key) {
return iteratee(iterable[key], key, iterable);
};
}
var index = findIndexFunc(collection, predicate, fromIndex);
return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
};
}
/**
* Creates a `_.flow` or `_.flowRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new flow function.
*/ function createFlow(fromRight) {
return flatRest(function(funcs) {
var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru;
for(fromRight && funcs.reverse(); index--;){
var func = funcs[index];
if ('function' != typeof func) throw new TypeError(FUNC_ERROR_TEXT);
if (prereq && !wrapper && 'wrapper' == getFuncName(func)) var wrapper = new LodashWrapper([], !0);
}
for(index = wrapper ? index : length; ++index < length;){
var funcName = getFuncName(func = funcs[index]), data = 'wrapper' == funcName ? getData(func) : undefined;
wrapper = data && isLaziable(data[0]) && 424 == data[1] && !data[4].length && 1 == data[9] ? wrapper[getFuncName(data[0])].apply(wrapper, data[3]) : 1 == func.length && isLaziable(func) ? wrapper[funcName]() : wrapper.thru(func);
}
return function() {
var args = arguments, value = args[0];
if (wrapper && 1 == args.length && isArray(value)) return wrapper.plant(value).value();
for(var index = 0, result = length ? funcs[index].apply(this, args) : value; ++index < length;)result = funcs[index].call(this, result);
return result;
};
});
}
/**
* Creates a function that wraps `func` to invoke it with optional `this`
* binding of `thisArg`, partial application, and currying.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [partialsRight] The arguments to append to those provided
* to the new function.
* @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
var isAry = 128 & bitmask, isBind = 1 & bitmask, isBindKey = 2 & bitmask, isCurried = 24 & bitmask, isFlip = 512 & bitmask, Ctor = isBindKey ? undefined : createCtor(func);
function wrapper() {
for(var length = arguments.length, args = Array1(length), index = length; index--;)args[index] = arguments[index];
if (isCurried) var placeholder = getHolder(wrapper), holdersCount = /**
* Gets the number of `placeholder` occurrences in `array`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} placeholder The placeholder to search for.
* @returns {number} Returns the placeholder count.
*/ function(array, placeholder) {
for(var length = array.length, result = 0; length--;)array[length] === placeholder && ++result;
return result;
}(args, placeholder);
if (partials && (args = composeArgs(args, partials, holders, isCurried)), partialsRight && (args = composeArgsRight(args, partialsRight, holdersRight, isCurried)), length -= holdersCount, isCurried && length < arity) {
var newHolders = replaceHolders(args, placeholder);
return createRecurry(func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length);
}
var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func;
return length = args.length, argPos ? args = /**
* Reorder `array` according to the specified indexes where the element at
* the first index is assigned as the first element, the element at
* the second index is assigned as the second element, and so on.
*
* @private
* @param {Array} array The array to reorder.
* @param {Array} indexes The arranged array indexes.
* @returns {Array} Returns `array`.
*/ function(array, indexes) {
for(var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); length--;){
var index = indexes[length];
array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
}
return array;
}(args, argPos) : isFlip && length > 1 && args.reverse(), isAry && ary < length && (args.length = ary), this && this !== root && this instanceof wrapper && (fn = Ctor || createCtor(fn)), fn.apply(thisBinding, args);
}
return wrapper;
}
/**
* Creates a function like `_.invertBy`.
*
* @private
* @param {Function} setter The function to set accumulator values.
* @param {Function} toIteratee The function to resolve iteratees.
* @returns {Function} Returns the new inverter function.
*/ function createInverter(setter, toIteratee) {
return function(object, iteratee) {
var iteratee1, accumulator;
return iteratee1 = toIteratee(iteratee), accumulator = {}, baseForOwn(object, function(value, key, object) {
setter(accumulator, iteratee1(value), key, object);
}), accumulator;
};
}
/**
* Creates a function that performs a mathematical operation on two values.
*
* @private
* @param {Function} operator The function to perform the operation.
* @param {number} [defaultValue] The value used for `undefined` arguments.
* @returns {Function} Returns the new mathematical operation function.
*/ function createMathOperation(operator, defaultValue) {
return function(value, other) {
var result;
if (undefined === value && undefined === other) return defaultValue;
if (undefined !== value && (result = value), undefined !== other) {
if (undefined === result) return other;
'string' == typeof value || 'string' == typeof other ? (value = baseToString(value), other = baseToString(other)) : (value = baseToNumber(value), other = baseToNumber(other)), result = operator(value, other);
}
return result;
};
}
/**
* Creates a function like `_.over`.
*
* @private
* @param {Function} arrayFunc The function to iterate over iteratees.
* @returns {Function} Returns the new over function.
*/ function createOver(arrayFunc) {
return flatRest(function(iteratees) {
return iteratees = arrayMap(iteratees, baseUnary(getIteratee())), baseRest(function(args) {
var thisArg = this;
return arrayFunc(iteratees, function(iteratee) {
return apply(iteratee, thisArg, args);
});
});
});
}
/**
* Creates the padding for `string` based on `length`. The `chars` string
* is truncated if the number of characters exceeds `length`.
*
* @private
* @param {number} length The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padding for `string`.
*/ function createPadding(length, chars) {
var charsLength = (chars = undefined === chars ? ' ' : baseToString(chars)).length;
if (charsLength < 2) return charsLength ? baseRepeat(chars, length) : chars;
var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));
return hasUnicode(chars) ? castSlice(stringToArray(result), 0, length).join('') : result.slice(0, length);
}
/**
* Creates a `_.range` or `_.rangeRight` function.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new range function.
*/ function createRange(fromRight) {
return function(start, end, step) {
return step && 'number' != typeof step && isIterateeCall(start, end, step) && (end = step = undefined), // Ensure the sign of `-0` is preserved.
start = toFinite(start), undefined === end ? (end = start, start = 0) : end = toFinite(end), step = undefined === step ? start < end ? 1 : -1 : toFinite(step), /**
* The base implementation of `_.range` and `_.rangeRight` which doesn't
* coerce arguments.
*
* @private
* @param {number} start The start of the range.
* @param {number} end The end of the range.
* @param {number} step The value to increment or decrement by.
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Array} Returns the range of numbers.
*/ function(start, end, step, fromRight) {
for(var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array1(length); length--;)result[fromRight ? length : ++index] = start, start += step;
return result;
}(start, end, step, fromRight);
};
}
/**
* Creates a function that performs a relational operation on two values.
*
* @private
* @param {Function} operator The function to perform the operation.
* @returns {Function} Returns the new relational operation function.
*/ function createRelationalOperation(operator) {
return function(value, other) {
return ('string' != typeof value || 'string' != typeof other) && (value = toNumber(value), other = toNumber(other)), operator(value, other);
};
}
/**
* Creates a function that wraps `func` to continue currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {Function} wrapFunc The function to create the `func` wrapper.
* @param {*} placeholder The placeholder value.
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to prepend to those provided to
* the new function.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
var isCurry = 8 & bitmask, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials;
bitmask |= isCurry ? 32 : 64, 4 & (bitmask &= ~(isCurry ? 64 : 32)) || (bitmask &= -4);
var newData = [
func,
bitmask,
thisArg,
newPartials,
newHolders,
newPartialsRight,
newHoldersRight,
argPos,
ary,
arity
], result = wrapFunc.apply(undefined, newData);
return isLaziable(func) && setData(result, newData), result.placeholder = placeholder, setWrapToString(result, func, bitmask);
}
/**
* Creates a function like `_.round`.
*
* @private
* @param {string} methodName The name of the `Math` method to use when rounding.
* @returns {Function} Returns the new round function.
*/ function createRound(methodName) {
var func = Math[methodName];
return function(number, precision) {
if (number = toNumber(number), (precision = null == precision ? 0 : nativeMin(toInteger(precision), 292)) && nativeIsFinite(number)) {
// Shift with exponential notation to avoid floating-point issues.
// See [MDN](https://mdn.io/round#Examples) for more details.
var pair = (toString(number) + 'e').split('e');
return +((pair = (toString(func(pair[0] + 'e' + (+pair[1] + precision))) + 'e').split('e'))[0] + 'e' + (+pair[1] - precision));
}
return func(number);
};
}
/**
* Creates a set object of `values`.
*
* @private
* @param {Array} values The values to add to the set.
* @returns {Object} Returns the new set.
*/ var createSet = Set && 1 / setToArray(new Set([
,
-0
]))[1] == INFINITY ? function(values) {
return new Set(values);
} : noop;
/**
* Creates a `_.toPairs` or `_.toPairsIn` function.
*
* @private
* @param {Function} keysFunc The function to get the keys of a given object.
* @returns {Function} Returns the new pairs function.
*/ function createToPairs(keysFunc) {
return function(object) {
var index, result, tag = getTag(object);
return tag == mapTag ? mapToArray(object) : tag == setTag ? (index = -1, result = Array(object.size), object.forEach(function(value) {
result[++index] = [
value,
value
];
}), result) : arrayMap(keysFunc(object), function(key) {
return [
key,
object[key]
];
});
};
}
/**
* Creates a function that either curries or invokes `func` with optional
* `this` binding and partially applied arguments.
*
* @private
* @param {Function|string} func The function or method name to wrap.
* @param {number} bitmask The bitmask flags.
* 1 - `_.bind`
* 2 - `_.bindKey`
* 4 - `_.curry` or `_.curryRight` of a bound function
* 8 - `_.curry`
* 16 - `_.curryRight`
* 32 - `_.partial`
* 64 - `_.partialRight`
* 128 - `_.rearg`
* 256 - `_.ary`
* 512 - `_.flip`
* @param {*} [thisArg] The `this` binding of `func`.
* @param {Array} [partials] The arguments to be partially applied.
* @param {Array} [holders] The `partials` placeholder indexes.
* @param {Array} [argPos] The argument positions of the new function.
* @param {number} [ary] The arity cap of `func`.
* @param {number} [arity] The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
var isBindKey = 2 & bitmask;
if (!isBindKey && 'function' != typeof func) throw new TypeError(FUNC_ERROR_TEXT);
var length = partials ? partials.length : 0;
if (length || (bitmask &= -97, partials = holders = undefined), ary = undefined === ary ? ary : nativeMax(toInteger(ary), 0), arity = undefined === arity ? arity : toInteger(arity), length -= holders ? holders.length : 0, 64 & bitmask) {
var partialsRight = partials, holdersRight = holders;
partials = holders = undefined;
}
var data = isBindKey ? undefined : getData(func), newData = [
func,
bitmask,
thisArg,
partials,
holders,
partialsRight,
holdersRight,
argPos,
ary,
arity
];
if (data && /**
* Merges the function metadata of `source` into `data`.
*
* Merging metadata reduces the number of wrappers used to invoke a function.
* This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
* may be applied regardless of execution order. Methods like `_.ary` and
* `_.rearg` modify function arguments, making the order in which they are
* executed important, preventing the merging of metadata. However, we make
* an exception for a safe combined case where curried functions have `_.ary`
* and or `_.rearg` applied.
*
* @private
* @param {Array} data The destination metadata.
* @param {Array} source The source metadata.
* @returns {Array} Returns `data`.
*/ function(data, source) {
var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < 131, isCombo = 128 == srcBitmask && 8 == bitmask || 128 == srcBitmask && 256 == bitmask && data[7].length <= source[8] || 384 == srcBitmask && source[7].length <= source[8] && 8 == bitmask;
// Exit early if metadata can't be merged.
if (isCommon || isCombo) {
1 & srcBitmask && (data[2] = source[2], // Set when currying a bound function.
newBitmask |= 1 & bitmask ? 0 : 4);
// Compose partial arguments.
var value = source[3];
if (value) {
var partials = data[3];
data[3] = partials ? composeArgs(partials, value, source[4]) : value, data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];
}
// Compose partial right arguments.
(value = source[5]) && (partials = data[5], data[5] = partials ? composeArgsRight(partials, value, source[6]) : value, data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]), // Use source `argPos` if available.
(value = source[7]) && (data[7] = value), 128 & srcBitmask && (data[8] = null == data[8] ? source[8] : nativeMin(data[8], source[8])), null == data[9] && (data[9] = source[9]), // Use source `func` and merge bitmasks.
data[0] = source[0], data[1] = newBitmask;
}
}(newData, data), func = newData[0], bitmask = newData[1], thisArg = newData[2], partials = newData[3], holders = newData[4], (arity = newData[9] = newData[9] === undefined ? isBindKey ? 0 : func.length : nativeMax(newData[9] - length, 0)) || !(24 & bitmask) || (bitmask &= -25), bitmask && 1 != bitmask) 8 == bitmask || 16 == bitmask ? result = /**
* Creates a function that wraps `func` to enable currying.
*
* @private
* @param {Function} func The function to wrap.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @param {number} arity The arity of `func`.
* @returns {Function} Returns the new wrapped function.
*/ function(func, bitmask, arity) {
var Ctor = createCtor(func);
function wrapper() {
for(var length = arguments.length, args = Array1(length), index = length, placeholder = getHolder(wrapper); index--;)args[index] = arguments[index];
var holders = length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder ? [] : replaceHolders(args, placeholder);
return (length -= holders.length) < arity ? createRecurry(func, bitmask, createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length) : apply(this && this !== root && this instanceof wrapper ? Ctor : func, this, args);
}
return wrapper;
}(func, bitmask, arity) : 32 != bitmask && 33 != bitmask || holders.length ? result = createHybrid.apply(undefined, newData) : (func1 = func, bitmask1 = bitmask, thisArg1 = thisArg, partials1 = partials, isBind = 1 & bitmask1, Ctor = createCtor(func1), result = function wrapper() {
for(var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials1.length, args = Array1(leftLength + argsLength), fn = this && this !== root && this instanceof wrapper ? Ctor : func1; ++leftIndex < leftLength;)args[leftIndex] = partials1[leftIndex];
for(; argsLength--;)args[leftIndex++] = arguments[++argsIndex];
return apply(fn, isBind ? thisArg1 : this, args);
});
else var func1, bitmask1, thisArg1, partials1, isBind, Ctor, func2, bitmask2, thisArg2, isBind1, Ctor1, result = (func2 = func, bitmask2 = bitmask, thisArg2 = thisArg, isBind1 = 1 & bitmask2, Ctor1 = createCtor(func2), function wrapper() {
return (this && this !== root && this instanceof wrapper ? Ctor1 : func2).apply(isBind1 ? thisArg2 : this, arguments);
});
return setWrapToString((data ? baseSetData : setData)(result, newData), func, bitmask);
}
/**
* Used by `_.defaults` to customize its `_.assignIn` use to assign properties
* of source objects to the destination object for all destination properties
* that resolve to `undefined`.
*
* @private
* @param {*} objValue The destination value.
* @param {*} srcValue The source value.
* @param {string} key The key of the property to assign.
* @param {Object} object The parent object of `objValue`.
* @returns {*} Returns the value to assign.
*/ function customDefaultsAssignIn(objValue, srcValue, key, object) {
return undefined === objValue || eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key) ? srcValue : objValue;
}
/**
* Used by `_.defaultsDeep` to customize its `_.merge` use to merge source
* objects into destination objects that are passed thru.
*
* @private
* @param {*} objValue The destination value.
* @param {*} srcValue The source value.
* @param {string} key The key of the property to merge.
* @param {Object} object The parent object of `objValue`.
* @param {Object} source The parent object of `srcValue`.
* @param {Object} [stack] Tracks traversed source values and their merged
* counterparts.
* @returns {*} Returns the value to assign.
*/ function customDefaultsMerge(objValue, srcValue, key, object, source, stack) {
return isObject(objValue) && isObject(srcValue) && (// Recursively merge objects and arrays (susceptible to call stack limits).
stack.set(srcValue, objValue), baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack), stack.delete(srcValue)), objValue;
}
/**
* Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
* objects.
*
* @private
* @param {*} value The value to inspect.
* @param {string} key The key of the property to inspect.
* @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
*/ function customOmitClone(value) {
return isPlainObject(value) ? undefined : value;
}
/**
* A specialized version of `baseIsEqualDeep` for arrays with support for
* partial deep comparisons.
*
* @private
* @param {Array} array The array to compare.
* @param {Array} other The other array to compare.
* @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
* @param {Function} customizer The function to customize comparisons.
* @param {Function} equalFunc The function to determine equivalents of values.
* @param {Object} stack Tracks traversed `array` and `other` objects.
* @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
*/ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
var isPartial = 1 & bitmask, arrLength = array.length, othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) return !1;
// Check that cyclic values are equal.
var arrStacked = stack.get(array), othStacked = stack.get(other);
if (arrStacked && othStacked) return arrStacked == other && othStacked == array;
var index = -1, result = !0, seen = 2 & bitmask ? new SetCache : undefined;
// Ignore non-index properties.
for(stack.set(array, other), stack.set(other, array); ++index < arrLength;){
var arrValue = array[index], othValue = other[index];
if (customizer) var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
if (undefined !== compared) {
if (compared) continue;
result = !1;
break;
}
// Recursively compare arrays (susceptible to call stack limits).
if (seen) {
if (!arraySome(other, function(othValue, othIndex) {
if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) return seen.push(othIndex);
})) {
result = !1;
break;
}
} else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
result = !1;
break;
}
}
return stack.delete(array), stack.delete(other), result;
}
/**
* A specialized version of `baseRest` which flattens the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @returns {Function} Returns the new function.
*/ function flatRest(func) {
return setToString(overRest(func, undefined, flatten), func + '');
}
/**
* Creates an array of own enumerable property names and symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/ function getAllKeys(object) {
return baseGetAllKeys(object, keys, getSymbols);
}
/**
* Creates an array of own and inherited enumerable property names and
* symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names and symbols.
*/ function getAllKeysIn(object) {
return baseGetAllKeys(object, keysIn, getSymbolsIn);
}
/**
* Gets metadata for `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {*} Returns the metadata for `func`.
*/ var getData = metaMap ? function(func) {
return metaMap.get(func);
} : noop;
/**
* Gets the name of `func`.
*
* @private
* @param {Function} func The function to query.
* @returns {string} Returns the function name.
*/ function getFuncName(func) {
for(var result = func.name + '', array = realNames[result], length = hasOwnProperty.call(realNames, result) ? array.length : 0; length--;){
var data = array[length], otherFunc = data.func;
if (null == otherFunc || otherFunc == func) return data.name;
}
return result;
}
/**
* Gets the argument placeholder value for `func`.
*
* @private
* @param {Function} func The function to inspect.
* @returns {*} Returns the placeholder value.
*/ function getHolder(func) {
return (hasOwnProperty.call(lodash, 'placeholder') ? lodash : func).placeholder;
}
/**
* Gets the appropriate "iteratee" function. If `_.iteratee` is customized,
* this function returns the custom method, otherwise it returns `baseIteratee`.
* If arguments are provided, the chosen function is invoked with them and
* its result is returned.
*
* @private
* @param {*} [value] The value to convert to an iteratee.
* @param {number} [arity] The arity of the created iteratee.
* @returns {Function} Returns the chosen function or its result.
*/ function getIteratee() {
var result = lodash.iteratee || iteratee;
return result = result === iteratee ? baseIteratee : result, arguments.length ? result(arguments[0], arguments[1]) : result;
}
/**
* Gets the data for `map`.
*
* @private
* @param {Object} map The map to query.
* @param {string} key The reference key.
* @returns {*} Returns the map data.
*/ function getMapData(map, key) {
var type, data = map.__data__;
return ('string' == (type = typeof key) || 'number' == type || 'symbol' == type || 'boolean' == type ? '__proto__' !== key : null === key) ? data['string' == typeof key ? 'string' : 'hash'] : data.map;
}
/**
* Gets the property names, values, and compare flags of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the match data of `object`.
*/ function getMatchData(object) {
for(var result = keys(object), length = result.length; length--;){
var key = result[length], value = object[key];
result[length] = [
key,
value,
value == value && !isObject(value)
];
}
return result;
}
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/ function getNative(object, key) {
var value = null == object ? undefined : object[key];
return baseIsNative(value) ? value : undefined;
}
/**
* Creates an array of the own enumerable symbols of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of symbols.
*/ var getSymbols = nativeGetSymbols ? function(object) {
return null == object ? [] : arrayFilter(nativeGetSymbols(object = Object1(object)), function(symbol) {
return propertyIsEnumerable.call(object, symbol);
});
} : stubArray, getSymbolsIn = nativeGetSymbols ? function(object) {
for(var result = []; object;)arrayPush(result, getSymbols(object)), object = getPrototype(object);
return result;
} : stubArray, getTag = baseGetTag;
/**
* Checks if `path` exists on `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @param {Function} hasFunc The function to check properties.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
*/ function hasPath(object, path, hasFunc) {
path = castPath(path, object);
for(var index = -1, length = path.length, result = !1; ++index < length;){
var key = toKey(path[index]);
if (!(result = null != object && hasFunc(object, key))) break;
object = object[key];
}
return result || ++index != length ? result : !!(length = null == object ? 0 : object.length) && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object));
}
/**
* Initializes an object clone.
*
* @private
* @param {Object} object The object to clone.
* @returns {Object} Returns the initialized clone.
*/ function initCloneObject(object) {
return 'function' != typeof object.constructor || isPrototype(object) ? {} : baseCreate(getPrototype(object));
}
/**
* Checks if `value` is a flattenable `arguments` object or array.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
*/ function isFlattenable(value) {
return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/ function isIndex(value, length) {
var type = typeof value;
return !!(length = null == length ? 9007199254740991 : length) && ('number' == type || 'symbol' != type && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length;
}
/**
* Checks if the given arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call,
* else `false`.
*/ function isIterateeCall(value, index, object) {
if (!isObject(object)) return !1;
var type = typeof index;
return ('number' == type ? !!(isArrayLike(object) && isIndex(index, object.length)) : 'string' == type && index in object) && eq(object[index], value);
}
/**
* Checks if `value` is a property name and not a property path.
*
* @private
* @param {*} value The value to check.
* @param {Object} [object] The object to query keys on.
* @returns {boolean} Returns `true` if `value` is a property name, else `false`.
*/ function isKey(value, object) {
if (isArray(value)) return !1;
var type = typeof value;
return !!('number' == type || 'symbol' == type || 'boolean' == type || null == value || isSymbol(value)) || reIsPlainProp.test(value) || !reIsDeepProp.test(value) || null != object && value in Object1(object);
}
/**
* Checks if `func` has a lazy counterpart.
*
* @private
* @param {Function} func The function to check.
* @returns {boolean} Returns `true` if `func` has a lazy counterpart,
* else `false`.
*/ function isLaziable(func) {
var funcName = getFuncName(func), other = lodash[funcName];
if ('function' != typeof other || !(funcName in LazyWrapper.prototype)) return !1;
if (func === other) return !0;
var data = getData(other);
return !!data && func === data[0];
}
(DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag || Map && getTag(new Map) != mapTag || Promise && getTag(Promise.resolve()) != promiseTag || Set && getTag(new Set) != setTag || WeakMap && getTag(new WeakMap) != weakMapTag) && (getTag = function(value) {
var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : '';
if (ctorString) switch(ctorString){
case dataViewCtorString:
return dataViewTag;
case mapCtorString:
return mapTag;
case promiseCtorString:
return promiseTag;
case setCtorString:
return setTag;
case weakMapCtorString:
return weakMapTag;
}
return result;
});
/**
* Checks if `func` is capable of being masked.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `func` is maskable, else `false`.
*/ var isMaskable = coreJsData ? isFunction : stubFalse;
/**
* Checks if `value` is likely a prototype object.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
*/ function isPrototype(value) {
var Ctor = value && value.constructor;
return value === ('function' == typeof Ctor && Ctor.prototype || objectProto);
}
/**
* A specialized version of `matchesProperty` for source values suitable
* for strict equality comparisons, i.e. `===`.
*
* @private
* @param {string} key The key of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
*/ function matchesStrictComparable(key, srcValue) {
return function(object) {
return null != object && object[key] === srcValue && (undefined !== srcValue || key in Object1(object));
};
}
/**
* A specialized version of `baseRest` which transforms the rest array.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @param {Function} transform The rest array transform.
* @returns {Function} Returns the new function.
*/ function overRest(func, start, transform) {
return start = nativeMax(undefined === start ? func.length - 1 : start, 0), function() {
for(var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array1(length); ++index < length;)array[index] = args[start + index];
index = -1;
for(var otherArgs = Array1(start + 1); ++index < start;)otherArgs[index] = args[index];
return otherArgs[start] = transform(array), apply(func, this, otherArgs);
};
}
/**
* Gets the parent value at `path` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} path The path to get the parent value of.
* @returns {*} Returns the parent value.
*/ function parent(object, path) {
return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));
}
/**
* Gets the value at `key`, unless `key` is "__proto__" or "constructor".
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the property to get.
* @returns {*} Returns the property value.
*/ function safeGet(object, key) {
if (('constructor' !== key || 'function' != typeof object[key]) && '__proto__' != key) return object[key];
}
/**
* Sets metadata for `func`.
*
* **Note:** If this function becomes hot, i.e. is invoked a lot in a short
* period of time, it will trip its breaker and transition to an identity
* function to avoid garbage collection pauses in V8. See
* [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
* for more details.
*
* @private
* @param {Function} func The function to associate metadata with.
* @param {*} data The metadata.
* @returns {Function} Returns `func`.
*/ var setData = shortOut(baseSetData), setTimeout = ctxSetTimeout || function(func, wait) {
return root.setTimeout(func, wait);
}, setToString = shortOut(baseSetToString);
/**
* Sets the `toString` method of `wrapper` to mimic the source of `reference`
* with wrapper details in a comment at the top of the source body.
*
* @private
* @param {Function} wrapper The function to modify.
* @param {Function} reference The reference function.
* @param {number} bitmask The bitmask flags. See `createWrap` for more details.
* @returns {Function} Returns `wrapper`.
*/ function setWrapToString(wrapper, reference, bitmask) {
var details, match, source = reference + '';
return setToString(wrapper, /**
* Inserts wrapper `details` in a comment at the top of the `source` body.
*
* @private
* @param {string} source The source to modify.
* @returns {Array} details The details to insert.
* @returns {string} Returns the modified source.
*/ function(source, details) {
var length = details.length;
if (!length) return source;
var lastIndex = length - 1;
return details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex], details = details.join(length > 2 ? ', ' : ' '), source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
}(source, (details = (match = source.match(reWrapDetails)) ? match[1].split(reSplitDetails) : [], arrayEach(wrapFlags, function(pair) {
var value = '_.' + pair[0];
bitmask & pair[1] && !arrayIncludes(details, value) && details.push(value);
}), details.sort())));
}
/**
* Creates a function that'll short out and invoke `identity` instead
* of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
* milliseconds.
*
* @private
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new shortable function.
*/ function shortOut(func) {
var count = 0, lastCalled = 0;
return function() {
var stamp = nativeNow(), remaining = 16 - (stamp - lastCalled);
if (lastCalled = stamp, remaining > 0) {
if (++count >= 800) return arguments[0];
} else count = 0;
return func.apply(undefined, arguments);
};
}
/**
* A specialized version of `_.shuffle` which mutates and sets the size of `array`.
*
* @private
* @param {Array} array The array to shuffle.
* @param {number} [size=array.length] The size of `array`.
* @returns {Array} Returns `array`.
*/ function shuffleSelf(array, size) {
var index = -1, length = array.length, lastIndex = length - 1;
for(size = undefined === size ? length : size; ++index < size;){
var rand = baseRandom(index, lastIndex), value = array[rand];
array[rand] = array[index], array[index] = value;
}
return array.length = size, array;
}
/**
* Converts `string` to a property path array.
*
* @private
* @param {string} string The string to convert.
* @returns {Array} Returns the property path array.
*/ var stringToPath = (cache = (result = memoize(function(string) {
var result = [];
return 46 /* . */ === string.charCodeAt(0) && result.push(''), string.replace(rePropName, function(match, number, quote, subString) {
result.push(quote ? subString.replace(reEscapeChar, '$1') : number || match);
}), result;
}, function(key) {
return 500 === cache.size && cache.clear(), key;
})).cache, result);
/**
* Converts `value` to a string key if it's not a string or symbol.
*
* @private
* @param {*} value The value to inspect.
* @returns {string|symbol} Returns the key.
*/ function toKey(value) {
if ('string' == typeof value || isSymbol(value)) return value;
var result = value + '';
return '0' == result && 1 / value == -INFINITY ? '-0' : result;
}
/**
* Converts `func` to its source code.
*
* @private
* @param {Function} func The function to convert.
* @returns {string} Returns the source code.
*/ function toSource(func) {
if (null != func) {
try {
return funcToString.call(func);
} catch (e) {}
try {
return func + '';
} catch (e) {}
}
return '';
}
/**
* Creates a clone of `wrapper`.
*
* @private
* @param {Object} wrapper The wrapper to clone.
* @returns {Object} Returns the cloned wrapper.
*/ function wrapperClone(wrapper) {
if (wrapper instanceof LazyWrapper) return wrapper.clone();
var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
return result.__actions__ = copyArray(wrapper.__actions__), result.__index__ = wrapper.__index__, result.__values__ = wrapper.__values__, result;
}
/**
* Creates an array of `array` values not included in the other given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* **Note:** Unlike `_.pullAll`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @see _.without, _.xor
* @example
*
* _.difference([2, 1], [2, 3]);
* // => [1]
*/ var difference = baseRest(function(array, values) {
return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, !0)) : [];
}), differenceBy = baseRest(function(array, values) {
var iteratee = last(values);
return isArrayLikeObject(iteratee) && (iteratee = undefined), isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, !0), getIteratee(iteratee, 2)) : [];
}), differenceWith = baseRest(function(array, values) {
var comparator = last(values);
return isArrayLikeObject(comparator) && (comparator = undefined), isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, !0), undefined, comparator) : [];
});
/**
* This method is like `_.find` except that it returns the index of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.findIndex(users, function(o) { return o.user == 'barney'; });
* // => 0
*
* // The `_.matches` iteratee shorthand.
* _.findIndex(users, { 'user': 'fred', 'active': false });
* // => 1
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findIndex(users, ['active', false]);
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.findIndex(users, 'active');
* // => 2
*/ function findIndex(array, predicate, fromIndex) {
var length = null == array ? 0 : array.length;
if (!length) return -1;
var index = null == fromIndex ? 0 : toInteger(fromIndex);
return index < 0 && (index = nativeMax(length + index, 0)), baseFindIndex(array, getIteratee(predicate, 3), index);
}
/**
* This method is like `_.findIndex` except that it iterates over elements
* of `collection` from right to left.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param {number} [fromIndex=array.length-1] The index to search from.
* @returns {number} Returns the index of the found element, else `-1`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
* // => 2
*
* // The `_.matches` iteratee shorthand.
* _.findLastIndex(users, { 'user': 'barney', 'active': true });
* // => 0
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findLastIndex(users, ['active', false]);
* // => 2
*
* // The `_.property` iteratee shorthand.
* _.findLastIndex(users, 'active');
* // => 0
*/ function findLastIndex(array, predicate, fromIndex) {
var length = null == array ? 0 : array.length;
if (!length) return -1;
var index = length - 1;
return undefined !== fromIndex && (index = toInteger(fromIndex), index = fromIndex < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1)), baseFindIndex(array, getIteratee(predicate, 3), index, !0);
}
/**
* Flattens `array` a single level deep.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flatten([1, [2, [3, [4]], 5]]);
* // => [1, 2, [3, [4]], 5]
*/ function flatten(array) {
return (null == array ? 0 : array.length) ? baseFlatten(array, 1) : [];
}
/**
* Gets the first element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias first
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the first element of `array`.
* @example
*
* _.head([1, 2, 3]);
* // => 1
*
* _.head([]);
* // => undefined
*/ function head(array) {
return array && array.length ? array[0] : undefined;
}
/**
* Creates an array of unique values that are included in all given arrays
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. The order and references of result values are
* determined by the first array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* _.intersection([2, 1], [2, 3]);
* // => [2]
*/ var intersection = baseRest(function(arrays) {
var mapped = arrayMap(arrays, castArrayLikeObject);
return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped) : [];
}), intersectionBy = baseRest(function(arrays) {
var iteratee = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject);
return iteratee === last(mapped) ? iteratee = undefined : mapped.pop(), mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, getIteratee(iteratee, 2)) : [];
}), intersectionWith = baseRest(function(arrays) {
var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject);
return (comparator = 'function' == typeof comparator ? comparator : undefined) && mapped.pop(), mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, undefined, comparator) : [];
});
/**
* Gets the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {*} Returns the last element of `array`.
* @example
*
* _.last([1, 2, 3]);
* // => 3
*/ function last(array) {
var length = null == array ? 0 : array.length;
return length ? array[length - 1] : undefined;
}
/**
* Removes all given values from `array` using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`
* to remove elements from an array by predicate.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {...*} [values] The values to remove.
* @returns {Array} Returns `array`.
* @example
*
* var array = ['a', 'b', 'c', 'a', 'b', 'c'];
*
* _.pull(array, 'a', 'c');
* console.log(array);
* // => ['b', 'b']
*/ var pull = baseRest(pullAll);
/**
* This method is like `_.pull` except that it accepts an array of values to remove.
*
* **Note:** Unlike `_.difference`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @returns {Array} Returns `array`.
* @example
*
* var array = ['a', 'b', 'c', 'a', 'b', 'c'];
*
* _.pullAll(array, ['a', 'c']);
* console.log(array);
* // => ['b', 'b']
*/ function pullAll(array, values) {
return array && array.length && values && values.length ? basePullAll(array, values) : array;
}
/**
* Removes elements from `array` corresponding to `indexes` and returns an
* array of removed elements.
*
* **Note:** Unlike `_.at`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {...(number|number[])} [indexes] The indexes of elements to remove.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* var array = ['a', 'b', 'c', 'd'];
* var pulled = _.pullAt(array, [1, 3]);
*
* console.log(array);
* // => ['a', 'c']
*
* console.log(pulled);
* // => ['b', 'd']
*/ var pullAt = flatRest(function(array, indexes) {
var length = null == array ? 0 : array.length, result = baseAt(array, indexes);
return basePullAt(array, arrayMap(indexes, function(index) {
return isIndex(index, length) ? +index : index;
}).sort(compareAscending)), result;
});
/**
* Reverses `array` so that the first element becomes the last, the second
* element becomes the second to last, and so on.
*
* **Note:** This method mutates `array` and is based on
* [`Array#reverse`](https://mdn.io/Array/reverse).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @returns {Array} Returns `array`.
* @example
*
* var array = [1, 2, 3];
*
* _.reverse(array);
* // => [3, 2, 1]
*
* console.log(array);
* // => [3, 2, 1]
*/ function reverse(array) {
return null == array ? array : nativeReverse.call(array);
}
/**
* Creates an array of unique values, in order, from all given arrays using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @returns {Array} Returns the new array of combined values.
* @example
*
* _.union([2], [1, 2]);
* // => [2, 1]
*/ var union = baseRest(function(arrays) {
return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, !0));
}), unionBy = baseRest(function(arrays) {
var iteratee = last(arrays);
return isArrayLikeObject(iteratee) && (iteratee = undefined), baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, !0), getIteratee(iteratee, 2));
}), unionWith = baseRest(function(arrays) {
var comparator = last(arrays);
return comparator = 'function' == typeof comparator ? comparator : undefined, baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, !0), undefined, comparator);
});
/**
* This method is like `_.zip` except that it accepts an array of grouped
* elements and creates an array regrouping the elements to their pre-zip
* configuration.
*
* @static
* @memberOf _
* @since 1.2.0
* @category Array
* @param {Array} array The array of grouped elements to process.
* @returns {Array} Returns the new array of regrouped elements.
* @example
*
* var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);
* // => [['a', 1, true], ['b', 2, false]]
*
* _.unzip(zipped);
* // => [['a', 'b'], [1, 2], [true, false]]
*/ function unzip(array) {
if (!(array && array.length)) return [];
var length = 0;
return array = arrayFilter(array, function(group) {
if (isArrayLikeObject(group)) return length = nativeMax(group.length, length), !0;
}), baseTimes(length, function(index) {
return arrayMap(array, baseProperty(index));
});
}
/**
* This method is like `_.unzip` except that it accepts `iteratee` to specify
* how regrouped values should be combined. The iteratee is invoked with the
* elements of each group: (...group).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Array
* @param {Array} array The array of grouped elements to process.
* @param {Function} [iteratee=_.identity] The function to combine
* regrouped values.
* @returns {Array} Returns the new array of regrouped elements.
* @example
*
* var zipped = _.zip([1, 2], [10, 20], [100, 200]);
* // => [[1, 10, 100], [2, 20, 200]]
*
* _.unzipWith(zipped, _.add);
* // => [3, 30, 300]
*/ function unzipWith(array, iteratee) {
if (!(array && array.length)) return [];
var result = unzip(array);
return null == iteratee ? result : arrayMap(result, function(group) {
return apply(iteratee, undefined, group);
});
}
/**
* Creates an array excluding all given values using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons.
*
* **Note:** Unlike `_.pull`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...*} [values] The values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @see _.difference, _.xor
* @example
*
* _.without([2, 1, 2, 3], 1, 2);
* // => [3]
*/ var without = baseRest(function(array, values) {
return isArrayLikeObject(array) ? baseDifference(array, values) : [];
}), xor = baseRest(function(arrays) {
return baseXor(arrayFilter(arrays, isArrayLikeObject));
}), xorBy = baseRest(function(arrays) {
var iteratee = last(arrays);
return isArrayLikeObject(iteratee) && (iteratee = undefined), baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2));
}), xorWith = baseRest(function(arrays) {
var comparator = last(arrays);
return comparator = 'function' == typeof comparator ? comparator : undefined, baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator);
}), zip = baseRest(unzip), zipWith = baseRest(function(arrays) {
var length = arrays.length, iteratee = length > 1 ? arrays[length - 1] : undefined;
return iteratee = 'function' == typeof iteratee ? (arrays.pop(), iteratee) : undefined, unzipWith(arrays, iteratee);
});
/*------------------------------------------------------------------------*/ /**
* Creates a `lodash` wrapper instance that wraps `value` with explicit method
* chain sequences enabled. The result of such sequences must be unwrapped
* with `_#value`.
*
* @static
* @memberOf _
* @since 1.3.0
* @category Seq
* @param {*} value The value to wrap.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'pebbles', 'age': 1 }
* ];
*
* var youngest = _
* .chain(users)
* .sortBy('age')
* .map(function(o) {
* return o.user + ' is ' + o.age;
* })
* .head()
* .value();
* // => 'pebbles is 1'
*/ function chain(value) {
var result = lodash(value);
return result.__chain__ = !0, result;
}
/**
* This method is like `_.tap` except that it returns the result of `interceptor`.
* The purpose of this method is to "pass thru" values replacing intermediate
* results in a method chain sequence.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Seq
* @param {*} value The value to provide to `interceptor`.
* @param {Function} interceptor The function to invoke.
* @returns {*} Returns the result of `interceptor`.
* @example
*
* _(' abc ')
* .chain()
* .trim()
* .thru(function(value) {
* return [value];
* })
* .value();
* // => ['abc']
*/ function thru(value, interceptor) {
return interceptor(value);
}
/**
* This method is the wrapper version of `_.at`.
*
* @name at
* @memberOf _
* @since 1.0.0
* @category Seq
* @param {...(string|string[])} [paths] The property paths to pick.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
*
* _(object).at(['a[0].b.c', 'a[1]']).value();
* // => [3, 4]
*/ var wrapperAt = flatRest(function(paths) {
var length = paths.length, start = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) {
return baseAt(object, paths);
};
return !(length > 1) && !this.__actions__.length && value instanceof LazyWrapper && isIndex(start) ? ((value = value.slice(start, +start + +!!length)).__actions__.push({
func: thru,
args: [
interceptor
],
thisArg: undefined
}), new LodashWrapper(value, this.__chain__).thru(function(array) {
return length && !array.length && array.push(undefined), array;
})) : this.thru(interceptor);
}), countBy = createAggregator(function(result, value, key) {
hasOwnProperty.call(result, key) ? ++result[key] : baseAssignValue(result, key, 1);
}), find = createFind(findIndex), findLast = createFind(findLastIndex);
/**
* Iterates over elements of `collection` and invokes `iteratee` for each element.
* The iteratee is invoked with three arguments: (value, index|key, collection).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* **Note:** As with other "Collections" methods, objects with a "length"
* property are iterated like arrays. To avoid this behavior use `_.forIn`
* or `_.forOwn` for object iteration.
*
* @static
* @memberOf _
* @since 0.1.0
* @alias each
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
* @see _.forEachRight
* @example
*
* _.forEach([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `1` then `2`.
*
* _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/ function forEach(collection, iteratee) {
return (isArray(collection) ? arrayEach : baseEach)(collection, getIteratee(iteratee, 3));
}
/**
* This method is like `_.forEach` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @since 2.0.0
* @alias eachRight
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
* @see _.forEach
* @example
*
* _.forEachRight([1, 2], function(value) {
* console.log(value);
* });
* // => Logs `2` then `1`.
*/ function forEachRight(collection, iteratee) {
return (isArray(collection) ? /**
* A specialized version of `_.forEachRight` for arrays without support for
* iteratee shorthands.
*
* @private
* @param {Array} [array] The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/ function(array, iteratee) {
for(var length = null == array ? 0 : array.length; length-- && !1 !== iteratee(array[length], length, array););
return array;
} : baseEachRight)(collection, getIteratee(iteratee, 3));
}
/**
* Creates an object composed of keys generated from the results of running
* each element of `collection` thru `iteratee`. The order of grouped values
* is determined by the order they occur in `collection`. The corresponding
* value of each key is an array of elements responsible for generating the
* key. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee to transform keys.
* @returns {Object} Returns the composed aggregate object.
* @example
*
* _.groupBy([6.1, 4.2, 6.3], Math.floor);
* // => { '4': [4.2], '6': [6.1, 6.3] }
*
* // The `_.property` iteratee shorthand.
* _.groupBy(['one', 'two', 'three'], 'length');
* // => { '3': ['one', 'two'], '5': ['three'] }
*/ var groupBy = createAggregator(function(result, value, key) {
hasOwnProperty.call(result, key) ? result[key].push(value) : baseAssignValue(result, key, [
value
]);
}), invokeMap = baseRest(function(collection, path, args) {
var index = -1, isFunc = 'function' == typeof path, result = isArrayLike(collection) ? Array1(collection.length) : [];
return baseEach(collection, function(value) {
result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args);
}), result;
}), keyBy = createAggregator(function(result, value, key) {
baseAssignValue(result, key, value);
});
/**
* Creates an array of values by running each element in `collection` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
*
* The guarded methods are:
* `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
* `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
* `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
* `template`, `trim`, `trimEnd`, `trimStart`, and `words`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new mapped array.
* @example
*
* function square(n) {
* return n * n;
* }
*
* _.map([4, 8], square);
* // => [16, 64]
*
* _.map({ 'a': 4, 'b': 8 }, square);
* // => [16, 64] (iteration order is not guaranteed)
*
* var users = [
* { 'user': 'barney' },
* { 'user': 'fred' }
* ];
*
* // The `_.property` iteratee shorthand.
* _.map(users, 'user');
* // => ['barney', 'fred']
*/ function map(collection, iteratee) {
return (isArray(collection) ? arrayMap : baseMap)(collection, getIteratee(iteratee, 3));
}
/**
* Creates an array of elements split into two groups, the first of which
* contains elements `predicate` returns truthy for, the second of which
* contains elements `predicate` returns falsey for. The predicate is
* invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the array of grouped elements.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true },
* { 'user': 'pebbles', 'age': 1, 'active': false }
* ];
*
* _.partition(users, function(o) { return o.active; });
* // => objects for [['fred'], ['barney', 'pebbles']]
*
* // The `_.matches` iteratee shorthand.
* _.partition(users, { 'age': 1, 'active': false });
* // => objects for [['pebbles'], ['barney', 'fred']]
*
* // The `_.matchesProperty` iteratee shorthand.
* _.partition(users, ['active', false]);
* // => objects for [['barney', 'pebbles'], ['fred']]
*
* // The `_.property` iteratee shorthand.
* _.partition(users, 'active');
* // => objects for [['fred'], ['barney', 'pebbles']]
*/ var partition = createAggregator(function(result, value, key) {
result[+!key].push(value);
}, function() {
return [
[],
[]
];
}), sortBy = baseRest(function(collection, iteratees) {
if (null == collection) return [];
var length = iteratees.length;
return length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1]) ? iteratees = [] : length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2]) && (iteratees = [
iteratees[0]
]), baseOrderBy(collection, baseFlatten(iteratees, 1), []);
}), now = ctxNow || function() {
return root.Date.now();
};
/**
* Creates a function that invokes `func`, with up to `n` arguments,
* ignoring any additional arguments.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} func The function to cap arguments for.
* @param {number} [n=func.length] The arity cap.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new capped function.
* @example
*
* _.map(['6', '8', '10'], _.ary(parseInt, 1));
* // => [6, 8, 10]
*/ function ary(func, n, guard) {
return n = guard ? undefined : n, n = func && null == n ? func.length : n, createWrap(func, 128, undefined, undefined, undefined, undefined, n);
}
/**
* Creates a function that invokes `func`, with the `this` binding and arguments
* of the created function, while it's called less than `n` times. Subsequent
* calls to the created function return the result of the last `func` invocation.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {number} n The number of calls at which `func` is no longer invoked.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* jQuery(element).on('click', _.before(5, addContactToList));
* // => Allows adding up to 4 contacts to the list.
*/ function before(n, func) {
var result;
if ('function' != typeof func) throw new TypeError(FUNC_ERROR_TEXT);
return n = toInteger(n), function() {
return --n > 0 && (result = func.apply(this, arguments)), n <= 1 && (func = undefined), result;
};
}
/**
* Creates a function that invokes `func` with the `this` binding of `thisArg`
* and `partials` prepended to the arguments it receives.
*
* The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for partially applied arguments.
*
* **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
* property of bound functions.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {...*} [partials] The arguments to be partially applied.
* @returns {Function} Returns the new bound function.
* @example
*
* function greet(greeting, punctuation) {
* return greeting + ' ' + this.user + punctuation;
* }
*
* var object = { 'user': 'fred' };
*
* var bound = _.bind(greet, object, 'hi');
* bound('!');
* // => 'hi fred!'
*
* // Bound with placeholders.
* var bound = _.bind(greet, object, _, '!');
* bound('hi');
* // => 'hi fred!'
*/ var bind = baseRest(function(func, thisArg, partials) {
var bitmask = 1;
if (partials.length) {
var holders = replaceHolders(partials, getHolder(bind));
bitmask |= 32;
}
return createWrap(func, bitmask, thisArg, partials, holders);
}), bindKey = baseRest(function(object, key, partials) {
var bitmask = 3;
if (partials.length) {
var holders = replaceHolders(partials, getHolder(bindKey));
bitmask |= 32;
}
return createWrap(key, bitmask, object, partials, holders);
});
/**
* Creates a function that accepts arguments of `func` and either invokes
* `func` returning its result, if at least `arity` number of arguments have
* been provided, or returns a function that accepts the remaining `func`
* arguments, and so on. The arity of `func` may be specified if `func.length`
* is not sufficient.
*
* The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
* may be used as a placeholder for provided arguments.
*
* **Note:** This method doesn't set the "length" property of curried functions.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Function
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new curried function.
* @example
*
* var abc = function(a, b, c) {
* return [a, b, c];
* };
*
* var curried = _.curry(abc);
*
* curried(1)(2)(3);
* // => [1, 2, 3]
*
* curried(1, 2)(3);
* // => [1, 2, 3]
*
* curried(1, 2, 3);
* // => [1, 2, 3]
*
* // Curried with placeholders.
* curried(1)(_, 3)(2);
* // => [1, 2, 3]
*/ function curry(func, arity, guard) {
arity = guard ? undefined : arity;
var result = createWrap(func, 8, undefined, undefined, undefined, undefined, undefined, arity);
return result.placeholder = curry.placeholder, result;
}
/**
* This method is like `_.curry` except that arguments are applied to `func`
* in the manner of `_.partialRight` instead of `_.partial`.
*
* The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
* builds, may be used as a placeholder for provided arguments.
*
* **Note:** This method doesn't set the "length" property of curried functions.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} func The function to curry.
* @param {number} [arity=func.length] The arity of `func`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the new curried function.
* @example
*
* var abc = function(a, b, c) {
* return [a, b, c];
* };
*
* var curried = _.curryRight(abc);
*
* curried(3)(2)(1);
* // => [1, 2, 3]
*
* curried(2, 3)(1);
* // => [1, 2, 3]
*
* curried(1, 2, 3);
* // => [1, 2, 3]
*
* // Curried with placeholders.
* curried(3)(1, _)(2);
* // => [1, 2, 3]
*/ function curryRight(func, arity, guard) {
arity = guard ? undefined : arity;
var result = createWrap(func, 16, undefined, undefined, undefined, undefined, undefined, arity);
return result.placeholder = curryRight.placeholder, result;
}
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
* delayed `func` invocations and a `flush` method to immediately invoke them.
* Provide `options` to indicate whether `func` should be invoked on the
* leading and/or trailing edge of the `wait` timeout. The `func` is invoked
* with the last arguments provided to the debounced function. Subsequent
* calls to the debounced function return the result of the last `func`
* invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the debounced function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to debounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=false]
* Specify invoking on the leading edge of the timeout.
* @param {number} [options.maxWait]
* The maximum time `func` is allowed to be delayed before it's invoked.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // Avoid costly calculations while the window size is in flux.
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // Invoke `sendMail` when clicked, debouncing subsequent calls.
* jQuery(element).on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // Ensure `batchLog` is invoked once after 1 second of debounced calls.
* var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
* var source = new EventSource('/stream');
* jQuery(source).on('message', debounced);
*
* // Cancel the trailing debounced invocation.
* jQuery(window).on('popstate', debounced.cancel);
*/ function debounce(func, wait, options) {
var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = !1, maxing = !1, trailing = !0;
if ('function' != typeof func) throw new TypeError(FUNC_ERROR_TEXT);
function invokeFunc(time) {
var args = lastArgs, thisArg = lastThis;
return lastArgs = lastThis = undefined, lastInvokeTime = time, result = func.apply(thisArg, args);
}
function shouldInvoke(time) {
var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
// Either this is the first call, activity has stopped and we're at the
// trailing edge, the system time has gone backwards and we're treating
// it as the trailing edge, or we've hit the `maxWait` limit.
return undefined === lastCallTime || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
}
function timerExpired() {
var timeSinceLastCall, timeSinceLastInvoke, timeWaiting, time = now();
if (shouldInvoke(time)) return trailingEdge(time);
// Restart the timer.
timerId = setTimeout(timerExpired, (timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall, maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting));
}
function trailingEdge(time) {
return(// Only invoke if we have `lastArgs` which means `func` has been
// debounced at least once.
(timerId = undefined, trailing && lastArgs) ? invokeFunc(time) : (lastArgs = lastThis = undefined, result));
}
function debounced() {
var time, time1 = now(), isInvoking = shouldInvoke(time1);
if (lastArgs = arguments, lastThis = this, lastCallTime = time1, isInvoking) {
if (undefined === timerId) return(// Reset any `maxWait` timer.
lastInvokeTime = time = lastCallTime, // Start the timer for the trailing edge.
timerId = setTimeout(timerExpired, wait), leading ? invokeFunc(time) : result);
if (maxing) return(// Handle invocations in a tight loop.
clearTimeout(timerId), timerId = setTimeout(timerExpired, wait), invokeFunc(lastCallTime));
}
return undefined === timerId && (timerId = setTimeout(timerExpired, wait)), result;
}
return wait = toNumber(wait) || 0, isObject(options) && (leading = !!options.leading, maxWait = (maxing = 'maxWait' in options) ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait, trailing = 'trailing' in options ? !!options.trailing : trailing), debounced.cancel = function() {
undefined !== timerId && clearTimeout(timerId), lastInvokeTime = 0, lastArgs = lastCallTime = lastThis = timerId = undefined;
}, debounced.flush = function() {
return undefined === timerId ? result : trailingEdge(now());
}, debounced;
}
/**
* Defers invoking the `func` until the current call stack has cleared. Any
* additional arguments are provided to `func` when it's invoked.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to defer.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {number} Returns the timer id.
* @example
*
* _.defer(function(text) {
* console.log(text);
* }, 'deferred');
* // => Logs 'deferred' after one millisecond.
*/ var defer = baseRest(function(func, args) {
return baseDelay(func, 1, args);
}), delay = baseRest(function(func, wait, args) {
return baseDelay(func, toNumber(wait) || 0, args);
});
/**
* Creates a function that memoizes the result of `func`. If `resolver` is
* provided, it determines the cache key for storing the result based on the
* arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is used as the map cache key. The `func`
* is invoked with the `this` binding of the memoized function.
*
* **Note:** The cache is exposed as the `cache` property on the memoized
* function. Its creation may be customized by replacing the `_.memoize.Cache`
* constructor with one whose instances implement the
* [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
* method interface of `clear`, `delete`, `get`, `has`, and `set`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to have its output memoized.
* @param {Function} [resolver] The function to resolve the cache key.
* @returns {Function} Returns the new memoized function.
* @example
*
* var object = { 'a': 1, 'b': 2 };
* var other = { 'c': 3, 'd': 4 };
*
* var values = _.memoize(_.values);
* values(object);
* // => [1, 2]
*
* values(other);
* // => [3, 4]
*
* object.a = 2;
* values(object);
* // => [1, 2]
*
* // Modify the result cache.
* values.cache.set(object, ['a', 'b']);
* values(object);
* // => ['a', 'b']
*
* // Replace `_.memoize.Cache`.
* _.memoize.Cache = WeakMap;
*/ function memoize(func, resolver) {
if ('function' != typeof func || null != resolver && 'function' != typeof resolver) throw new TypeError(FUNC_ERROR_TEXT);
var memoized = function() {
var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache;
if (cache.has(key)) return cache.get(key);
var result = func.apply(this, args);
return memoized.cache = cache.set(key, result) || cache, result;
};
return memoized.cache = new (memoize.Cache || MapCache), memoized;
}
/**
* Creates a function that negates the result of the predicate `func`. The
* `func` predicate is invoked with the `this` binding and arguments of the
* created function.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Function
* @param {Function} predicate The predicate to negate.
* @returns {Function} Returns the new negated function.
* @example
*
* function isEven(n) {
* return n % 2 == 0;
* }
*
* _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
* // => [1, 3, 5]
*/ function negate(predicate) {
if ('function' != typeof predicate) throw new TypeError(FUNC_ERROR_TEXT);
return function() {
var args = arguments;
switch(args.length){
case 0:
return !predicate.call(this);
case 1:
return !predicate.call(this, args[0]);
case 2:
return !predicate.call(this, args[0], args[1]);
case 3:
return !predicate.call(this, args[0], args[1], args[2]);
}
return !predicate.apply(this, args);
};
}
// Expose `MapCache`.
memoize.Cache = MapCache;
/**
* Creates a function that invokes `func` with its arguments transformed.
*
* @static
* @since 4.0.0
* @memberOf _
* @category Function
* @param {Function} func The function to wrap.
* @param {...(Function|Function[])} [transforms=[_.identity]]
* The argument transforms.
* @returns {Function} Returns the new function.
* @example
*
* function doubled(n) {
* return n * 2;
* }
*
* function square(n) {
* return n * n;
* }
*
* var func = _.overArgs(function(x, y) {
* return [x, y];
* }, [square, doubled]);
*
* func(9, 3);
* // => [81, 6]
*
* func(10, 5);
* // => [100, 10]
*/ var overArgs = baseRest(function(func, transforms) {
var funcsLength = (transforms = 1 == transforms.length && isArray(transforms[0]) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee()))).length;
return baseRest(function(args) {
for(var index = -1, length = nativeMin(args.length, funcsLength); ++index < length;)args[index] = transforms[index].call(this, args[index]);
return apply(func, this, args);
});
}), partial = baseRest(function(func, partials) {
var holders = replaceHolders(partials, getHolder(partial));
return createWrap(func, 32, undefined, partials, holders);
}), partialRight = baseRest(function(func, partials) {
var holders = replaceHolders(partials, getHolder(partialRight));
return createWrap(func, 64, undefined, partials, holders);
}), rearg = flatRest(function(func, indexes) {
return createWrap(func, 256, undefined, undefined, undefined, indexes);
});
/**
* Performs a
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* comparison between two values to determine if they are equivalent.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.eq(object, object);
* // => true
*
* _.eq(object, other);
* // => false
*
* _.eq('a', 'a');
* // => true
*
* _.eq('a', Object('a'));
* // => false
*
* _.eq(NaN, NaN);
* // => true
*/ function eq(value, other) {
return value === other || value != value && other != other;
}
/**
* Checks if `value` is greater than `other`.
*
* @static
* @memberOf _
* @since 3.9.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if `value` is greater than `other`,
* else `false`.
* @see _.lt
* @example
*
* _.gt(3, 1);
* // => true
*
* _.gt(3, 3);
* // => false
*
* _.gt(1, 3);
* // => false
*/ var gt = createRelationalOperation(baseGt), gte = createRelationalOperation(function(value, other) {
return value >= other;
}), isArguments = baseIsArguments(function() {
return arguments;
}()) ? baseIsArguments : function(value) {
return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
}, isArray = Array1.isArray, isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : /**
* The base implementation of `_.isArrayBuffer` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
*/ function(value) {
return isObjectLike(value) && baseGetTag(value) == arrayBufferTag;
};
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/ function isArrayLike(value) {
return null != value && isLength(value.length) && !isFunction(value);
}
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/ function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
/**
* Checks if `value` is a buffer.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
* @example
*
* _.isBuffer(new Buffer(2));
* // => true
*
* _.isBuffer(new Uint8Array(2));
* // => false
*/ var isBuffer = nativeIsBuffer || stubFalse, isDate = nodeIsDate ? baseUnary(nodeIsDate) : /**
* The base implementation of `_.isDate` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a date object, else `false`.
*/ function(value) {
return isObjectLike(value) && baseGetTag(value) == dateTag;
};
/**
* Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
* `SyntaxError`, `TypeError`, or `URIError` object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an error object, else `false`.
* @example
*
* _.isError(new Error);
* // => true
*
* _.isError(Error);
* // => false
*/ function isError(value) {
if (!isObjectLike(value)) return !1;
var tag = baseGetTag(value);
return tag == errorTag || '[object DOMException]' == tag || 'string' == typeof value.message && 'string' == typeof value.name && !isPlainObject(value);
}
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/ function isFunction(value) {
if (!isObject(value)) return !1;
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 9 which returns 'object' for typed arrays and other constructors.
var tag = baseGetTag(value);
return tag == funcTag || tag == genTag || '[object AsyncFunction]' == tag || '[object Proxy]' == tag;
}
/**
* Checks if `value` is an integer.
*
* **Note:** This method is based on
* [`Number.isInteger`](https://mdn.io/Number/isInteger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an integer, else `false`.
* @example
*
* _.isInteger(3);
* // => true
*
* _.isInteger(Number.MIN_VALUE);
* // => false
*
* _.isInteger(Infinity);
* // => false
*
* _.isInteger('3');
* // => false
*/ function isInteger(value) {
return 'number' == typeof value && value == toInteger(value);
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/ function isLength(value) {
return 'number' == typeof value && value > -1 && value % 1 == 0 && value <= 9007199254740991;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/ function isObject(value) {
var type = typeof value;
return null != value && ('object' == type || 'function' == type);
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/ function isObjectLike(value) {
return null != value && 'object' == typeof value;
}
/**
* Checks if `value` is classified as a `Map` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
* @example
*
* _.isMap(new Map);
* // => true
*
* _.isMap(new WeakMap);
* // => false
*/ var isMap = nodeIsMap ? baseUnary(nodeIsMap) : /**
* The base implementation of `_.isMap` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a map, else `false`.
*/ function(value) {
return isObjectLike(value) && getTag(value) == mapTag;
};
/**
* Checks if `value` is classified as a `Number` primitive or object.
*
* **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
* classified as numbers, use the `_.isFinite` method.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a number, else `false`.
* @example
*
* _.isNumber(3);
* // => true
*
* _.isNumber(Number.MIN_VALUE);
* // => true
*
* _.isNumber(Infinity);
* // => true
*
* _.isNumber('3');
* // => false
*/ function isNumber(value) {
return 'number' == typeof value || isObjectLike(value) && baseGetTag(value) == numberTag;
}
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @static
* @memberOf _
* @since 0.8.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/ function isPlainObject(value) {
if (!isObjectLike(value) || baseGetTag(value) != objectTag) return !1;
var proto = getPrototype(value);
if (null === proto) return !0;
var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
return 'function' == typeof Ctor && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString;
}
/**
* Checks if `value` is classified as a `RegExp` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
* @example
*
* _.isRegExp(/abc/);
* // => true
*
* _.isRegExp('/abc/');
* // => false
*/ var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : /**
* The base implementation of `_.isRegExp` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
*/ function(value) {
return isObjectLike(value) && baseGetTag(value) == regexpTag;
}, isSet = nodeIsSet ? baseUnary(nodeIsSet) : /**
* The base implementation of `_.isSet` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a set, else `false`.
*/ function(value) {
return isObjectLike(value) && getTag(value) == setTag;
};
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a string, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/ function isString(value) {
return 'string' == typeof value || !isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag;
}
/**
* Checks if `value` is classified as a `Symbol` primitive or object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
* @example
*
* _.isSymbol(Symbol.iterator);
* // => true
*
* _.isSymbol('abc');
* // => false
*/ function isSymbol(value) {
return 'symbol' == typeof value || isObjectLike(value) && baseGetTag(value) == symbolTag;
}
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : /**
* The base implementation of `_.isTypedArray` without Node.js optimizations.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
*/ function(value) {
return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
}, lt = createRelationalOperation(baseLt), lte = createRelationalOperation(function(value, other) {
return value <= other;
});
/**
* Converts `value` to an array.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to convert.
* @returns {Array} Returns the converted array.
* @example
*
* _.toArray({ 'a': 1, 'b': 2 });
* // => [1, 2]
*
* _.toArray('abc');
* // => ['a', 'b', 'c']
*
* _.toArray(1);
* // => []
*
* _.toArray(null);
* // => []
*/ function toArray(value) {
if (!value) return [];
if (isArrayLike(value)) return isString(value) ? stringToArray(value) : copyArray(value);
if (symIterator && value[symIterator]) return(/**
* Converts `iterator` to an array.
*
* @private
* @param {Object} iterator The iterator to convert.
* @returns {Array} Returns the converted array.
*/ function(iterator) {
for(var data, result = []; !(data = iterator.next()).done;)result.push(data.value);
return result;
}(value[symIterator]()));
var tag = getTag(value);
return (tag == mapTag ? mapToArray : tag == setTag ? setToArray : values)(value);
}
/**
* Converts `value` to a finite number.
*
* @static
* @memberOf _
* @since 4.12.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted number.
* @example
*
* _.toFinite(3.2);
* // => 3.2
*
* _.toFinite(Number.MIN_VALUE);
* // => 5e-324
*
* _.toFinite(Infinity);
* // => 1.7976931348623157e+308
*
* _.toFinite('3.2');
* // => 3.2
*/ function toFinite(value) {
return value ? (value = toNumber(value)) === INFINITY || value === -INFINITY ? (value < 0 ? -1 : 1) * 1.7976931348623157e+308 : value == value ? value : 0 : 0 === value ? value : 0;
}
/**
* Converts `value` to an integer.
*
* **Note:** This method is loosely based on
* [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toInteger(3.2);
* // => 3
*
* _.toInteger(Number.MIN_VALUE);
* // => 0
*
* _.toInteger(Infinity);
* // => 1.7976931348623157e+308
*
* _.toInteger('3.2');
* // => 3
*/ function toInteger(value) {
var result = toFinite(value), remainder = result % 1;
return result == result ? remainder ? result - remainder : result : 0;
}
/**
* Converts `value` to an integer suitable for use as the length of an
* array-like object.
*
* **Note:** This method is based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toLength(3.2);
* // => 3
*
* _.toLength(Number.MIN_VALUE);
* // => 0
*
* _.toLength(Infinity);
* // => 4294967295
*
* _.toLength('3.2');
* // => 3
*/ function toLength(value) {
return value ? baseClamp(toInteger(value), 0, 4294967295) : 0;
}
/**
* Converts `value` to a number.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to process.
* @returns {number} Returns the number.
* @example
*
* _.toNumber(3.2);
* // => 3.2
*
* _.toNumber(Number.MIN_VALUE);
* // => 5e-324
*
* _.toNumber(Infinity);
* // => Infinity
*
* _.toNumber('3.2');
* // => 3.2
*/ function toNumber(value) {
if ('number' == typeof value) return value;
if (isSymbol(value)) return NAN;
if (isObject(value)) {
var other = 'function' == typeof value.valueOf ? value.valueOf() : value;
value = isObject(other) ? other + '' : other;
}
if ('string' != typeof value) return 0 === value ? value : +value;
value = baseTrim(value);
var isBinary = reIsBinary.test(value);
return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
}
/**
* Converts `value` to a plain object flattening inherited enumerable string
* keyed properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/ function toPlainObject(value) {
return copyObject(value, keysIn(value));
}
/**
* Converts `value` to a string. An empty string is returned for `null`
* and `undefined` values. The sign of `-0` is preserved.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {string} Returns the converted string.
* @example
*
* _.toString(null);
* // => ''
*
* _.toString(-0);
* // => '-0'
*
* _.toString([1, 2, 3]);
* // => '1,2,3'
*/ function toString(value) {
return null == value ? '' : baseToString(value);
}
/*------------------------------------------------------------------------*/ /**
* Assigns own enumerable string keyed properties of source objects to the
* destination object. Source objects are applied from left to right.
* Subsequent sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object` and is loosely based on
* [`Object.assign`](https://mdn.io/Object/assign).
*
* @static
* @memberOf _
* @since 0.10.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @see _.assignIn
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* function Bar() {
* this.c = 3;
* }
*
* Foo.prototype.b = 2;
* Bar.prototype.d = 4;
*
* _.assign({ 'a': 0 }, new Foo, new Bar);
* // => { 'a': 1, 'c': 3 }
*/ var assign = createAssigner(function(object, source) {
if (isPrototype(source) || isArrayLike(source)) {
copyObject(source, keys(source), object);
return;
}
for(var key in source)hasOwnProperty.call(source, key) && assignValue(object, key, source[key]);
}), assignIn = createAssigner(function(object, source) {
copyObject(source, keysIn(source), object);
}), assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
copyObject(source, keysIn(source), object, customizer);
}), assignWith = createAssigner(function(object, source, srcIndex, customizer) {
copyObject(source, keys(source), object, customizer);
}), at = flatRest(baseAt), defaults = baseRest(function(object, sources) {
object = Object1(object);
var index = -1, length = sources.length, guard = length > 2 ? sources[2] : undefined;
for(guard && isIterateeCall(sources[0], sources[1], guard) && (length = 1); ++index < length;)for(var source = sources[index], props = keysIn(source), propsIndex = -1, propsLength = props.length; ++propsIndex < propsLength;){
var key = props[propsIndex], value = object[key];
(undefined === value || eq(value, objectProto[key]) && !hasOwnProperty.call(object, key)) && (object[key] = source[key]);
}
return object;
}), defaultsDeep = baseRest(function(args) {
return args.push(undefined, customDefaultsMerge), apply(mergeWith, undefined, args);
});
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/ function get(object, path, defaultValue) {
var result = null == object ? undefined : baseGet(object, path);
return undefined === result ? defaultValue : result;
}
/**
* Checks if `path` is a direct or inherited property of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.hasIn(object, 'a');
* // => true
*
* _.hasIn(object, 'a.b');
* // => true
*
* _.hasIn(object, ['a', 'b']);
* // => true
*
* _.hasIn(object, 'b');
* // => false
*/ function hasIn(object, path) {
return null != object && hasPath(object, path, baseHasIn);
}
/**
* Creates an object composed of the inverted keys and values of `object`.
* If `object` contains duplicate values, subsequent values overwrite
* property assignments of previous values.
*
* @static
* @memberOf _
* @since 0.7.0
* @category Object
* @param {Object} object The object to invert.
* @returns {Object} Returns the new inverted object.
* @example
*
* var object = { 'a': 1, 'b': 2, 'c': 1 };
*
* _.invert(object);
* // => { '1': 'c', '2': 'b' }
*/ var invert = createInverter(function(result, value, key) {
null != value && 'function' != typeof value.toString && (value = nativeObjectToString.call(value)), result[value] = key;
}, constant(identity)), invertBy = createInverter(function(result, value, key) {
null != value && 'function' != typeof value.toString && (value = nativeObjectToString.call(value)), hasOwnProperty.call(result, value) ? result[value].push(key) : result[value] = [
key
];
}, getIteratee), invoke = baseRest(baseInvoke);
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* for more details.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/ function keys(object) {
return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
}
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/ function keysIn(object) {
return isArrayLike(object) ? arrayLikeKeys(object, !0) : /**
* The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/ function(object) {
if (!isObject(object)) return(/**
* This function is like
* [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
* except that it includes inherited enumerable properties.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/ function(object) {
var result = [];
if (null != object) for(var key in Object1(object))result.push(key);
return result;
}(object));
var isProto = isPrototype(object), result = [];
for(var key in object)'constructor' == key && (isProto || !hasOwnProperty.call(object, key)) || result.push(key);
return result;
}(object);
}
/**
* This method is like `_.assign` except that it recursively merges own and
* inherited enumerable string keyed properties of source objects into the
* destination object. Source properties that resolve to `undefined` are
* skipped if a destination value exists. Array and plain object properties
* are merged recursively. Other objects and value types are overridden by
* assignment. Source objects are applied from left to right. Subsequent
* sources overwrite property assignments of previous sources.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @returns {Object} Returns `object`.
* @example
*
* var object = {
* 'a': [{ 'b': 2 }, { 'd': 4 }]
* };
*
* var other = {
* 'a': [{ 'c': 3 }, { 'e': 5 }]
* };
*
* _.merge(object, other);
* // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
*/ var merge = createAssigner(function(object, source, srcIndex) {
baseMerge(object, source, srcIndex);
}), mergeWith = createAssigner(function(object, source, srcIndex, customizer) {
baseMerge(object, source, srcIndex, customizer);
}), omit = flatRest(function(object, paths) {
var result = {};
if (null == object) return result;
var isDeep = !1;
paths = arrayMap(paths, function(path) {
return path = castPath(path, object), isDeep || (isDeep = path.length > 1), path;
}), copyObject(object, getAllKeysIn(object), result), isDeep && (result = baseClone(result, 7, customOmitClone));
for(var length = paths.length; length--;)baseUnset(result, paths[length]);
return result;
}), pick = flatRest(function(object, paths) {
return null == object ? {} : basePickBy(object, paths, function(value, path) {
return hasIn(object, path);
});
});
/**
* Creates an object composed of the `object` properties `predicate` returns
* truthy for. The predicate is invoked with two arguments: (value, key).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The source object.
* @param {Function} [predicate=_.identity] The function invoked per property.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.pickBy(object, _.isNumber);
* // => { 'a': 1, 'c': 3 }
*/ function pickBy(object, predicate) {
if (null == object) return {};
var props = arrayMap(getAllKeysIn(object), function(prop) {
return [
prop
];
});
return predicate = getIteratee(predicate), basePickBy(object, props, function(value, path) {
return predicate(value, path[0]);
});
}
/**
* Creates an array of own enumerable string keyed-value pairs for `object`
* which can be consumed by `_.fromPairs`. If `object` is a map or set, its
* entries are returned.
*
* @static
* @memberOf _
* @since 4.0.0
* @alias entries
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the key-value pairs.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.toPairs(new Foo);
* // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
*/ var toPairs = createToPairs(keys), toPairsIn = createToPairs(keysIn);
/**
* Creates an array of the own enumerable string keyed property values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.values(new Foo);
* // => [1, 2] (iteration order is not guaranteed)
*
* _.values('hi');
* // => ['h', 'i']
*/ function values(object) {
return null == object ? [] : baseValues(object, keys(object));
}
/*------------------------------------------------------------------------*/ /**
* Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the camel cased string.
* @example
*
* _.camelCase('Foo Bar');
* // => 'fooBar'
*
* _.camelCase('--foo-bar--');
* // => 'fooBar'
*
* _.camelCase('__FOO_BAR__');
* // => 'fooBar'
*/ var camelCase = createCompounder(function(result, word, index) {
return word = word.toLowerCase(), result + (index ? capitalize(word) : word);
});
/**
* Converts the first character of `string` to upper case and the remaining
* to lower case.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to capitalize.
* @returns {string} Returns the capitalized string.
* @example
*
* _.capitalize('FRED');
* // => 'Fred'
*/ function capitalize(string) {
return upperFirst(toString(string).toLowerCase());
}
/**
* Deburrs `string` by converting
* [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
* and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
* letters to basic Latin letters and removing
* [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to deburr.
* @returns {string} Returns the deburred string.
* @example
*
* _.deburr('déjà vu');
* // => 'deja vu'
*/ function deburr(string) {
return (string = toString(string)) && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
}
/**
* Converts `string` to
* [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the kebab cased string.
* @example
*
* _.kebabCase('Foo Bar');
* // => 'foo-bar'
*
* _.kebabCase('fooBar');
* // => 'foo-bar'
*
* _.kebabCase('__FOO_BAR__');
* // => 'foo-bar'
*/ var kebabCase = createCompounder(function(result, word, index) {
return result + (index ? '-' : '') + word.toLowerCase();
}), lowerCase = createCompounder(function(result, word, index) {
return result + (index ? ' ' : '') + word.toLowerCase();
}), lowerFirst = createCaseFirst('toLowerCase'), snakeCase = createCompounder(function(result, word, index) {
return result + (index ? '_' : '') + word.toLowerCase();
}), startCase = createCompounder(function(result, word, index) {
return result + (index ? ' ' : '') + upperFirst(word);
}), upperCase = createCompounder(function(result, word, index) {
return result + (index ? ' ' : '') + word.toUpperCase();
}), upperFirst = createCaseFirst('toUpperCase');
/**
* Splits `string` into an array of its words.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {RegExp|string} [pattern] The pattern to match words.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the words of `string`.
* @example
*
* _.words('fred, barney, & pebbles');
* // => ['fred', 'barney', 'pebbles']
*
* _.words('fred, barney, & pebbles', /[^, ]+/g);
* // => ['fred', 'barney', '&', 'pebbles']
*/ function words(string, pattern, guard) {
if (string = toString(string), pattern = guard ? undefined : pattern, undefined === pattern) {
var string1;
return (string1 = string, reHasUnicodeWord.test(string1)) ? string.match(reUnicodeWord) || [] : string.match(reAsciiWord) || [];
}
return string.match(pattern) || [];
}
/*------------------------------------------------------------------------*/ /**
* Attempts to invoke `func`, returning either the result or the caught error
* object. Any additional arguments are provided to `func` when it's invoked.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {Function} func The function to attempt.
* @param {...*} [args] The arguments to invoke `func` with.
* @returns {*} Returns the `func` result or error object.
* @example
*
* // Avoid throwing errors for invalid selectors.
* var elements = _.attempt(function(selector) {
* return document.querySelectorAll(selector);
* }, '>_>');
*
* if (_.isError(elements)) {
* elements = [];
* }
*/ var attempt = baseRest(function(func, args) {
try {
return apply(func, undefined, args);
} catch (e) {
return isError(e) ? e : new Error(e);
}
}), bindAll = flatRest(function(object, methodNames) {
return arrayEach(methodNames, function(key) {
baseAssignValue(object, key = toKey(key), bind(object[key], object));
}), object;
});
/**
* Creates a function that returns `value`.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {*} value The value to return from the new function.
* @returns {Function} Returns the new constant function.
* @example
*
* var objects = _.times(2, _.constant({ 'a': 1 }));
*
* console.log(objects);
* // => [{ 'a': 1 }, { 'a': 1 }]
*
* console.log(objects[0] === objects[1]);
* // => true
*/ function constant(value) {
return function() {
return value;
};
}
/**
* Creates a function that returns the result of invoking the given functions
* with the `this` binding of the created function, where each successive
* invocation is supplied the return value of the previous.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {...(Function|Function[])} [funcs] The functions to invoke.
* @returns {Function} Returns the new composite function.
* @see _.flowRight
* @example
*
* function square(n) {
* return n * n;
* }
*
* var addSquare = _.flow([_.add, square]);
* addSquare(1, 2);
* // => 9
*/ var flow = createFlow(), flowRight = createFlow(!0);
/**
* This method returns the first argument it receives.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'a': 1 };
*
* console.log(_.identity(object) === object);
* // => true
*/ function identity(value) {
return value;
}
/**
* Creates a function that invokes `func` with the arguments of the created
* function. If `func` is a property name, the created function returns the
* property value for a given element. If `func` is an array or object, the
* created function returns `true` for elements that contain the equivalent
* source properties, otherwise it returns `false`.
*
* @static
* @since 4.0.0
* @memberOf _
* @category Util
* @param {*} [func=_.identity] The value to convert to a callback.
* @returns {Function} Returns the callback.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
* // => [{ 'user': 'barney', 'age': 36, 'active': true }]
*
* // The `_.matchesProperty` iteratee shorthand.
* _.filter(users, _.iteratee(['user', 'fred']));
* // => [{ 'user': 'fred', 'age': 40 }]
*
* // The `_.property` iteratee shorthand.
* _.map(users, _.iteratee('user'));
* // => ['barney', 'fred']
*
* // Create custom iteratee shorthands.
* _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
* return !_.isRegExp(func) ? iteratee(func) : function(string) {
* return func.test(string);
* };
* });
*
* _.filter(['abc', 'def'], /ef/);
* // => ['def']
*/ function iteratee(func) {
return baseIteratee('function' == typeof func ? func : baseClone(func, 1));
}
/**
* Creates a function that invokes the method at `path` of a given object.
* Any additional arguments are provided to the invoked method.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Util
* @param {Array|string} path The path of the method to invoke.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {Function} Returns the new invoker function.
* @example
*
* var objects = [
* { 'a': { 'b': _.constant(2) } },
* { 'a': { 'b': _.constant(1) } }
* ];
*
* _.map(objects, _.method('a.b'));
* // => [2, 1]
*
* _.map(objects, _.method(['a', 'b']));
* // => [2, 1]
*/ var method = baseRest(function(path, args) {
return function(object) {
return baseInvoke(object, path, args);
};
}), methodOf = baseRest(function(object, args) {
return function(path) {
return baseInvoke(object, path, args);
};
});
/**
* Adds all own enumerable string keyed function properties of a source
* object to the destination object. If `object` is a function, then methods
* are added to its prototype as well.
*
* **Note:** Use `_.runInContext` to create a pristine `lodash` function to
* avoid conflicts caused by modifying the original.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {Function|Object} [object=lodash] The destination object.
* @param {Object} source The object of functions to add.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.chain=true] Specify whether mixins are chainable.
* @returns {Function|Object} Returns `object`.
* @example
*
* function vowels(string) {
* return _.filter(string, function(v) {
* return /[aeiou]/i.test(v);
* });
* }
*
* _.mixin({ 'vowels': vowels });
* _.vowels('fred');
* // => ['e']
*
* _('fred').vowels().value();
* // => ['e']
*
* _.mixin({ 'vowels': vowels }, { 'chain': false });
* _('fred').vowels();
* // => ['e']
*/ function mixin(object, source, options) {
var props = keys(source), methodNames = baseFunctions(source, props);
null != options || isObject(source) && (methodNames.length || !props.length) || (options = source, source = object, object = this, methodNames = baseFunctions(source, keys(source)));
var chain = !(isObject(options) && 'chain' in options) || !!options.chain, isFunc = isFunction(object);
return arrayEach(methodNames, function(methodName) {
var func = source[methodName];
object[methodName] = func, isFunc && (object.prototype[methodName] = function() {
var chainAll = this.__chain__;
if (chain || chainAll) {
var result = object(this.__wrapped__);
return (result.__actions__ = copyArray(this.__actions__)).push({
func: func,
args: arguments,
thisArg: object
}), result.__chain__ = chainAll, result;
}
return func.apply(object, arrayPush([
this.value()
], arguments));
});
}), object;
}
/**
* This method returns `undefined`.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Util
* @example
*
* _.times(2, _.noop);
* // => [undefined, undefined]
*/ function noop() {
// No operation performed.
}
/**
* Creates a function that invokes `iteratees` with the arguments it receives
* and returns their results.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {...(Function|Function[])} [iteratees=[_.identity]]
* The iteratees to invoke.
* @returns {Function} Returns the new function.
* @example
*
* var func = _.over([Math.max, Math.min]);
*
* func(1, 2, 3, 4);
* // => [4, 1]
*/ var over = createOver(arrayMap), overEvery = createOver(arrayEvery), overSome = createOver(arraySome);
/**
* Creates a function that returns the value at `path` of a given object.
*
* @static
* @memberOf _
* @since 2.4.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @returns {Function} Returns the new accessor function.
* @example
*
* var objects = [
* { 'a': { 'b': 2 } },
* { 'a': { 'b': 1 } }
* ];
*
* _.map(objects, _.property('a.b'));
* // => [2, 1]
*
* _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
* // => [1, 2]
*/ function property(path) {
return isKey(path) ? baseProperty(toKey(path)) : function(object) {
return baseGet(object, path);
};
}
/**
* Creates an array of numbers (positive and/or negative) progressing from
* `start` up to, but not including, `end`. A step of `-1` is used if a negative
* `start` is specified without an `end` or `step`. If `end` is not specified,
* it's set to `start` with `start` then set to `0`.
*
* **Note:** JavaScript follows the IEEE-754 standard for resolving
* floating-point values which can produce unexpected results.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @param {number} [step=1] The value to increment or decrement by.
* @returns {Array} Returns the range of numbers.
* @see _.inRange, _.rangeRight
* @example
*
* _.range(4);
* // => [0, 1, 2, 3]
*
* _.range(-4);
* // => [0, -1, -2, -3]
*
* _.range(1, 5);
* // => [1, 2, 3, 4]
*
* _.range(0, 20, 5);
* // => [0, 5, 10, 15]
*
* _.range(0, -4, -1);
* // => [0, -1, -2, -3]
*
* _.range(1, 4, 0);
* // => [1, 1, 1]
*
* _.range(0);
* // => []
*/ var range = createRange(), rangeRight = createRange(!0);
/**
* This method returns a new empty array.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Array} Returns the new empty array.
* @example
*
* var arrays = _.times(2, _.stubArray);
*
* console.log(arrays);
* // => [[], []]
*
* console.log(arrays[0] === arrays[1]);
* // => false
*/ function stubArray() {
return [];
}
/**
* This method returns `false`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `false`.
* @example
*
* _.times(2, _.stubFalse);
* // => [false, false]
*/ function stubFalse() {
return !1;
}
/*------------------------------------------------------------------------*/ /**
* Adds two numbers.
*
* @static
* @memberOf _
* @since 3.4.0
* @category Math
* @param {number} augend The first number in an addition.
* @param {number} addend The second number in an addition.
* @returns {number} Returns the total.
* @example
*
* _.add(6, 4);
* // => 10
*/ var add = createMathOperation(function(augend, addend) {
return augend + addend;
}, 0), ceil = createRound('ceil'), divide = createMathOperation(function(dividend, divisor) {
return dividend / divisor;
}, 1), floor = createRound('floor'), multiply = createMathOperation(function(multiplier, multiplicand) {
return multiplier * multiplicand;
}, 1), round = createRound('round'), subtract = createMathOperation(function(minuend, subtrahend) {
return minuend - subtrahend;
}, 0);
return(/*------------------------------------------------------------------------*/ // Add methods that return wrapped values in chain sequences.
lodash.after = /*------------------------------------------------------------------------*/ /**
* The opposite of `_.before`; this method creates a function that invokes
* `func` once it's called `n` or more times.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {number} n The number of calls before `func` is invoked.
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var saves = ['profile', 'settings'];
*
* var done = _.after(saves.length, function() {
* console.log('done saving!');
* });
*
* _.forEach(saves, function(type) {
* asyncSave({ 'type': type, 'complete': done });
* });
* // => Logs 'done saving!' after the two async saves have completed.
*/ function(n, func) {
if ('function' != typeof func) throw new TypeError(FUNC_ERROR_TEXT);
return n = toInteger(n), function() {
if (--n < 1) return func.apply(this, arguments);
};
}, lodash.ary = ary, lodash.assign = assign, lodash.assignIn = assignIn, lodash.assignInWith = assignInWith, lodash.assignWith = assignWith, lodash.at = at, lodash.before = before, lodash.bind = bind, lodash.bindAll = bindAll, lodash.bindKey = bindKey, lodash.castArray = /*------------------------------------------------------------------------*/ /**
* Casts `value` as an array if it's not one.
*
* @static
* @memberOf _
* @since 4.4.0
* @category Lang
* @param {*} value The value to inspect.
* @returns {Array} Returns the cast array.
* @example
*
* _.castArray(1);
* // => [1]
*
* _.castArray({ 'a': 1 });
* // => [{ 'a': 1 }]
*
* _.castArray('abc');
* // => ['abc']
*
* _.castArray(null);
* // => [null]
*
* _.castArray(undefined);
* // => [undefined]
*
* _.castArray();
* // => []
*
* var array = [1, 2, 3];
* console.log(_.castArray(array) === array);
* // => true
*/ function() {
if (!arguments.length) return [];
var value = arguments[0];
return isArray(value) ? value : [
value
];
}, lodash.chain = chain, lodash.chunk = /*------------------------------------------------------------------------*/ /**
* Creates an array of elements split into groups the length of `size`.
* If `array` can't be split evenly, the final chunk will be the remaining
* elements.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to process.
* @param {number} [size=1] The length of each chunk
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the new array of chunks.
* @example
*
* _.chunk(['a', 'b', 'c', 'd'], 2);
* // => [['a', 'b'], ['c', 'd']]
*
* _.chunk(['a', 'b', 'c', 'd'], 3);
* // => [['a', 'b', 'c'], ['d']]
*/ function(array, size, guard) {
size = (guard ? isIterateeCall(array, size, guard) : undefined === size) ? 1 : nativeMax(toInteger(size), 0);
var length = null == array ? 0 : array.length;
if (!length || size < 1) return [];
for(var index = 0, resIndex = 0, result = Array1(nativeCeil(length / size)); index < length;)result[resIndex++] = baseSlice(array, index, index += size);
return result;
}, lodash.compact = /**
* Creates an array with all falsey values removed. The values `false`, `null`,
* `0`, `""`, `undefined`, and `NaN` are falsey.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to compact.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.compact([0, 1, false, 2, '', 3]);
* // => [1, 2, 3]
*/ function(array) {
for(var index = -1, length = null == array ? 0 : array.length, resIndex = 0, result = []; ++index < length;){
var value = array[index];
value && (result[resIndex++] = value);
}
return result;
}, lodash.concat = /**
* Creates a new array concatenating `array` with any additional arrays
* and/or values.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to concatenate.
* @param {...*} [values] The values to concatenate.
* @returns {Array} Returns the new concatenated array.
* @example
*
* var array = [1];
* var other = _.concat(array, 2, [3], [[4]]);
*
* console.log(other);
* // => [1, 2, 3, [4]]
*
* console.log(array);
* // => [1]
*/ function() {
var length = arguments.length;
if (!length) return [];
for(var args = Array1(length - 1), array = arguments[0], index = length; index--;)args[index - 1] = arguments[index];
return arrayPush(isArray(array) ? copyArray(array) : [
array
], baseFlatten(args, 1));
}, lodash.cond = /**
* Creates a function that iterates over `pairs` and invokes the corresponding
* function of the first predicate to return truthy. The predicate-function
* pairs are invoked with the `this` binding and arguments of the created
* function.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {Array} pairs The predicate-function pairs.
* @returns {Function} Returns the new composite function.
* @example
*
* var func = _.cond([
* [_.matches({ 'a': 1 }), _.constant('matches A')],
* [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
* [_.stubTrue, _.constant('no match')]
* ]);
*
* func({ 'a': 1, 'b': 2 });
* // => 'matches A'
*
* func({ 'a': 0, 'b': 1 });
* // => 'matches B'
*
* func({ 'a': '1', 'b': '2' });
* // => 'no match'
*/ function(pairs) {
var length = null == pairs ? 0 : pairs.length, toIteratee = getIteratee();
return pairs = length ? arrayMap(pairs, function(pair) {
if ('function' != typeof pair[1]) throw new TypeError(FUNC_ERROR_TEXT);
return [
toIteratee(pair[0]),
pair[1]
];
}) : [], baseRest(function(args) {
for(var index = -1; ++index < length;){
var pair = pairs[index];
if (apply(pair[0], this, args)) return apply(pair[1], this, args);
}
});
}, lodash.conforms = /**
* Creates a function that invokes the predicate properties of `source` with
* the corresponding property values of a given object, returning `true` if
* all predicates return truthy, else `false`.
*
* **Note:** The created function is equivalent to `_.conformsTo` with
* `source` partially applied.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {Object} source The object of property predicates to conform to.
* @returns {Function} Returns the new spec function.
* @example
*
* var objects = [
* { 'a': 2, 'b': 1 },
* { 'a': 1, 'b': 2 }
* ];
*
* _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } }));
* // => [{ 'a': 1, 'b': 2 }]
*/ function(source) {
var source1, props;
return props = keys(source1 = baseClone(source, 1)), function(object) {
return baseConformsTo(object, source1, props);
};
}, lodash.constant = constant, lodash.countBy = countBy, lodash.create = /**
* Creates an object that inherits from the `prototype` object. If a
* `properties` object is given, its own enumerable string keyed properties
* are assigned to the created object.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Object
* @param {Object} prototype The object to inherit from.
* @param {Object} [properties] The properties to assign to the object.
* @returns {Object} Returns the new object.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* function Circle() {
* Shape.call(this);
* }
*
* Circle.prototype = _.create(Shape.prototype, {
* 'constructor': Circle
* });
*
* var circle = new Circle;
* circle instanceof Circle;
* // => true
*
* circle instanceof Shape;
* // => true
*/ function(prototype, properties) {
var result = baseCreate(prototype);
return null == properties ? result : baseAssign(result, properties);
}, lodash.curry = curry, lodash.curryRight = curryRight, lodash.debounce = debounce, lodash.defaults = defaults, lodash.defaultsDeep = defaultsDeep, lodash.defer = defer, lodash.delay = delay, lodash.difference = difference, lodash.differenceBy = differenceBy, lodash.differenceWith = differenceWith, lodash.drop = /**
* Creates a slice of `array` with `n` elements dropped from the beginning.
*
* @static
* @memberOf _
* @since 0.5.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to drop.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.drop([1, 2, 3]);
* // => [2, 3]
*
* _.drop([1, 2, 3], 2);
* // => [3]
*
* _.drop([1, 2, 3], 5);
* // => []
*
* _.drop([1, 2, 3], 0);
* // => [1, 2, 3]
*/ function(array, n, guard) {
var length = null == array ? 0 : array.length;
return length ? baseSlice(array, (n = guard || undefined === n ? 1 : toInteger(n)) < 0 ? 0 : n, length) : [];
}, lodash.dropRight = /**
* Creates a slice of `array` with `n` elements dropped from the end.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to drop.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.dropRight([1, 2, 3]);
* // => [1, 2]
*
* _.dropRight([1, 2, 3], 2);
* // => [1]
*
* _.dropRight([1, 2, 3], 5);
* // => []
*
* _.dropRight([1, 2, 3], 0);
* // => [1, 2, 3]
*/ function(array, n, guard) {
var length = null == array ? 0 : array.length;
return length ? baseSlice(array, 0, (n = length - (n = guard || undefined === n ? 1 : toInteger(n))) < 0 ? 0 : n) : [];
}, lodash.dropRightWhile = /**
* Creates a slice of `array` excluding elements dropped from the end.
* Elements are dropped until `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.dropRightWhile(users, function(o) { return !o.active; });
* // => objects for ['barney']
*
* // The `_.matches` iteratee shorthand.
* _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });
* // => objects for ['barney', 'fred']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.dropRightWhile(users, ['active', false]);
* // => objects for ['barney']
*
* // The `_.property` iteratee shorthand.
* _.dropRightWhile(users, 'active');
* // => objects for ['barney', 'fred', 'pebbles']
*/ function(array, predicate) {
return array && array.length ? baseWhile(array, getIteratee(predicate, 3), !0, !0) : [];
}, lodash.dropWhile = /**
* Creates a slice of `array` excluding elements dropped from the beginning.
* Elements are dropped until `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.dropWhile(users, function(o) { return !o.active; });
* // => objects for ['pebbles']
*
* // The `_.matches` iteratee shorthand.
* _.dropWhile(users, { 'user': 'barney', 'active': false });
* // => objects for ['fred', 'pebbles']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.dropWhile(users, ['active', false]);
* // => objects for ['pebbles']
*
* // The `_.property` iteratee shorthand.
* _.dropWhile(users, 'active');
* // => objects for ['barney', 'fred', 'pebbles']
*/ function(array, predicate) {
return array && array.length ? baseWhile(array, getIteratee(predicate, 3), !0) : [];
}, lodash.fill = /**
* Fills elements of `array` with `value` from `start` up to, but not
* including, `end`.
*
* **Note:** This method mutates `array`.
*
* @static
* @memberOf _
* @since 3.2.0
* @category Array
* @param {Array} array The array to fill.
* @param {*} value The value to fill `array` with.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns `array`.
* @example
*
* var array = [1, 2, 3];
*
* _.fill(array, 'a');
* console.log(array);
* // => ['a', 'a', 'a']
*
* _.fill(Array(3), 2);
* // => [2, 2, 2]
*
* _.fill([4, 6, 8, 10], '*', 1, 3);
* // => [4, '*', '*', 10]
*/ function(array, value, start, end) {
var length = null == array ? 0 : array.length;
return length ? (start && 'number' != typeof start && isIterateeCall(array, value, start) && (start = 0, end = length), /**
* The base implementation of `_.fill` without an iteratee call guard.
*
* @private
* @param {Array} array The array to fill.
* @param {*} value The value to fill `array` with.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns `array`.
*/ function(array, value, start, end) {
var length = array.length;
for((start = toInteger(start)) < 0 && (start = -start > length ? 0 : length + start), (end = undefined === end || end > length ? length : toInteger(end)) < 0 && (end += length), end = start > end ? 0 : toLength(end); start < end;)array[start++] = value;
return array;
}(array, value, start, end)) : [];
}, lodash.filter = /**
* Iterates over elements of `collection`, returning an array of all elements
* `predicate` returns truthy for. The predicate is invoked with three
* arguments: (value, index|key, collection).
*
* **Note:** Unlike `_.remove`, this method returns a new array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
* @see _.reject
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': true },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* _.filter(users, function(o) { return !o.active; });
* // => objects for ['fred']
*
* // The `_.matches` iteratee shorthand.
* _.filter(users, { 'age': 36, 'active': true });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.filter(users, ['active', false]);
* // => objects for ['fred']
*
* // The `_.property` iteratee shorthand.
* _.filter(users, 'active');
* // => objects for ['barney']
*
* // Combining several predicates using `_.overEvery` or `_.overSome`.
* _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));
* // => objects for ['fred', 'barney']
*/ function(collection, predicate) {
return (isArray(collection) ? arrayFilter : baseFilter)(collection, getIteratee(predicate, 3));
}, lodash.flatMap = /**
* Creates a flattened array of values by running each element in `collection`
* thru `iteratee` and flattening the mapped results. The iteratee is invoked
* with three arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new flattened array.
* @example
*
* function duplicate(n) {
* return [n, n];
* }
*
* _.flatMap([1, 2], duplicate);
* // => [1, 1, 2, 2]
*/ function(collection, iteratee) {
return baseFlatten(map(collection, iteratee), 1);
}, lodash.flatMapDeep = /**
* This method is like `_.flatMap` except that it recursively flattens the
* mapped results.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new flattened array.
* @example
*
* function duplicate(n) {
* return [[[n, n]]];
* }
*
* _.flatMapDeep([1, 2], duplicate);
* // => [1, 1, 2, 2]
*/ function(collection, iteratee) {
return baseFlatten(map(collection, iteratee), INFINITY);
}, lodash.flatMapDepth = /**
* This method is like `_.flatMap` except that it recursively flattens the
* mapped results up to `depth` times.
*
* @static
* @memberOf _
* @since 4.7.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {number} [depth=1] The maximum recursion depth.
* @returns {Array} Returns the new flattened array.
* @example
*
* function duplicate(n) {
* return [[[n, n]]];
* }
*
* _.flatMapDepth([1, 2], duplicate, 2);
* // => [[1, 1], [2, 2]]
*/ function(collection, iteratee, depth) {
return depth = undefined === depth ? 1 : toInteger(depth), baseFlatten(map(collection, iteratee), depth);
}, lodash.flatten = flatten, lodash.flattenDeep = /**
* Recursively flattens `array`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to flatten.
* @returns {Array} Returns the new flattened array.
* @example
*
* _.flattenDeep([1, [2, [3, [4]], 5]]);
* // => [1, 2, 3, 4, 5]
*/ function(array) {
return (null == array ? 0 : array.length) ? baseFlatten(array, INFINITY) : [];
}, lodash.flattenDepth = /**
* Recursively flatten `array` up to `depth` times.
*
* @static
* @memberOf _
* @since 4.4.0
* @category Array
* @param {Array} array The array to flatten.
* @param {number} [depth=1] The maximum recursion depth.
* @returns {Array} Returns the new flattened array.
* @example
*
* var array = [1, [2, [3, [4]], 5]];
*
* _.flattenDepth(array, 1);
* // => [1, 2, [3, [4]], 5]
*
* _.flattenDepth(array, 2);
* // => [1, 2, 3, [4], 5]
*/ function(array, depth) {
return (null == array ? 0 : array.length) ? baseFlatten(array, depth = undefined === depth ? 1 : toInteger(depth)) : [];
}, lodash.flip = /**
* Creates a function that invokes `func` with arguments reversed.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Function
* @param {Function} func The function to flip arguments for.
* @returns {Function} Returns the new flipped function.
* @example
*
* var flipped = _.flip(function() {
* return _.toArray(arguments);
* });
*
* flipped('a', 'b', 'c', 'd');
* // => ['d', 'c', 'b', 'a']
*/ function(func) {
return createWrap(func, 512);
}, lodash.flow = flow, lodash.flowRight = flowRight, lodash.fromPairs = /**
* The inverse of `_.toPairs`; this method returns an object composed
* from key-value `pairs`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} pairs The key-value pairs.
* @returns {Object} Returns the new object.
* @example
*
* _.fromPairs([['a', 1], ['b', 2]]);
* // => { 'a': 1, 'b': 2 }
*/ function(pairs) {
for(var index = -1, length = null == pairs ? 0 : pairs.length, result = {}; ++index < length;){
var pair = pairs[index];
result[pair[0]] = pair[1];
}
return result;
}, lodash.functions = /**
* Creates an array of function property names from own enumerable properties
* of `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the function names.
* @see _.functionsIn
* @example
*
* function Foo() {
* this.a = _.constant('a');
* this.b = _.constant('b');
* }
*
* Foo.prototype.c = _.constant('c');
*
* _.functions(new Foo);
* // => ['a', 'b']
*/ function(object) {
return null == object ? [] : baseFunctions(object, keys(object));
}, lodash.functionsIn = /**
* Creates an array of function property names from own and inherited
* enumerable properties of `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to inspect.
* @returns {Array} Returns the function names.
* @see _.functions
* @example
*
* function Foo() {
* this.a = _.constant('a');
* this.b = _.constant('b');
* }
*
* Foo.prototype.c = _.constant('c');
*
* _.functionsIn(new Foo);
* // => ['a', 'b', 'c']
*/ function(object) {
return null == object ? [] : baseFunctions(object, keysIn(object));
}, lodash.groupBy = groupBy, lodash.initial = /**
* Gets all but the last element of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.initial([1, 2, 3]);
* // => [1, 2]
*/ function(array) {
return (null == array ? 0 : array.length) ? baseSlice(array, 0, -1) : [];
}, lodash.intersection = intersection, lodash.intersectionBy = intersectionBy, lodash.intersectionWith = intersectionWith, lodash.invert = invert, lodash.invertBy = invertBy, lodash.invokeMap = invokeMap, lodash.iteratee = iteratee, lodash.keyBy = keyBy, lodash.keys = keys, lodash.keysIn = keysIn, lodash.map = map, lodash.mapKeys = /**
* The opposite of `_.mapValues`; this method creates an object with the
* same values as `object` and keys generated by running each own enumerable
* string keyed property of `object` thru `iteratee`. The iteratee is invoked
* with three arguments: (value, key, object).
*
* @static
* @memberOf _
* @since 3.8.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapValues
* @example
*
* _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
* return key + value;
* });
* // => { 'a1': 1, 'b2': 2 }
*/ function(object, iteratee) {
var result = {};
return iteratee = getIteratee(iteratee, 3), baseForOwn(object, function(value, key, object) {
baseAssignValue(result, iteratee(value, key, object), value);
}), result;
}, lodash.mapValues = /**
* Creates an object with the same keys as `object` and values generated
* by running each own enumerable string keyed property of `object` thru
* `iteratee`. The iteratee is invoked with three arguments:
* (value, key, object).
*
* @static
* @memberOf _
* @since 2.4.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns the new mapped object.
* @see _.mapKeys
* @example
*
* var users = {
* 'fred': { 'user': 'fred', 'age': 40 },
* 'pebbles': { 'user': 'pebbles', 'age': 1 }
* };
*
* _.mapValues(users, function(o) { return o.age; });
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*
* // The `_.property` iteratee shorthand.
* _.mapValues(users, 'age');
* // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
*/ function(object, iteratee) {
var result = {};
return iteratee = getIteratee(iteratee, 3), baseForOwn(object, function(value, key, object) {
baseAssignValue(result, key, iteratee(value, key, object));
}), result;
}, lodash.matches = /**
* Creates a function that performs a partial deep comparison between a given
* object and `source`, returning `true` if the given object has equivalent
* property values, else `false`.
*
* **Note:** The created function is equivalent to `_.isMatch` with `source`
* partially applied.
*
* Partial comparisons will match empty array and empty object `source`
* values against any array or object value, respectively. See `_.isEqual`
* for a list of supported value comparisons.
*
* **Note:** Multiple values can be checked by combining several matchers
* using `_.overSome`
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {Object} source The object of property values to match.
* @returns {Function} Returns the new spec function.
* @example
*
* var objects = [
* { 'a': 1, 'b': 2, 'c': 3 },
* { 'a': 4, 'b': 5, 'c': 6 }
* ];
*
* _.filter(objects, _.matches({ 'a': 4, 'c': 6 }));
* // => [{ 'a': 4, 'b': 5, 'c': 6 }]
*
* // Checking for several possible values
* _.filter(objects, _.overSome([_.matches({ 'a': 1 }), _.matches({ 'a': 4 })]));
* // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]
*/ function(source) {
return baseMatches(baseClone(source, 1));
}, lodash.matchesProperty = /**
* Creates a function that performs a partial deep comparison between the
* value at `path` of a given object to `srcValue`, returning `true` if the
* object value is equivalent, else `false`.
*
* **Note:** Partial comparisons will match empty array and empty object
* `srcValue` values against any array or object value, respectively. See
* `_.isEqual` for a list of supported value comparisons.
*
* **Note:** Multiple values can be checked by combining several matchers
* using `_.overSome`
*
* @static
* @memberOf _
* @since 3.2.0
* @category Util
* @param {Array|string} path The path of the property to get.
* @param {*} srcValue The value to match.
* @returns {Function} Returns the new spec function.
* @example
*
* var objects = [
* { 'a': 1, 'b': 2, 'c': 3 },
* { 'a': 4, 'b': 5, 'c': 6 }
* ];
*
* _.find(objects, _.matchesProperty('a', 4));
* // => { 'a': 4, 'b': 5, 'c': 6 }
*
* // Checking for several possible values
* _.filter(objects, _.overSome([_.matchesProperty('a', 1), _.matchesProperty('a', 4)]));
* // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]
*/ function(path, srcValue) {
return baseMatchesProperty(path, baseClone(srcValue, 1));
}, lodash.memoize = memoize, lodash.merge = merge, lodash.mergeWith = mergeWith, lodash.method = method, lodash.methodOf = methodOf, lodash.mixin = mixin, lodash.negate = negate, lodash.nthArg = /**
* Creates a function that gets the argument at index `n`. If `n` is negative,
* the nth argument from the end is returned.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {number} [n=0] The index of the argument to return.
* @returns {Function} Returns the new pass-thru function.
* @example
*
* var func = _.nthArg(1);
* func('a', 'b', 'c', 'd');
* // => 'b'
*
* var func = _.nthArg(-2);
* func('a', 'b', 'c', 'd');
* // => 'c'
*/ function(n) {
return n = toInteger(n), baseRest(function(args) {
return baseNth(args, n);
});
}, lodash.omit = omit, lodash.omitBy = /**
* The opposite of `_.pickBy`; this method creates an object composed of
* the own and inherited enumerable string keyed properties of `object` that
* `predicate` doesn't return truthy for. The predicate is invoked with two
* arguments: (value, key).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The source object.
* @param {Function} [predicate=_.identity] The function invoked per property.
* @returns {Object} Returns the new object.
* @example
*
* var object = { 'a': 1, 'b': '2', 'c': 3 };
*
* _.omitBy(object, _.isNumber);
* // => { 'b': '2' }
*/ function(object, predicate) {
return pickBy(object, negate(getIteratee(predicate)));
}, lodash.once = /**
* Creates a function that is restricted to invoking `func` once. Repeat calls
* to the function return the value of the first invocation. The `func` is
* invoked with the `this` binding and arguments of the created function.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to restrict.
* @returns {Function} Returns the new restricted function.
* @example
*
* var initialize = _.once(createApplication);
* initialize();
* initialize();
* // => `createApplication` is invoked once
*/ function(func) {
return before(2, func);
}, lodash.orderBy = /**
* This method is like `_.sortBy` except that it allows specifying the sort
* orders of the iteratees to sort by. If `orders` is unspecified, all values
* are sorted in ascending order. Otherwise, specify an order of "desc" for
* descending or "asc" for ascending sort order of corresponding values.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
* The iteratees to sort by.
* @param {string[]} [orders] The sort orders of `iteratees`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 34 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'barney', 'age': 36 }
* ];
*
* // Sort by `user` in ascending order and by `age` in descending order.
* _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
*/ function(collection, iteratees, orders, guard) {
return null == collection ? [] : (isArray(iteratees) || (iteratees = null == iteratees ? [] : [
iteratees
]), isArray(orders = guard ? undefined : orders) || (orders = null == orders ? [] : [
orders
]), baseOrderBy(collection, iteratees, orders));
}, lodash.over = over, lodash.overArgs = overArgs, lodash.overEvery = overEvery, lodash.overSome = overSome, lodash.partial = partial, lodash.partialRight = partialRight, lodash.partition = partition, lodash.pick = pick, lodash.pickBy = pickBy, lodash.property = property, lodash.propertyOf = /**
* The opposite of `_.property`; this method creates a function that returns
* the value at a given path of `object`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Util
* @param {Object} object The object to query.
* @returns {Function} Returns the new accessor function.
* @example
*
* var array = [0, 1, 2],
* object = { 'a': array, 'b': array, 'c': array };
*
* _.map(['a[2]', 'c[0]'], _.propertyOf(object));
* // => [2, 0]
*
* _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
* // => [2, 0]
*/ function(object) {
return function(path) {
return null == object ? undefined : baseGet(object, path);
};
}, lodash.pull = pull, lodash.pullAll = pullAll, lodash.pullAllBy = /**
* This method is like `_.pullAll` except that it accepts `iteratee` which is
* invoked for each element of `array` and `values` to generate the criterion
* by which they're compared. The iteratee is invoked with one argument: (value).
*
* **Note:** Unlike `_.differenceBy`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns `array`.
* @example
*
* var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
*
* _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');
* console.log(array);
* // => [{ 'x': 2 }]
*/ function(array, values, iteratee) {
return array && array.length && values && values.length ? basePullAll(array, values, getIteratee(iteratee, 2)) : array;
}, lodash.pullAllWith = /**
* This method is like `_.pullAll` except that it accepts `comparator` which
* is invoked to compare elements of `array` to `values`. The comparator is
* invoked with two arguments: (arrVal, othVal).
*
* **Note:** Unlike `_.differenceWith`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.6.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns `array`.
* @example
*
* var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];
*
* _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);
* console.log(array);
* // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]
*/ function(array, values, comparator) {
return array && array.length && values && values.length ? basePullAll(array, values, undefined, comparator) : array;
}, lodash.pullAt = pullAt, lodash.range = range, lodash.rangeRight = rangeRight, lodash.rearg = rearg, lodash.reject = /**
* The opposite of `_.filter`; this method returns the elements of `collection`
* that `predicate` does **not** return truthy for.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new filtered array.
* @see _.filter
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': true }
* ];
*
* _.reject(users, function(o) { return !o.active; });
* // => objects for ['fred']
*
* // The `_.matches` iteratee shorthand.
* _.reject(users, { 'age': 40, 'active': true });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.reject(users, ['active', false]);
* // => objects for ['fred']
*
* // The `_.property` iteratee shorthand.
* _.reject(users, 'active');
* // => objects for ['barney']
*/ function(collection, predicate) {
return (isArray(collection) ? arrayFilter : baseFilter)(collection, negate(getIteratee(predicate, 3)));
}, lodash.remove = /**
* Removes all elements from `array` that `predicate` returns truthy for
* and returns an array of the removed elements. The predicate is invoked
* with three arguments: (value, index, array).
*
* **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
* to pull elements from an array by value.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* var array = [1, 2, 3, 4];
* var evens = _.remove(array, function(n) {
* return n % 2 == 0;
* });
*
* console.log(array);
* // => [1, 3]
*
* console.log(evens);
* // => [2, 4]
*/ function(array, predicate) {
var result = [];
if (!(array && array.length)) return result;
var index = -1, indexes = [], length = array.length;
for(predicate = getIteratee(predicate, 3); ++index < length;){
var value = array[index];
predicate(value, index, array) && (result.push(value), indexes.push(index));
}
return basePullAt(array, indexes), result;
}, lodash.rest = /**
* Creates a function that invokes `func` with the `this` binding of the
* created function and arguments from `start` and beyond provided as
* an array.
*
* **Note:** This method is based on the
* [rest parameter](https://mdn.io/rest_parameters).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Function
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.rest(function(what, names) {
* return what + ' ' + _.initial(names).join(', ') +
* (_.size(names) > 1 ? ', & ' : '') + _.last(names);
* });
*
* say('hello', 'fred', 'barney', 'pebbles');
* // => 'hello fred, barney, & pebbles'
*/ function(func, start) {
if ('function' != typeof func) throw new TypeError(FUNC_ERROR_TEXT);
return baseRest(func, start = undefined === start ? start : toInteger(start));
}, lodash.reverse = reverse, lodash.sampleSize = /**
* Gets `n` random elements at unique keys from `collection` up to the
* size of `collection`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to sample.
* @param {number} [n=1] The number of elements to sample.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the random elements.
* @example
*
* _.sampleSize([1, 2, 3], 2);
* // => [3, 1]
*
* _.sampleSize([1, 2, 3], 4);
* // => [2, 3, 1]
*/ function(collection, n, guard) {
return n = (guard ? isIterateeCall(collection, n, guard) : undefined === n) ? 1 : toInteger(n), (isArray(collection) ? /**
* A specialized version of `_.sampleSize` for arrays.
*
* @private
* @param {Array} array The array to sample.
* @param {number} n The number of elements to sample.
* @returns {Array} Returns the random elements.
*/ function(array, n) {
return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length));
} : /**
* The base implementation of `_.sampleSize` without param guards.
*
* @private
* @param {Array|Object} collection The collection to sample.
* @param {number} n The number of elements to sample.
* @returns {Array} Returns the random elements.
*/ function(collection, n) {
var array = values(collection);
return shuffleSelf(array, baseClamp(n, 0, array.length));
})(collection, n);
}, lodash.set = /**
* Sets the value at `path` of `object`. If a portion of `path` doesn't exist,
* it's created. Arrays are created for missing index properties while objects
* are created for all other missing properties. Use `_.setWith` to customize
* `path` creation.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @returns {Object} Returns `object`.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.set(object, 'a[0].b.c', 4);
* console.log(object.a[0].b.c);
* // => 4
*
* _.set(object, ['x', '0', 'y', 'z'], 5);
* console.log(object.x[0].y.z);
* // => 5
*/ function(object, path, value) {
return null == object ? object : baseSet(object, path, value);
}, lodash.setWith = /**
* This method is like `_.set` except that it accepts `customizer` which is
* invoked to produce the objects of `path`. If `customizer` returns `undefined`
* path creation is handled by the method instead. The `customizer` is invoked
* with three arguments: (nsValue, key, nsObject).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {*} value The value to set.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @example
*
* var object = {};
*
* _.setWith(object, '[0][1]', 'a', Object);
* // => { '0': { '1': 'a' } }
*/ function(object, path, value, customizer) {
return customizer = 'function' == typeof customizer ? customizer : undefined, null == object ? object : baseSet(object, path, value, customizer);
}, lodash.shuffle = /**
* Creates an array of shuffled values, using a version of the
* [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to shuffle.
* @returns {Array} Returns the new shuffled array.
* @example
*
* _.shuffle([1, 2, 3, 4]);
* // => [4, 1, 3, 2]
*/ function(collection) {
return (isArray(collection) ? /**
* A specialized version of `_.shuffle` for arrays.
*
* @private
* @param {Array} array The array to shuffle.
* @returns {Array} Returns the new shuffled array.
*/ function(array) {
return shuffleSelf(copyArray(array));
} : /**
* The base implementation of `_.shuffle`.
*
* @private
* @param {Array|Object} collection The collection to shuffle.
* @returns {Array} Returns the new shuffled array.
*/ function(collection) {
return shuffleSelf(values(collection));
})(collection);
}, lodash.slice = /**
* Creates a slice of `array` from `start` up to, but not including, `end`.
*
* **Note:** This method is used instead of
* [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are
* returned.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to slice.
* @param {number} [start=0] The start position.
* @param {number} [end=array.length] The end position.
* @returns {Array} Returns the slice of `array`.
*/ function(array, start, end) {
var length = null == array ? 0 : array.length;
return length ? (end && 'number' != typeof end && isIterateeCall(array, start, end) ? (start = 0, end = length) : (start = null == start ? 0 : toInteger(start), end = undefined === end ? length : toInteger(end)), baseSlice(array, start, end)) : [];
}, lodash.sortBy = sortBy, lodash.sortedUniq = /**
* This method is like `_.uniq` except that it's designed and optimized
* for sorted arrays.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.sortedUniq([1, 1, 2]);
* // => [1, 2]
*/ function(array) {
return array && array.length ? baseSortedUniq(array) : [];
}, lodash.sortedUniqBy = /**
* This method is like `_.uniqBy` except that it's designed and optimized
* for sorted arrays.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [iteratee] The iteratee invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);
* // => [1.1, 2.3]
*/ function(array, iteratee) {
return array && array.length ? baseSortedUniq(array, getIteratee(iteratee, 2)) : [];
}, lodash.split = /**
* Splits `string` by `separator`.
*
* **Note:** This method is based on
* [`String#split`](https://mdn.io/String/split).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to split.
* @param {RegExp|string} separator The separator pattern to split by.
* @param {number} [limit] The length to truncate results to.
* @returns {Array} Returns the string segments.
* @example
*
* _.split('a-b-c', '-', 2);
* // => ['a', 'b']
*/ function(string, separator, limit) {
return (limit && 'number' != typeof limit && isIterateeCall(string, separator, limit) && (separator = limit = undefined), limit = undefined === limit ? 4294967295 : limit >>> 0) ? (string = toString(string)) && ('string' == typeof separator || null != separator && !isRegExp(separator)) && !(separator = baseToString(separator)) && hasUnicode(string) ? castSlice(stringToArray(string), 0, limit) : string.split(separator, limit) : [];
}, lodash.spread = /**
* Creates a function that invokes `func` with the `this` binding of the
* create function and an array of arguments much like
* [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply).
*
* **Note:** This method is based on the
* [spread operator](https://mdn.io/spread_operator).
*
* @static
* @memberOf _
* @since 3.2.0
* @category Function
* @param {Function} func The function to spread arguments over.
* @param {number} [start=0] The start position of the spread.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.spread(function(who, what) {
* return who + ' says ' + what;
* });
*
* say(['fred', 'hello']);
* // => 'fred says hello'
*
* var numbers = Promise.all([
* Promise.resolve(40),
* Promise.resolve(36)
* ]);
*
* numbers.then(_.spread(function(x, y) {
* return x + y;
* }));
* // => a Promise of 76
*/ function(func, start) {
if ('function' != typeof func) throw new TypeError(FUNC_ERROR_TEXT);
return start = null == start ? 0 : nativeMax(toInteger(start), 0), baseRest(function(args) {
var array = args[start], otherArgs = castSlice(args, 0, start);
return array && arrayPush(otherArgs, array), apply(func, this, otherArgs);
});
}, lodash.tail = /**
* Gets all but the first element of `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to query.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.tail([1, 2, 3]);
* // => [2, 3]
*/ function(array) {
var length = null == array ? 0 : array.length;
return length ? baseSlice(array, 1, length) : [];
}, lodash.take = /**
* Creates a slice of `array` with `n` elements taken from the beginning.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to take.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.take([1, 2, 3]);
* // => [1]
*
* _.take([1, 2, 3], 2);
* // => [1, 2]
*
* _.take([1, 2, 3], 5);
* // => [1, 2, 3]
*
* _.take([1, 2, 3], 0);
* // => []
*/ function(array, n, guard) {
return array && array.length ? baseSlice(array, 0, (n = guard || undefined === n ? 1 : toInteger(n)) < 0 ? 0 : n) : [];
}, lodash.takeRight = /**
* Creates a slice of `array` with `n` elements taken from the end.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to take.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.takeRight([1, 2, 3]);
* // => [3]
*
* _.takeRight([1, 2, 3], 2);
* // => [2, 3]
*
* _.takeRight([1, 2, 3], 5);
* // => [1, 2, 3]
*
* _.takeRight([1, 2, 3], 0);
* // => []
*/ function(array, n, guard) {
var length = null == array ? 0 : array.length;
return length ? baseSlice(array, (n = length - (n = guard || undefined === n ? 1 : toInteger(n))) < 0 ? 0 : n, length) : [];
}, lodash.takeRightWhile = /**
* Creates a slice of `array` with elements taken from the end. Elements are
* taken until `predicate` returns falsey. The predicate is invoked with
* three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': false }
* ];
*
* _.takeRightWhile(users, function(o) { return !o.active; });
* // => objects for ['fred', 'pebbles']
*
* // The `_.matches` iteratee shorthand.
* _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });
* // => objects for ['pebbles']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.takeRightWhile(users, ['active', false]);
* // => objects for ['fred', 'pebbles']
*
* // The `_.property` iteratee shorthand.
* _.takeRightWhile(users, 'active');
* // => []
*/ function(array, predicate) {
return array && array.length ? baseWhile(array, getIteratee(predicate, 3), !1, !0) : [];
}, lodash.takeWhile = /**
* Creates a slice of `array` with elements taken from the beginning. Elements
* are taken until `predicate` returns falsey. The predicate is invoked with
* three arguments: (value, index, array).
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {Array} Returns the slice of `array`.
* @example
*
* var users = [
* { 'user': 'barney', 'active': false },
* { 'user': 'fred', 'active': false },
* { 'user': 'pebbles', 'active': true }
* ];
*
* _.takeWhile(users, function(o) { return !o.active; });
* // => objects for ['barney', 'fred']
*
* // The `_.matches` iteratee shorthand.
* _.takeWhile(users, { 'user': 'barney', 'active': false });
* // => objects for ['barney']
*
* // The `_.matchesProperty` iteratee shorthand.
* _.takeWhile(users, ['active', false]);
* // => objects for ['barney', 'fred']
*
* // The `_.property` iteratee shorthand.
* _.takeWhile(users, 'active');
* // => []
*/ function(array, predicate) {
return array && array.length ? baseWhile(array, getIteratee(predicate, 3)) : [];
}, lodash.tap = /**
* This method invokes `interceptor` and returns `value`. The interceptor
* is invoked with one argument; (value). The purpose of this method is to
* "tap into" a method chain sequence in order to modify intermediate results.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Seq
* @param {*} value The value to provide to `interceptor`.
* @param {Function} interceptor The function to invoke.
* @returns {*} Returns `value`.
* @example
*
* _([1, 2, 3])
* .tap(function(array) {
* // Mutate input array.
* array.pop();
* })
* .reverse()
* .value();
* // => [2, 1]
*/ function(value, interceptor) {
return interceptor(value), value;
}, lodash.throttle = /**
* Creates a throttled function that only invokes `func` at most once per
* every `wait` milliseconds. The throttled function comes with a `cancel`
* method to cancel delayed `func` invocations and a `flush` method to
* immediately invoke them. Provide `options` to indicate whether `func`
* should be invoked on the leading and/or trailing edge of the `wait`
* timeout. The `func` is invoked with the last arguments provided to the
* throttled function. Subsequent calls to the throttled function return the
* result of the last `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is
* invoked on the trailing edge of the timeout only if the throttled function
* is invoked more than once during the `wait` timeout.
*
* If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
* until to the next tick, similar to `setTimeout` with a timeout of `0`.
*
* See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
* for details over the differences between `_.throttle` and `_.debounce`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {Function} func The function to throttle.
* @param {number} [wait=0] The number of milliseconds to throttle invocations to.
* @param {Object} [options={}] The options object.
* @param {boolean} [options.leading=true]
* Specify invoking on the leading edge of the timeout.
* @param {boolean} [options.trailing=true]
* Specify invoking on the trailing edge of the timeout.
* @returns {Function} Returns the new throttled function.
* @example
*
* // Avoid excessively updating the position while scrolling.
* jQuery(window).on('scroll', _.throttle(updatePosition, 100));
*
* // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
* var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
* jQuery(element).on('click', throttled);
*
* // Cancel the trailing throttled invocation.
* jQuery(window).on('popstate', throttled.cancel);
*/ function(func, wait, options) {
var leading = !0, trailing = !0;
if ('function' != typeof func) throw new TypeError(FUNC_ERROR_TEXT);
return isObject(options) && (leading = 'leading' in options ? !!options.leading : leading, trailing = 'trailing' in options ? !!options.trailing : trailing), debounce(func, wait, {
leading: leading,
maxWait: wait,
trailing: trailing
});
}, lodash.thru = thru, lodash.toArray = toArray, lodash.toPairs = toPairs, lodash.toPairsIn = toPairsIn, lodash.toPath = /**
* Converts `value` to a property path array.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {*} value The value to convert.
* @returns {Array} Returns the new property path array.
* @example
*
* _.toPath('a.b.c');
* // => ['a', 'b', 'c']
*
* _.toPath('a[0].b.c');
* // => ['a', '0', 'b', 'c']
*/ function(value) {
return isArray(value) ? arrayMap(value, toKey) : isSymbol(value) ? [
value
] : copyArray(stringToPath(toString(value)));
}, lodash.toPlainObject = toPlainObject, lodash.transform = /**
* An alternative to `_.reduce`; this method transforms `object` to a new
* `accumulator` object which is the result of running each of its own
* enumerable string keyed properties thru `iteratee`, with each invocation
* potentially mutating the `accumulator` object. If `accumulator` is not
* provided, a new object with the same `[[Prototype]]` will be used. The
* iteratee is invoked with four arguments: (accumulator, value, key, object).
* Iteratee functions may exit iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 1.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The custom accumulator value.
* @returns {*} Returns the accumulated value.
* @example
*
* _.transform([2, 3, 4], function(result, n) {
* result.push(n *= n);
* return n % 2 == 0;
* }, []);
* // => [4, 9]
*
* _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
* (result[value] || (result[value] = [])).push(key);
* }, {});
* // => { '1': ['a', 'c'], '2': ['b'] }
*/ function(object, iteratee, accumulator) {
var isArr = isArray(object), isArrLike = isArr || isBuffer(object) || isTypedArray(object);
if (iteratee = getIteratee(iteratee, 4), null == accumulator) {
var Ctor = object && object.constructor;
accumulator = isArrLike ? isArr ? new Ctor : [] : isObject(object) && isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};
}
return (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {
return iteratee(accumulator, value, index, object);
}), accumulator;
}, lodash.unary = /**
* Creates a function that accepts up to one argument, ignoring any
* additional arguments.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Function
* @param {Function} func The function to cap arguments for.
* @returns {Function} Returns the new capped function.
* @example
*
* _.map(['6', '8', '10'], _.unary(parseInt));
* // => [6, 8, 10]
*/ function(func) {
return ary(func, 1);
}, lodash.union = union, lodash.unionBy = unionBy, lodash.unionWith = unionWith, lodash.uniq = /**
* Creates a duplicate-free version of an array, using
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons, in which only the first occurrence of each element
* is kept. The order of result values is determined by the order they occur
* in the array.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.uniq([2, 1, 2]);
* // => [2, 1]
*/ function(array) {
return array && array.length ? baseUniq(array) : [];
}, lodash.uniqBy = /**
* This method is like `_.uniq` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the criterion by which
* uniqueness is computed. The order of result values is determined by the
* order they occur in the array. The iteratee is invoked with one argument:
* (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* _.uniqBy([2.1, 1.2, 2.3], Math.floor);
* // => [2.1, 1.2]
*
* // The `_.property` iteratee shorthand.
* _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }, { 'x': 2 }]
*/ function(array, iteratee) {
return array && array.length ? baseUniq(array, getIteratee(iteratee, 2)) : [];
}, lodash.uniqWith = /**
* This method is like `_.uniq` except that it accepts `comparator` which
* is invoked to compare elements of `array`. The order of result values is
* determined by the order they occur in the array.The comparator is invoked
* with two arguments: (arrVal, othVal).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new duplicate free array.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
*
* _.uniqWith(objects, _.isEqual);
* // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
*/ function(array, comparator) {
return comparator = 'function' == typeof comparator ? comparator : undefined, array && array.length ? baseUniq(array, undefined, comparator) : [];
}, lodash.unset = /**
* Removes the property at `path` of `object`.
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to unset.
* @returns {boolean} Returns `true` if the property is deleted, else `false`.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 7 } }] };
* _.unset(object, 'a[0].b.c');
* // => true
*
* console.log(object);
* // => { 'a': [{ 'b': {} }] };
*
* _.unset(object, ['a', '0', 'b', 'c']);
* // => true
*
* console.log(object);
* // => { 'a': [{ 'b': {} }] };
*/ function(object, path) {
return null == object || baseUnset(object, path);
}, lodash.unzip = unzip, lodash.unzipWith = unzipWith, lodash.update = /**
* This method is like `_.set` except that accepts `updater` to produce the
* value to set. Use `_.updateWith` to customize `path` creation. The `updater`
* is invoked with one argument: (value).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.6.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {Function} updater The function to produce the updated value.
* @returns {Object} Returns `object`.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.update(object, 'a[0].b.c', function(n) { return n * n; });
* console.log(object.a[0].b.c);
* // => 9
*
* _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });
* console.log(object.x[0].y.z);
* // => 0
*/ function(object, path, updater) {
return null == object ? object : baseUpdate(object, path, castFunction(updater));
}, lodash.updateWith = /**
* This method is like `_.update` except that it accepts `customizer` which is
* invoked to produce the objects of `path`. If `customizer` returns `undefined`
* path creation is handled by the method instead. The `customizer` is invoked
* with three arguments: (nsValue, key, nsObject).
*
* **Note:** This method mutates `object`.
*
* @static
* @memberOf _
* @since 4.6.0
* @category Object
* @param {Object} object The object to modify.
* @param {Array|string} path The path of the property to set.
* @param {Function} updater The function to produce the updated value.
* @param {Function} [customizer] The function to customize assigned values.
* @returns {Object} Returns `object`.
* @example
*
* var object = {};
*
* _.updateWith(object, '[0][1]', _.constant('a'), Object);
* // => { '0': { '1': 'a' } }
*/ function(object, path, updater, customizer) {
return customizer = 'function' == typeof customizer ? customizer : undefined, null == object ? object : baseUpdate(object, path, castFunction(updater), customizer);
}, lodash.values = values, lodash.valuesIn = /**
* Creates an array of the own and inherited enumerable string keyed property
* values of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property values.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.valuesIn(new Foo);
* // => [1, 2, 3] (iteration order is not guaranteed)
*/ function(object) {
return null == object ? [] : baseValues(object, keysIn(object));
}, lodash.without = without, lodash.words = words, lodash.wrap = /**
* Creates a function that provides `value` to `wrapper` as its first
* argument. Any additional arguments provided to the function are appended
* to those provided to the `wrapper`. The wrapper is invoked with the `this`
* binding of the created function.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Function
* @param {*} value The value to wrap.
* @param {Function} [wrapper=identity] The wrapper function.
* @returns {Function} Returns the new function.
* @example
*
* var p = _.wrap(_.escape, function(func, text) {
* return '<p>' + func(text) + '</p>';
* });
*
* p('fred, barney, & pebbles');
* // => '<p>fred, barney, & pebbles</p>'
*/ function(value, wrapper) {
return partial(castFunction(wrapper), value);
}, lodash.xor = xor, lodash.xorBy = xorBy, lodash.xorWith = xorWith, lodash.zip = zip, lodash.zipObject = /**
* This method is like `_.fromPairs` except that it accepts two arrays,
* one of property identifiers and one of corresponding values.
*
* @static
* @memberOf _
* @since 0.4.0
* @category Array
* @param {Array} [props=[]] The property identifiers.
* @param {Array} [values=[]] The property values.
* @returns {Object} Returns the new object.
* @example
*
* _.zipObject(['a', 'b'], [1, 2]);
* // => { 'a': 1, 'b': 2 }
*/ function(props, values) {
return baseZipObject(props || [], values || [], assignValue);
}, lodash.zipObjectDeep = /**
* This method is like `_.zipObject` except that it supports property paths.
*
* @static
* @memberOf _
* @since 4.1.0
* @category Array
* @param {Array} [props=[]] The property identifiers.
* @param {Array} [values=[]] The property values.
* @returns {Object} Returns the new object.
* @example
*
* _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);
* // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }
*/ function(props, values) {
return baseZipObject(props || [], values || [], baseSet);
}, lodash.zipWith = zipWith, // Add aliases.
lodash.entries = toPairs, lodash.entriesIn = toPairsIn, lodash.extend = assignIn, lodash.extendWith = assignInWith, // Add methods to `lodash.prototype`.
mixin(lodash, lodash), /*------------------------------------------------------------------------*/ // Add methods that return unwrapped values in chain sequences.
lodash.add = add, lodash.attempt = attempt, lodash.camelCase = camelCase, lodash.capitalize = capitalize, lodash.ceil = ceil, lodash.clamp = /*------------------------------------------------------------------------*/ /**
* Clamps `number` within the inclusive `lower` and `upper` bounds.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Number
* @param {number} number The number to clamp.
* @param {number} [lower] The lower bound.
* @param {number} upper The upper bound.
* @returns {number} Returns the clamped number.
* @example
*
* _.clamp(-10, -5, 5);
* // => -5
*
* _.clamp(10, -5, 5);
* // => 5
*/ function(number, lower, upper) {
return undefined === upper && (upper = lower, lower = undefined), undefined !== upper && (upper = (upper = toNumber(upper)) == upper ? upper : 0), undefined !== lower && (lower = (lower = toNumber(lower)) == lower ? lower : 0), baseClamp(toNumber(number), lower, upper);
}, lodash.clone = /**
* Creates a shallow clone of `value`.
*
* **Note:** This method is loosely based on the
* [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
* and supports cloning arrays, array buffers, booleans, date objects, maps,
* numbers, `Object` objects, regexes, sets, strings, symbols, and typed
* arrays. The own enumerable properties of `arguments` objects are cloned
* as plain objects. An empty object is returned for uncloneable values such
* as error objects, functions, DOM nodes, and WeakMaps.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to clone.
* @returns {*} Returns the cloned value.
* @see _.cloneDeep
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var shallow = _.clone(objects);
* console.log(shallow[0] === objects[0]);
* // => true
*/ function(value) {
return baseClone(value, 4);
}, lodash.cloneDeep = /**
* This method is like `_.clone` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @since 1.0.0
* @category Lang
* @param {*} value The value to recursively clone.
* @returns {*} Returns the deep cloned value.
* @see _.clone
* @example
*
* var objects = [{ 'a': 1 }, { 'b': 2 }];
*
* var deep = _.cloneDeep(objects);
* console.log(deep[0] === objects[0]);
* // => false
*/ function(value) {
return baseClone(value, 5);
}, lodash.cloneDeepWith = /**
* This method is like `_.cloneWith` except that it recursively clones `value`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to recursively clone.
* @param {Function} [customizer] The function to customize cloning.
* @returns {*} Returns the deep cloned value.
* @see _.cloneWith
* @example
*
* function customizer(value) {
* if (_.isElement(value)) {
* return value.cloneNode(true);
* }
* }
*
* var el = _.cloneDeepWith(document.body, customizer);
*
* console.log(el === document.body);
* // => false
* console.log(el.nodeName);
* // => 'BODY'
* console.log(el.childNodes.length);
* // => 20
*/ function(value, customizer) {
return baseClone(value, 5, customizer = 'function' == typeof customizer ? customizer : undefined);
}, lodash.cloneWith = /**
* This method is like `_.clone` except that it accepts `customizer` which
* is invoked to produce the cloned value. If `customizer` returns `undefined`,
* cloning is handled by the method instead. The `customizer` is invoked with
* up to four arguments; (value [, index|key, object, stack]).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to clone.
* @param {Function} [customizer] The function to customize cloning.
* @returns {*} Returns the cloned value.
* @see _.cloneDeepWith
* @example
*
* function customizer(value) {
* if (_.isElement(value)) {
* return value.cloneNode(false);
* }
* }
*
* var el = _.cloneWith(document.body, customizer);
*
* console.log(el === document.body);
* // => false
* console.log(el.nodeName);
* // => 'BODY'
* console.log(el.childNodes.length);
* // => 0
*/ function(value, customizer) {
return baseClone(value, 4, customizer = 'function' == typeof customizer ? customizer : undefined);
}, lodash.conformsTo = /**
* Checks if `object` conforms to `source` by invoking the predicate
* properties of `source` with the corresponding property values of `object`.
*
* **Note:** This method is equivalent to `_.conforms` when `source` is
* partially applied.
*
* @static
* @memberOf _
* @since 4.14.0
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property predicates to conform to.
* @returns {boolean} Returns `true` if `object` conforms, else `false`.
* @example
*
* var object = { 'a': 1, 'b': 2 };
*
* _.conformsTo(object, { 'b': function(n) { return n > 1; } });
* // => true
*
* _.conformsTo(object, { 'b': function(n) { return n > 2; } });
* // => false
*/ function(object, source) {
return null == source || baseConformsTo(object, source, keys(source));
}, lodash.deburr = deburr, lodash.defaultTo = /**
* Checks `value` to determine whether a default value should be returned in
* its place. The `defaultValue` is returned if `value` is `NaN`, `null`,
* or `undefined`.
*
* @static
* @memberOf _
* @since 4.14.0
* @category Util
* @param {*} value The value to check.
* @param {*} defaultValue The default value.
* @returns {*} Returns the resolved value.
* @example
*
* _.defaultTo(1, 10);
* // => 1
*
* _.defaultTo(undefined, 10);
* // => 10
*/ function(value, defaultValue) {
return null == value || value != value ? defaultValue : value;
}, lodash.divide = divide, lodash.endsWith = /**
* Checks if `string` ends with the given target string.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {string} [target] The string to search for.
* @param {number} [position=string.length] The position to search up to.
* @returns {boolean} Returns `true` if `string` ends with `target`,
* else `false`.
* @example
*
* _.endsWith('abc', 'c');
* // => true
*
* _.endsWith('abc', 'b');
* // => false
*
* _.endsWith('abc', 'b', 2);
* // => true
*/ function(string, target, position) {
string = toString(string), target = baseToString(target);
var length = string.length, end = position = undefined === position ? length : baseClamp(toInteger(position), 0, length);
return (position -= target.length) >= 0 && string.slice(position, end) == target;
}, lodash.eq = eq, lodash.escape = /**
* Converts the characters "&", "<", ">", '"', and "'" in `string` to their
* corresponding HTML entities.
*
* **Note:** No other characters are escaped. To escape additional
* characters use a third-party library like [_he_](https://mths.be/he).
*
* Though the ">" character is escaped for symmetry, characters like
* ">" and "/" don't need escaping in HTML and have no special meaning
* unless they're part of a tag or unquoted attribute value. See
* [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
* (under "semi-related fun fact") for more details.
*
* When working with HTML you should always
* [quote attribute values](http://wonko.com/post/html-escaping) to reduce
* XSS vectors.
*
* @static
* @since 0.1.0
* @memberOf _
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escape('fred, barney, & pebbles');
* // => 'fred, barney, & pebbles'
*/ function(string) {
return (string = toString(string)) && reHasUnescapedHtml.test(string) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string;
}, lodash.escapeRegExp = /**
* Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
* "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to escape.
* @returns {string} Returns the escaped string.
* @example
*
* _.escapeRegExp('[lodash](https://lodash.com/)');
* // => '\[lodash\]\(https://lodash\.com/\)'
*/ function(string) {
return (string = toString(string)) && reHasRegExpChar.test(string) ? string.replace(reRegExpChar, '\\$&') : string;
}, lodash.every = /**
* Checks if `predicate` returns truthy for **all** elements of `collection`.
* Iteration is stopped once `predicate` returns falsey. The predicate is
* invoked with three arguments: (value, index|key, collection).
*
* **Note:** This method returns `true` for
* [empty collections](https://en.wikipedia.org/wiki/Empty_set) because
* [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of
* elements of empty collections.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {boolean} Returns `true` if all elements pass the predicate check,
* else `false`.
* @example
*
* _.every([true, 1, null, 'yes'], Boolean);
* // => false
*
* var users = [
* { 'user': 'barney', 'age': 36, 'active': false },
* { 'user': 'fred', 'age': 40, 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.every(users, { 'user': 'barney', 'active': false });
* // => false
*
* // The `_.matchesProperty` iteratee shorthand.
* _.every(users, ['active', false]);
* // => true
*
* // The `_.property` iteratee shorthand.
* _.every(users, 'active');
* // => false
*/ function(collection, predicate, guard) {
var func = isArray(collection) ? arrayEvery : baseEvery;
return guard && isIterateeCall(collection, predicate, guard) && (predicate = undefined), func(collection, getIteratee(predicate, 3));
}, lodash.find = find, lodash.findIndex = findIndex, lodash.findKey = /**
* This method is like `_.find` except that it returns the key of the first
* element `predicate` returns truthy for instead of the element itself.
*
* @static
* @memberOf _
* @since 1.1.0
* @category Object
* @param {Object} object The object to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {string|undefined} Returns the key of the matched element,
* else `undefined`.
* @example
*
* var users = {
* 'barney': { 'age': 36, 'active': true },
* 'fred': { 'age': 40, 'active': false },
* 'pebbles': { 'age': 1, 'active': true }
* };
*
* _.findKey(users, function(o) { return o.age < 40; });
* // => 'barney' (iteration order is not guaranteed)
*
* // The `_.matches` iteratee shorthand.
* _.findKey(users, { 'age': 1, 'active': true });
* // => 'pebbles'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findKey(users, ['active', false]);
* // => 'fred'
*
* // The `_.property` iteratee shorthand.
* _.findKey(users, 'active');
* // => 'barney'
*/ function(object, predicate) {
return baseFindKey(object, getIteratee(predicate, 3), baseForOwn);
}, lodash.findLast = findLast, lodash.findLastIndex = findLastIndex, lodash.findLastKey = /**
* This method is like `_.findKey` except that it iterates over elements of
* a collection in the opposite order.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Object
* @param {Object} object The object to inspect.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @returns {string|undefined} Returns the key of the matched element,
* else `undefined`.
* @example
*
* var users = {
* 'barney': { 'age': 36, 'active': true },
* 'fred': { 'age': 40, 'active': false },
* 'pebbles': { 'age': 1, 'active': true }
* };
*
* _.findLastKey(users, function(o) { return o.age < 40; });
* // => returns 'pebbles' assuming `_.findKey` returns 'barney'
*
* // The `_.matches` iteratee shorthand.
* _.findLastKey(users, { 'age': 36, 'active': true });
* // => 'barney'
*
* // The `_.matchesProperty` iteratee shorthand.
* _.findLastKey(users, ['active', false]);
* // => 'fred'
*
* // The `_.property` iteratee shorthand.
* _.findLastKey(users, 'active');
* // => 'pebbles'
*/ function(object, predicate) {
return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);
}, lodash.floor = floor, lodash.forEach = forEach, lodash.forEachRight = forEachRight, lodash.forIn = /**
* Iterates over own and inherited enumerable string keyed properties of an
* object and invokes `iteratee` for each property. The iteratee is invoked
* with three arguments: (value, key, object). Iteratee functions may exit
* iteration early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 0.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forInRight
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forIn(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).
*/ function(object, iteratee) {
return null == object ? object : baseFor(object, getIteratee(iteratee, 3), keysIn);
}, lodash.forInRight = /**
* This method is like `_.forIn` except that it iterates over properties of
* `object` in the opposite order.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forIn
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forInRight(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.
*/ function(object, iteratee) {
return null == object ? object : baseForRight(object, getIteratee(iteratee, 3), keysIn);
}, lodash.forOwn = /**
* Iterates over own enumerable string keyed properties of an object and
* invokes `iteratee` for each property. The iteratee is invoked with three
* arguments: (value, key, object). Iteratee functions may exit iteration
* early by explicitly returning `false`.
*
* @static
* @memberOf _
* @since 0.3.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forOwnRight
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forOwn(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'a' then 'b' (iteration order is not guaranteed).
*/ function(object, iteratee) {
return object && baseForOwn(object, getIteratee(iteratee, 3));
}, lodash.forOwnRight = /**
* This method is like `_.forOwn` except that it iterates over properties of
* `object` in the opposite order.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Object
* @param {Object} object The object to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Object} Returns `object`.
* @see _.forOwn
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.forOwnRight(new Foo, function(value, key) {
* console.log(key);
* });
* // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.
*/ function(object, iteratee) {
return object && baseForOwnRight(object, getIteratee(iteratee, 3));
}, lodash.get = get, lodash.gt = gt, lodash.gte = gte, lodash.has = /**
* Checks if `path` is a direct property of `object`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path to check.
* @returns {boolean} Returns `true` if `path` exists, else `false`.
* @example
*
* var object = { 'a': { 'b': 2 } };
* var other = _.create({ 'a': _.create({ 'b': 2 }) });
*
* _.has(object, 'a');
* // => true
*
* _.has(object, 'a.b');
* // => true
*
* _.has(object, ['a', 'b']);
* // => true
*
* _.has(other, 'a');
* // => false
*/ function(object, path) {
return null != object && hasPath(object, path, baseHas);
}, lodash.hasIn = hasIn, lodash.head = head, lodash.identity = identity, lodash.includes = /**
* Checks if `value` is in `collection`. If `collection` is a string, it's
* checked for a substring of `value`, otherwise
* [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* is used for equality comparisons. If `fromIndex` is negative, it's used as
* the offset from the end of `collection`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {boolean} Returns `true` if `value` is found, else `false`.
* @example
*
* _.includes([1, 2, 3], 1);
* // => true
*
* _.includes([1, 2, 3], 1, 2);
* // => false
*
* _.includes({ 'a': 1, 'b': 2 }, 1);
* // => true
*
* _.includes('abcd', 'bc');
* // => true
*/ function(collection, value, fromIndex, guard) {
collection = isArrayLike(collection) ? collection : values(collection), fromIndex = fromIndex && !guard ? toInteger(fromIndex) : 0;
var length = collection.length;
return fromIndex < 0 && (fromIndex = nativeMax(length + fromIndex, 0)), isString(collection) ? fromIndex <= length && collection.indexOf(value, fromIndex) > -1 : !!length && baseIndexOf(collection, value, fromIndex) > -1;
}, lodash.indexOf = /**
* Gets the index at which the first occurrence of `value` is found in `array`
* using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
* for equality comparisons. If `fromIndex` is negative, it's used as the
* offset from the end of `array`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=0] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.indexOf([1, 2, 1, 2], 2);
* // => 1
*
* // Search from the `fromIndex`.
* _.indexOf([1, 2, 1, 2], 2, 2);
* // => 3
*/ function(array, value, fromIndex) {
var length = null == array ? 0 : array.length;
if (!length) return -1;
var index = null == fromIndex ? 0 : toInteger(fromIndex);
return index < 0 && (index = nativeMax(length + index, 0)), baseIndexOf(array, value, index);
}, lodash.inRange = /**
* Checks if `n` is between `start` and up to, but not including, `end`. If
* `end` is not specified, it's set to `start` with `start` then set to `0`.
* If `start` is greater than `end` the params are swapped to support
* negative ranges.
*
* @static
* @memberOf _
* @since 3.3.0
* @category Number
* @param {number} number The number to check.
* @param {number} [start=0] The start of the range.
* @param {number} end The end of the range.
* @returns {boolean} Returns `true` if `number` is in the range, else `false`.
* @see _.range, _.rangeRight
* @example
*
* _.inRange(3, 2, 4);
* // => true
*
* _.inRange(4, 8);
* // => true
*
* _.inRange(4, 2);
* // => false
*
* _.inRange(2, 2);
* // => false
*
* _.inRange(1.2, 2);
* // => true
*
* _.inRange(5.2, 4);
* // => false
*
* _.inRange(-3, -2, -6);
* // => true
*/ function(number, start, end) {
var number1, start1, end1;
return start = toFinite(start), undefined === end ? (end = start, start = 0) : end = toFinite(end), (number1 = number = toNumber(number)) >= nativeMin(start1 = start, end1 = end) && number1 < nativeMax(start1, end1);
}, lodash.invoke = invoke, lodash.isArguments = isArguments, lodash.isArray = isArray, lodash.isArrayBuffer = isArrayBuffer, lodash.isArrayLike = isArrayLike, lodash.isArrayLikeObject = isArrayLikeObject, lodash.isBoolean = /**
* Checks if `value` is classified as a boolean primitive or object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a boolean, else `false`.
* @example
*
* _.isBoolean(false);
* // => true
*
* _.isBoolean(null);
* // => false
*/ function(value) {
return !0 === value || !1 === value || isObjectLike(value) && baseGetTag(value) == boolTag;
}, lodash.isBuffer = isBuffer, lodash.isDate = isDate, lodash.isElement = /**
* Checks if `value` is likely a DOM element.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
* @example
*
* _.isElement(document.body);
* // => true
*
* _.isElement('<body>');
* // => false
*/ function(value) {
return isObjectLike(value) && 1 === value.nodeType && !isPlainObject(value);
}, lodash.isEmpty = /**
* Checks if `value` is an empty object, collection, map, or set.
*
* Objects are considered empty if they have no own enumerable string keyed
* properties.
*
* Array-like values such as `arguments` objects, arrays, buffers, strings, or
* jQuery-like collections are considered empty if they have a `length` of `0`.
* Similarly, maps and sets are considered empty if they have a `size` of `0`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
* @example
*
* _.isEmpty(null);
* // => true
*
* _.isEmpty(true);
* // => true
*
* _.isEmpty(1);
* // => true
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({ 'a': 1 });
* // => false
*/ function(value) {
if (null == value) return !0;
if (isArrayLike(value) && (isArray(value) || 'string' == typeof value || 'function' == typeof value.splice || isBuffer(value) || isTypedArray(value) || isArguments(value))) return !value.length;
var tag = getTag(value);
if (tag == mapTag || tag == setTag) return !value.size;
if (isPrototype(value)) return !baseKeys(value).length;
for(var key in value)if (hasOwnProperty.call(value, key)) return !1;
return !0;
}, lodash.isEqual = /**
* Performs a deep comparison between two values to determine if they are
* equivalent.
*
* **Note:** This method supports comparing arrays, array buffers, booleans,
* date objects, error objects, maps, numbers, `Object` objects, regexes,
* sets, strings, symbols, and typed arrays. `Object` objects are compared
* by their own, not inherited, enumerable properties. Functions and DOM
* nodes are compared by strict equality, i.e. `===`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* var object = { 'a': 1 };
* var other = { 'a': 1 };
*
* _.isEqual(object, other);
* // => true
*
* object === other;
* // => false
*/ function(value, other) {
return baseIsEqual(value, other);
}, lodash.isEqualWith = /**
* This method is like `_.isEqual` except that it accepts `customizer` which
* is invoked to compare values. If `customizer` returns `undefined`, comparisons
* are handled by the method instead. The `customizer` is invoked with up to
* six arguments: (objValue, othValue [, index|key, object, other, stack]).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to compare.
* @param {*} other The other value to compare.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if the values are equivalent, else `false`.
* @example
*
* function isGreeting(value) {
* return /^h(?:i|ello)$/.test(value);
* }
*
* function customizer(objValue, othValue) {
* if (isGreeting(objValue) && isGreeting(othValue)) {
* return true;
* }
* }
*
* var array = ['hello', 'goodbye'];
* var other = ['hi', 'goodbye'];
*
* _.isEqualWith(array, other, customizer);
* // => true
*/ function(value, other, customizer) {
var result = (customizer = 'function' == typeof customizer ? customizer : undefined) ? customizer(value, other) : undefined;
return undefined === result ? baseIsEqual(value, other, undefined, customizer) : !!result;
}, lodash.isError = isError, lodash.isFinite = /**
* Checks if `value` is a finite primitive number.
*
* **Note:** This method is based on
* [`Number.isFinite`](https://mdn.io/Number/isFinite).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
* @example
*
* _.isFinite(3);
* // => true
*
* _.isFinite(Number.MIN_VALUE);
* // => true
*
* _.isFinite(Infinity);
* // => false
*
* _.isFinite('3');
* // => false
*/ function(value) {
return 'number' == typeof value && nativeIsFinite(value);
}, lodash.isFunction = isFunction, lodash.isInteger = isInteger, lodash.isLength = isLength, lodash.isMap = isMap, lodash.isMatch = /**
* Performs a partial deep comparison between `object` and `source` to
* determine if `object` contains equivalent property values.
*
* **Note:** This method is equivalent to `_.matches` when `source` is
* partially applied.
*
* Partial comparisons will match empty array and empty object `source`
* values against any array or object value, respectively. See `_.isEqual`
* for a list of supported value comparisons.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
* @example
*
* var object = { 'a': 1, 'b': 2 };
*
* _.isMatch(object, { 'b': 2 });
* // => true
*
* _.isMatch(object, { 'b': 1 });
* // => false
*/ function(object, source) {
return object === source || baseIsMatch(object, source, getMatchData(source));
}, lodash.isMatchWith = /**
* This method is like `_.isMatch` except that it accepts `customizer` which
* is invoked to compare values. If `customizer` returns `undefined`, comparisons
* are handled by the method instead. The `customizer` is invoked with five
* arguments: (objValue, srcValue, index|key, object, source).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {Object} object The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Function} [customizer] The function to customize comparisons.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
* @example
*
* function isGreeting(value) {
* return /^h(?:i|ello)$/.test(value);
* }
*
* function customizer(objValue, srcValue) {
* if (isGreeting(objValue) && isGreeting(srcValue)) {
* return true;
* }
* }
*
* var object = { 'greeting': 'hello' };
* var source = { 'greeting': 'hi' };
*
* _.isMatchWith(object, source, customizer);
* // => true
*/ function(object, source, customizer) {
return customizer = 'function' == typeof customizer ? customizer : undefined, baseIsMatch(object, source, getMatchData(source), customizer);
}, lodash.isNaN = /**
* Checks if `value` is `NaN`.
*
* **Note:** This method is based on
* [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
* global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
* `undefined` and other non-number values.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
* @example
*
* _.isNaN(NaN);
* // => true
*
* _.isNaN(new Number(NaN));
* // => true
*
* isNaN(undefined);
* // => true
*
* _.isNaN(undefined);
* // => false
*/ function(value) {
// An `NaN` primitive is the only value that is not equal to itself.
// Perform the `toStringTag` check first to avoid errors with some
// ActiveX objects in IE.
return isNumber(value) && value != +value;
}, lodash.isNative = /**
* Checks if `value` is a pristine native function.
*
* **Note:** This method can't reliably detect native functions in the presence
* of the core-js package because core-js circumvents this kind of detection.
* Despite multiple requests, the core-js maintainer has made it clear: any
* attempt to fix the detection will be obstructed. As a result, we're left
* with little choice but to throw an error. Unfortunately, this also affects
* packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill),
* which rely on core-js.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function,
* else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/ function(value) {
if (isMaskable(value)) throw new Error('Unsupported core-js use. Try https://npms.io/search?q=ponyfill.');
return baseIsNative(value);
}, lodash.isNil = /**
* Checks if `value` is `null` or `undefined`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is nullish, else `false`.
* @example
*
* _.isNil(null);
* // => true
*
* _.isNil(void 0);
* // => true
*
* _.isNil(NaN);
* // => false
*/ function(value) {
return null == value;
}, lodash.isNull = /**
* Checks if `value` is `null`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `null`, else `false`.
* @example
*
* _.isNull(null);
* // => true
*
* _.isNull(void 0);
* // => false
*/ function(value) {
return null === value;
}, lodash.isNumber = isNumber, lodash.isObject = isObject, lodash.isObjectLike = isObjectLike, lodash.isPlainObject = isPlainObject, lodash.isRegExp = isRegExp, lodash.isSafeInteger = /**
* Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754
* double precision number which isn't the result of a rounded unsafe integer.
*
* **Note:** This method is based on
* [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.
* @example
*
* _.isSafeInteger(3);
* // => true
*
* _.isSafeInteger(Number.MIN_VALUE);
* // => false
*
* _.isSafeInteger(Infinity);
* // => false
*
* _.isSafeInteger('3');
* // => false
*/ function(value) {
return isInteger(value) && value >= -9007199254740991 && value <= 9007199254740991;
}, lodash.isSet = isSet, lodash.isString = isString, lodash.isSymbol = isSymbol, lodash.isTypedArray = isTypedArray, lodash.isUndefined = /**
* Checks if `value` is `undefined`.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
* @example
*
* _.isUndefined(void 0);
* // => true
*
* _.isUndefined(null);
* // => false
*/ function(value) {
return undefined === value;
}, lodash.isWeakMap = /**
* Checks if `value` is classified as a `WeakMap` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a weak map, else `false`.
* @example
*
* _.isWeakMap(new WeakMap);
* // => true
*
* _.isWeakMap(new Map);
* // => false
*/ function(value) {
return isObjectLike(value) && getTag(value) == weakMapTag;
}, lodash.isWeakSet = /**
* Checks if `value` is classified as a `WeakSet` object.
*
* @static
* @memberOf _
* @since 4.3.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a weak set, else `false`.
* @example
*
* _.isWeakSet(new WeakSet);
* // => true
*
* _.isWeakSet(new Set);
* // => false
*/ function(value) {
return isObjectLike(value) && '[object WeakSet]' == baseGetTag(value);
}, lodash.join = /**
* Converts all elements in `array` into a string separated by `separator`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to convert.
* @param {string} [separator=','] The element separator.
* @returns {string} Returns the joined string.
* @example
*
* _.join(['a', 'b', 'c'], '~');
* // => 'a~b~c'
*/ function(array, separator) {
return null == array ? '' : nativeJoin.call(array, separator);
}, lodash.kebabCase = kebabCase, lodash.last = last, lodash.lastIndexOf = /**
* This method is like `_.indexOf` except that it iterates over elements of
* `array` from right to left.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} [fromIndex=array.length-1] The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.lastIndexOf([1, 2, 1, 2], 2);
* // => 3
*
* // Search from the `fromIndex`.
* _.lastIndexOf([1, 2, 1, 2], 2, 2);
* // => 1
*/ function(array, value, fromIndex) {
var length = null == array ? 0 : array.length;
if (!length) return -1;
var index = length;
return undefined !== fromIndex && (index = (index = toInteger(fromIndex)) < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1)), value == value ? /**
* A specialized version of `_.lastIndexOf` which performs strict equality
* comparisons of values, i.e. `===`.
*
* @private
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @param {number} fromIndex The index to search from.
* @returns {number} Returns the index of the matched value, else `-1`.
*/ function(array, value, fromIndex) {
for(var index = fromIndex + 1; index-- && array[index] !== value;);
return index;
}(array, value, index) : baseFindIndex(array, baseIsNaN, index, !0);
}, lodash.lowerCase = lowerCase, lodash.lowerFirst = lowerFirst, lodash.lt = lt, lodash.lte = lte, lodash.max = /**
* Computes the maximum value of `array`. If `array` is empty or falsey,
* `undefined` is returned.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Math
* @param {Array} array The array to iterate over.
* @returns {*} Returns the maximum value.
* @example
*
* _.max([4, 2, 8, 6]);
* // => 8
*
* _.max([]);
* // => undefined
*/ function(array) {
return array && array.length ? baseExtremum(array, identity, baseGt) : undefined;
}, lodash.maxBy = /**
* This method is like `_.max` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the criterion by which
* the value is ranked. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {*} Returns the maximum value.
* @example
*
* var objects = [{ 'n': 1 }, { 'n': 2 }];
*
* _.maxBy(objects, function(o) { return o.n; });
* // => { 'n': 2 }
*
* // The `_.property` iteratee shorthand.
* _.maxBy(objects, 'n');
* // => { 'n': 2 }
*/ function(array, iteratee) {
return array && array.length ? baseExtremum(array, getIteratee(iteratee, 2), baseGt) : undefined;
}, lodash.mean = /**
* Computes the mean of the values in `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @returns {number} Returns the mean.
* @example
*
* _.mean([4, 2, 8, 6]);
* // => 5
*/ function(array) {
return baseMean(array, identity);
}, lodash.meanBy = /**
* This method is like `_.mean` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the value to be averaged.
* The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.7.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the mean.
* @example
*
* var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
*
* _.meanBy(objects, function(o) { return o.n; });
* // => 5
*
* // The `_.property` iteratee shorthand.
* _.meanBy(objects, 'n');
* // => 5
*/ function(array, iteratee) {
return baseMean(array, getIteratee(iteratee, 2));
}, lodash.min = /**
* Computes the minimum value of `array`. If `array` is empty or falsey,
* `undefined` is returned.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Math
* @param {Array} array The array to iterate over.
* @returns {*} Returns the minimum value.
* @example
*
* _.min([4, 2, 8, 6]);
* // => 2
*
* _.min([]);
* // => undefined
*/ function(array) {
return array && array.length ? baseExtremum(array, identity, baseLt) : undefined;
}, lodash.minBy = /**
* This method is like `_.min` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the criterion by which
* the value is ranked. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {*} Returns the minimum value.
* @example
*
* var objects = [{ 'n': 1 }, { 'n': 2 }];
*
* _.minBy(objects, function(o) { return o.n; });
* // => { 'n': 1 }
*
* // The `_.property` iteratee shorthand.
* _.minBy(objects, 'n');
* // => { 'n': 1 }
*/ function(array, iteratee) {
return array && array.length ? baseExtremum(array, getIteratee(iteratee, 2), baseLt) : undefined;
}, lodash.stubArray = stubArray, lodash.stubFalse = stubFalse, lodash.stubObject = /**
* This method returns a new empty object.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {Object} Returns the new empty object.
* @example
*
* var objects = _.times(2, _.stubObject);
*
* console.log(objects);
* // => [{}, {}]
*
* console.log(objects[0] === objects[1]);
* // => false
*/ function() {
return {};
}, lodash.stubString = /**
* This method returns an empty string.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {string} Returns the empty string.
* @example
*
* _.times(2, _.stubString);
* // => ['', '']
*/ function() {
return '';
}, lodash.stubTrue = /**
* This method returns `true`.
*
* @static
* @memberOf _
* @since 4.13.0
* @category Util
* @returns {boolean} Returns `true`.
* @example
*
* _.times(2, _.stubTrue);
* // => [true, true]
*/ function() {
return !0;
}, lodash.multiply = multiply, lodash.nth = /**
* Gets the element at index `n` of `array`. If `n` is negative, the nth
* element from the end is returned.
*
* @static
* @memberOf _
* @since 4.11.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=0] The index of the element to return.
* @returns {*} Returns the nth element of `array`.
* @example
*
* var array = ['a', 'b', 'c', 'd'];
*
* _.nth(array, 1);
* // => 'b'
*
* _.nth(array, -2);
* // => 'c';
*/ function(array, n) {
return array && array.length ? baseNth(array, toInteger(n)) : undefined;
}, lodash.noConflict = /**
* Reverts the `_` variable to its previous value and returns a reference to
* the `lodash` function.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @returns {Function} Returns the `lodash` function.
* @example
*
* var lodash = _.noConflict();
*/ function() {
return root._ === this && (root._ = oldDash), this;
}, lodash.noop = noop, lodash.now = now, lodash.pad = /**
* Pads `string` on the left and right sides if it's shorter than `length`.
* Padding characters are truncated if they can't be evenly divided by `length`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.pad('abc', 8);
* // => ' abc '
*
* _.pad('abc', 8, '_-');
* // => '_-abc_-_'
*
* _.pad('abc', 3);
* // => 'abc'
*/ function(string, length, chars) {
string = toString(string);
var strLength = (length = toInteger(length)) ? stringSize(string) : 0;
if (!length || strLength >= length) return string;
var mid = (length - strLength) / 2;
return createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars);
}, lodash.padEnd = /**
* Pads `string` on the right side if it's shorter than `length`. Padding
* characters are truncated if they exceed `length`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.padEnd('abc', 6);
* // => 'abc '
*
* _.padEnd('abc', 6, '_-');
* // => 'abc_-_'
*
* _.padEnd('abc', 3);
* // => 'abc'
*/ function(string, length, chars) {
string = toString(string);
var strLength = (length = toInteger(length)) ? stringSize(string) : 0;
return length && strLength < length ? string + createPadding(length - strLength, chars) : string;
}, lodash.padStart = /**
* Pads `string` on the left side if it's shorter than `length`. Padding
* characters are truncated if they exceed `length`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to pad.
* @param {number} [length=0] The padding length.
* @param {string} [chars=' '] The string used as padding.
* @returns {string} Returns the padded string.
* @example
*
* _.padStart('abc', 6);
* // => ' abc'
*
* _.padStart('abc', 6, '_-');
* // => '_-_abc'
*
* _.padStart('abc', 3);
* // => 'abc'
*/ function(string, length, chars) {
string = toString(string);
var strLength = (length = toInteger(length)) ? stringSize(string) : 0;
return length && strLength < length ? createPadding(length - strLength, chars) + string : string;
}, lodash.parseInt = /**
* Converts `string` to an integer of the specified radix. If `radix` is
* `undefined` or `0`, a `radix` of `10` is used unless `value` is a
* hexadecimal, in which case a `radix` of `16` is used.
*
* **Note:** This method aligns with the
* [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.
*
* @static
* @memberOf _
* @since 1.1.0
* @category String
* @param {string} string The string to convert.
* @param {number} [radix=10] The radix to interpret `value` by.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {number} Returns the converted integer.
* @example
*
* _.parseInt('08');
* // => 8
*
* _.map(['6', '08', '10'], _.parseInt);
* // => [6, 8, 10]
*/ function(string, radix, guard) {
return guard || null == radix ? radix = 0 : radix && (radix *= 1), nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0);
}, lodash.random = /**
* Produces a random number between the inclusive `lower` and `upper` bounds.
* If only one argument is provided a number between `0` and the given number
* is returned. If `floating` is `true`, or either `lower` or `upper` are
* floats, a floating-point number is returned instead of an integer.
*
* **Note:** JavaScript follows the IEEE-754 standard for resolving
* floating-point values which can produce unexpected results.
*
* @static
* @memberOf _
* @since 0.7.0
* @category Number
* @param {number} [lower=0] The lower bound.
* @param {number} [upper=1] The upper bound.
* @param {boolean} [floating] Specify returning a floating-point number.
* @returns {number} Returns the random number.
* @example
*
* _.random(0, 5);
* // => an integer between 0 and 5
*
* _.random(5);
* // => also an integer between 0 and 5
*
* _.random(5, true);
* // => a floating-point number between 0 and 5
*
* _.random(1.2, 5.2);
* // => a floating-point number between 1.2 and 5.2
*/ function(lower, upper, floating) {
if (floating && 'boolean' != typeof floating && isIterateeCall(lower, upper, floating) && (upper = floating = undefined), undefined === floating && ('boolean' == typeof upper ? (floating = upper, upper = undefined) : 'boolean' == typeof lower && (floating = lower, lower = undefined)), undefined === lower && undefined === upper ? (lower = 0, upper = 1) : (lower = toFinite(lower), undefined === upper ? (upper = lower, lower = 0) : upper = toFinite(upper)), lower > upper) {
var temp = lower;
lower = upper, upper = temp;
}
if (floating || lower % 1 || upper % 1) {
var rand = nativeRandom();
return nativeMin(lower + rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1))), upper);
}
return baseRandom(lower, upper);
}, lodash.reduce = /**
* Reduces `collection` to a value which is the accumulated result of running
* each element in `collection` thru `iteratee`, where each successive
* invocation is supplied the return value of the previous. If `accumulator`
* is not given, the first element of `collection` is used as the initial
* value. The iteratee is invoked with four arguments:
* (accumulator, value, index|key, collection).
*
* Many lodash methods are guarded to work as iteratees for methods like
* `_.reduce`, `_.reduceRight`, and `_.transform`.
*
* The guarded methods are:
* `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
* and `sortBy`
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @returns {*} Returns the accumulated value.
* @see _.reduceRight
* @example
*
* _.reduce([1, 2], function(sum, n) {
* return sum + n;
* }, 0);
* // => 3
*
* _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
* (result[value] || (result[value] = [])).push(key);
* return result;
* }, {});
* // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
*/ function(collection, iteratee, accumulator) {
var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3;
return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach);
}, lodash.reduceRight = /**
* This method is like `_.reduce` except that it iterates over elements of
* `collection` from right to left.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @param {*} [accumulator] The initial value.
* @returns {*} Returns the accumulated value.
* @see _.reduce
* @example
*
* var array = [[0, 1], [2, 3], [4, 5]];
*
* _.reduceRight(array, function(flattened, other) {
* return flattened.concat(other);
* }, []);
* // => [4, 5, 2, 3, 0, 1]
*/ function(collection, iteratee, accumulator) {
var func = isArray(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3;
return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight);
}, lodash.repeat = /**
* Repeats the given string `n` times.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to repeat.
* @param {number} [n=1] The number of times to repeat the string.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the repeated string.
* @example
*
* _.repeat('*', 3);
* // => '***'
*
* _.repeat('abc', 2);
* // => 'abcabc'
*
* _.repeat('abc', 0);
* // => ''
*/ function(string, n, guard) {
return n = (guard ? isIterateeCall(string, n, guard) : undefined === n) ? 1 : toInteger(n), baseRepeat(toString(string), n);
}, lodash.replace = /**
* Replaces matches for `pattern` in `string` with `replacement`.
*
* **Note:** This method is based on
* [`String#replace`](https://mdn.io/String/replace).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to modify.
* @param {RegExp|string} pattern The pattern to replace.
* @param {Function|string} replacement The match replacement.
* @returns {string} Returns the modified string.
* @example
*
* _.replace('Hi Fred', 'Fred', 'Barney');
* // => 'Hi Barney'
*/ function() {
var args = arguments, string = toString(args[0]);
return args.length < 3 ? string : string.replace(args[1], args[2]);
}, lodash.result = /**
* This method is like `_.get` except that if the resolved value is a
* function it's invoked with the `this` binding of its parent object and
* its result is returned.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to resolve.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
*
* _.result(object, 'a[0].b.c1');
* // => 3
*
* _.result(object, 'a[0].b.c2');
* // => 4
*
* _.result(object, 'a[0].b.c3', 'default');
* // => 'default'
*
* _.result(object, 'a[0].b.c3', _.constant('default'));
* // => 'default'
*/ function(object, path, defaultValue) {
path = castPath(path, object);
var index = -1, length = path.length;
for(length || (length = 1, object = undefined); ++index < length;){
var value = null == object ? undefined : object[toKey(path[index])];
undefined === value && (index = length, value = defaultValue), object = isFunction(value) ? value.call(object) : value;
}
return object;
}, lodash.round = round, lodash.runInContext = runInContext, lodash.sample = /**
* Gets a random element from `collection`.
*
* @static
* @memberOf _
* @since 2.0.0
* @category Collection
* @param {Array|Object} collection The collection to sample.
* @returns {*} Returns the random element.
* @example
*
* _.sample([1, 2, 3, 4]);
* // => 2
*/ function(collection) {
return (isArray(collection) ? arraySample : /**
* The base implementation of `_.sample`.
*
* @private
* @param {Array|Object} collection The collection to sample.
* @returns {*} Returns the random element.
*/ function(collection) {
return arraySample(values(collection));
})(collection);
}, lodash.size = /**
* Gets the size of `collection` by returning its length for array-like
* values or the number of own enumerable string keyed properties for objects.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object|string} collection The collection to inspect.
* @returns {number} Returns the collection size.
* @example
*
* _.size([1, 2, 3]);
* // => 3
*
* _.size({ 'a': 1, 'b': 2 });
* // => 2
*
* _.size('pebbles');
* // => 7
*/ function(collection) {
if (null == collection) return 0;
if (isArrayLike(collection)) return isString(collection) ? stringSize(collection) : collection.length;
var tag = getTag(collection);
return tag == mapTag || tag == setTag ? collection.size : baseKeys(collection).length;
}, lodash.snakeCase = snakeCase, lodash.some = /**
* Checks if `predicate` returns truthy for **any** element of `collection`.
* Iteration is stopped once `predicate` returns truthy. The predicate is
* invoked with three arguments: (value, index|key, collection).
*
* @static
* @memberOf _
* @since 0.1.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} [predicate=_.identity] The function invoked per iteration.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {boolean} Returns `true` if any element passes the predicate check,
* else `false`.
* @example
*
* _.some([null, 0, 'yes', false], Boolean);
* // => true
*
* var users = [
* { 'user': 'barney', 'active': true },
* { 'user': 'fred', 'active': false }
* ];
*
* // The `_.matches` iteratee shorthand.
* _.some(users, { 'user': 'barney', 'active': false });
* // => false
*
* // The `_.matchesProperty` iteratee shorthand.
* _.some(users, ['active', false]);
* // => true
*
* // The `_.property` iteratee shorthand.
* _.some(users, 'active');
* // => true
*/ function(collection, predicate, guard) {
var func = isArray(collection) ? arraySome : baseSome;
return guard && isIterateeCall(collection, predicate, guard) && (predicate = undefined), func(collection, getIteratee(predicate, 3));
}, lodash.sortedIndex = /**
* Uses a binary search to determine the lowest index at which `value`
* should be inserted into `array` in order to maintain its sort order.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* _.sortedIndex([30, 50], 40);
* // => 1
*/ function(array, value) {
return baseSortedIndex(array, value);
}, lodash.sortedIndexBy = /**
* This method is like `_.sortedIndex` except that it accepts `iteratee`
* which is invoked for `value` and each element of `array` to compute their
* sort ranking. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* var objects = [{ 'x': 4 }, { 'x': 5 }];
*
* _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
* // => 0
*
* // The `_.property` iteratee shorthand.
* _.sortedIndexBy(objects, { 'x': 4 }, 'x');
* // => 0
*/ function(array, value, iteratee) {
return baseSortedIndexBy(array, value, getIteratee(iteratee, 2));
}, lodash.sortedIndexOf = /**
* This method is like `_.indexOf` except that it performs a binary
* search on a sorted `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.sortedIndexOf([4, 5, 5, 5, 6], 5);
* // => 1
*/ function(array, value) {
var length = null == array ? 0 : array.length;
if (length) {
var index = baseSortedIndex(array, value);
if (index < length && eq(array[index], value)) return index;
}
return -1;
}, lodash.sortedLastIndex = /**
* This method is like `_.sortedIndex` except that it returns the highest
* index at which `value` should be inserted into `array` in order to
* maintain its sort order.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* _.sortedLastIndex([4, 5, 5, 5, 6], 5);
* // => 4
*/ function(array, value) {
return baseSortedIndex(array, value, !0);
}, lodash.sortedLastIndexBy = /**
* This method is like `_.sortedLastIndex` except that it accepts `iteratee`
* which is invoked for `value` and each element of `array` to compute their
* sort ranking. The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The sorted array to inspect.
* @param {*} value The value to evaluate.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the index at which `value` should be inserted
* into `array`.
* @example
*
* var objects = [{ 'x': 4 }, { 'x': 5 }];
*
* _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
* // => 1
*
* // The `_.property` iteratee shorthand.
* _.sortedLastIndexBy(objects, { 'x': 4 }, 'x');
* // => 1
*/ function(array, value, iteratee) {
return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), !0);
}, lodash.sortedLastIndexOf = /**
* This method is like `_.lastIndexOf` except that it performs a binary
* search on a sorted `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {*} value The value to search for.
* @returns {number} Returns the index of the matched value, else `-1`.
* @example
*
* _.sortedLastIndexOf([4, 5, 5, 5, 6], 5);
* // => 3
*/ function(array, value) {
if (null == array ? 0 : array.length) {
var index = baseSortedIndex(array, value, !0) - 1;
if (eq(array[index], value)) return index;
}
return -1;
}, lodash.startCase = startCase, lodash.startsWith = /**
* Checks if `string` starts with the given target string.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to inspect.
* @param {string} [target] The string to search for.
* @param {number} [position=0] The position to search from.
* @returns {boolean} Returns `true` if `string` starts with `target`,
* else `false`.
* @example
*
* _.startsWith('abc', 'a');
* // => true
*
* _.startsWith('abc', 'b');
* // => false
*
* _.startsWith('abc', 'b', 1);
* // => true
*/ function(string, target, position) {
return string = toString(string), position = null == position ? 0 : baseClamp(toInteger(position), 0, string.length), target = baseToString(target), string.slice(position, position + target.length) == target;
}, lodash.subtract = subtract, lodash.sum = /**
* Computes the sum of the values in `array`.
*
* @static
* @memberOf _
* @since 3.4.0
* @category Math
* @param {Array} array The array to iterate over.
* @returns {number} Returns the sum.
* @example
*
* _.sum([4, 2, 8, 6]);
* // => 20
*/ function(array) {
return array && array.length ? baseSum(array, identity) : 0;
}, lodash.sumBy = /**
* This method is like `_.sum` except that it accepts `iteratee` which is
* invoked for each element in `array` to generate the value to be summed.
* The iteratee is invoked with one argument: (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Math
* @param {Array} array The array to iterate over.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {number} Returns the sum.
* @example
*
* var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
*
* _.sumBy(objects, function(o) { return o.n; });
* // => 20
*
* // The `_.property` iteratee shorthand.
* _.sumBy(objects, 'n');
* // => 20
*/ function(array, iteratee) {
return array && array.length ? baseSum(array, getIteratee(iteratee, 2)) : 0;
}, lodash.template = /**
* Creates a compiled template function that can interpolate data properties
* in "interpolate" delimiters, HTML-escape interpolated data properties in
* "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
* properties may be accessed as free variables in the template. If a setting
* object is given, it takes precedence over `_.templateSettings` values.
*
* **Note:** In the development build `_.template` utilizes
* [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
* for easier debugging.
*
* For more information on precompiling templates see
* [lodash's custom builds documentation](https://lodash.com/custom-builds).
*
* For more information on Chrome extension sandboxes see
* [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
*
* @static
* @since 0.1.0
* @memberOf _
* @category String
* @param {string} [string=''] The template string.
* @param {Object} [options={}] The options object.
* @param {RegExp} [options.escape=_.templateSettings.escape]
* The HTML "escape" delimiter.
* @param {RegExp} [options.evaluate=_.templateSettings.evaluate]
* The "evaluate" delimiter.
* @param {Object} [options.imports=_.templateSettings.imports]
* An object to import into the template as free variables.
* @param {RegExp} [options.interpolate=_.templateSettings.interpolate]
* The "interpolate" delimiter.
* @param {string} [options.sourceURL='lodash.templateSources[n]']
* The sourceURL of the compiled template.
* @param {string} [options.variable='obj']
* The data object variable name.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Function} Returns the compiled template function.
* @example
*
* // Use the "interpolate" delimiter to create a compiled template.
* var compiled = _.template('hello <%= user %>!');
* compiled({ 'user': 'fred' });
* // => 'hello fred!'
*
* // Use the HTML "escape" delimiter to escape data property values.
* var compiled = _.template('<b><%- value %></b>');
* compiled({ 'value': '<script>' });
* // => '<b><script></b>'
*
* // Use the "evaluate" delimiter to execute JavaScript and generate HTML.
* var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
* // Use the internal `print` function in "evaluate" delimiters.
* var compiled = _.template('<% print("hello " + user); %>!');
* compiled({ 'user': 'barney' });
* // => 'hello barney!'
*
* // Use the ES template literal delimiter as an "interpolate" delimiter.
* // Disable support by replacing the "interpolate" delimiter.
* var compiled = _.template('hello ${ user }!');
* compiled({ 'user': 'pebbles' });
* // => 'hello pebbles!'
*
* // Use backslashes to treat delimiters as plain text.
* var compiled = _.template('<%= "\\<%- value %\\>" %>');
* compiled({ 'value': 'ignored' });
* // => '<%- value %>'
*
* // Use the `imports` option to import `jQuery` as `jq`.
* var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
* var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
* compiled({ 'users': ['fred', 'barney'] });
* // => '<li>fred</li><li>barney</li>'
*
* // Use the `sourceURL` option to specify a custom sourceURL for the template.
* var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
* compiled(data);
* // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
*
* // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
* var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
* compiled.source;
* // => function(data) {
* // var __t, __p = '';
* // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
* // return __p;
* // }
*
* // Use custom template delimiters.
* _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
* var compiled = _.template('hello {{ user }}!');
* compiled({ 'user': 'mustache' });
* // => 'hello mustache!'
*
* // Use the `source` property to inline compiled templates for meaningful
* // line numbers in error messages and stack traces.
* fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\
* var JST = {\
* "main": ' + _.template(mainText).source + '\
* };\
* ');
*/ function(string, options, guard) {
// Based on John Resig's `tmpl` implementation
// (http://ejohn.org/blog/javascript-micro-templating/)
// and Laura Doktorova's doT.js (https://github.com/olado/doT).
var settings = lodash.templateSettings;
guard && isIterateeCall(string, options, guard) && (options = undefined), string = toString(string), options = assignInWith({}, options, settings, customDefaultsAssignIn);
var isEscaping, isEvaluating, imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys), index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '", reDelimiters = RegExp1((options.escape || reNoMatch).source + '|' + interpolate.source + '|' + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + (options.evaluate || reNoMatch).source + '|$', 'g'), sourceURL = '//# sourceURL=' + (hasOwnProperty.call(options, 'sourceURL') ? (options.sourceURL + '').replace(/\s/g, ' ') : 'lodash.templateSources[' + ++templateCounter + ']') + '\n';
string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
// The JS engine embedded in Adobe products needs `match` returned in
// order to produce the correct `offset` value.
return interpolateValue || (interpolateValue = esTemplateValue), // Escape characters that can't be included in string literals.
source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar), escapeValue && (isEscaping = !0, source += "' +\n__e(" + escapeValue + ") +\n'"), evaluateValue && (isEvaluating = !0, source += "';\n" + evaluateValue + ";\n__p += '"), interpolateValue && (source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"), index = offset + match.length, match;
}), source += "';\n";
// If `variable` is not specified wrap a with-statement around the generated
// code to add the data object to the top of the scope chain.
var variable = hasOwnProperty.call(options, 'variable') && options.variable;
if (variable) {
if (reForbiddenIdentifierChars.test(variable)) throw new Error('Invalid `variable` option passed into `_.template`');
} else source = 'with (obj) {\n' + source + '\n}\n';
// Cleanup code by stripping empty strings.
source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source).replace(reEmptyStringMiddle, '$1').replace(reEmptyStringTrailing, '$1;'), // Frame code as the function body.
source = 'function(' + (variable || 'obj') + ') {\n' + (variable ? '' : 'obj || (obj = {});\n') + "var __t, __p = ''" + (isEscaping ? ', __e = _.escape' : '') + (isEvaluating ? ", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n" : ';\n') + source + 'return __p\n}';
var result = attempt(function() {
return Function1(importsKeys, sourceURL + 'return ' + source).apply(undefined, importsValues);
});
if (// Provide the compiled function's source by its `toString` method or
// the `source` property as a convenience for inlining compiled templates.
result.source = source, isError(result)) throw result;
return result;
}, lodash.times = /**
* Invokes the iteratee `n` times, returning an array of the results of
* each invocation. The iteratee is invoked with one argument; (index).
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {number} n The number of times to invoke `iteratee`.
* @param {Function} [iteratee=_.identity] The function invoked per iteration.
* @returns {Array} Returns the array of results.
* @example
*
* _.times(3, String);
* // => ['0', '1', '2']
*
* _.times(4, _.constant(0));
* // => [0, 0, 0, 0]
*/ function(n, iteratee) {
if ((n = toInteger(n)) < 1 || n > 9007199254740991) return [];
var index = 4294967295, length = nativeMin(n, 4294967295);
iteratee = getIteratee(iteratee), n -= 4294967295;
for(var result = baseTimes(length, iteratee); ++index < n;)iteratee(index);
return result;
}, lodash.toFinite = toFinite, lodash.toInteger = toInteger, lodash.toLength = toLength, lodash.toLower = /**
* Converts `string`, as a whole, to lower case just like
* [String#toLowerCase](https://mdn.io/toLowerCase).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the lower cased string.
* @example
*
* _.toLower('--Foo-Bar--');
* // => '--foo-bar--'
*
* _.toLower('fooBar');
* // => 'foobar'
*
* _.toLower('__FOO_BAR__');
* // => '__foo_bar__'
*/ function(value) {
return toString(value).toLowerCase();
}, lodash.toNumber = toNumber, lodash.toSafeInteger = /**
* Converts `value` to a safe integer. A safe integer can be compared and
* represented correctly.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to convert.
* @returns {number} Returns the converted integer.
* @example
*
* _.toSafeInteger(3.2);
* // => 3
*
* _.toSafeInteger(Number.MIN_VALUE);
* // => 0
*
* _.toSafeInteger(Infinity);
* // => 9007199254740991
*
* _.toSafeInteger('3.2');
* // => 3
*/ function(value) {
return value ? baseClamp(toInteger(value), -9007199254740991, 9007199254740991) : 0 === value ? value : 0;
}, lodash.toString = toString, lodash.toUpper = /**
* Converts `string`, as a whole, to upper case just like
* [String#toUpperCase](https://mdn.io/toUpperCase).
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to convert.
* @returns {string} Returns the upper cased string.
* @example
*
* _.toUpper('--foo-bar--');
* // => '--FOO-BAR--'
*
* _.toUpper('fooBar');
* // => 'FOOBAR'
*
* _.toUpper('__foo_bar__');
* // => '__FOO_BAR__'
*/ function(value) {
return toString(value).toUpperCase();
}, lodash.trim = /**
* Removes leading and trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trim(' abc ');
* // => 'abc'
*
* _.trim('-_-abc-_-', '_-');
* // => 'abc'
*
* _.map([' foo ', ' bar '], _.trim);
* // => ['foo', 'bar']
*/ function(string, chars, guard) {
if ((string = toString(string)) && (guard || undefined === chars)) return baseTrim(string);
if (!string || !(chars = baseToString(chars))) return string;
var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1;
return castSlice(strSymbols, start, end).join('');
}, lodash.trimEnd = /**
* Removes trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trimEnd(' abc ');
* // => ' abc'
*
* _.trimEnd('-_-abc-_-', '_-');
* // => '-_-abc'
*/ function(string, chars, guard) {
if ((string = toString(string)) && (guard || undefined === chars)) return string.slice(0, trimmedEndIndex(string) + 1);
if (!string || !(chars = baseToString(chars))) return string;
var strSymbols = stringToArray(string), end = charsEndIndex(strSymbols, stringToArray(chars)) + 1;
return castSlice(strSymbols, 0, end).join('');
}, lodash.trimStart = /**
* Removes leading whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trimStart(' abc ');
* // => 'abc '
*
* _.trimStart('-_-abc-_-', '_-');
* // => 'abc-_-'
*/ function(string, chars, guard) {
if ((string = toString(string)) && (guard || undefined === chars)) return string.replace(reTrimStart, '');
if (!string || !(chars = baseToString(chars))) return string;
var strSymbols = stringToArray(string), start = charsStartIndex(strSymbols, stringToArray(chars));
return castSlice(strSymbols, start).join('');
}, lodash.truncate = /**
* Truncates `string` if it's longer than the given maximum string length.
* The last characters of the truncated string are replaced with the omission
* string which defaults to "...".
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to truncate.
* @param {Object} [options={}] The options object.
* @param {number} [options.length=30] The maximum string length.
* @param {string} [options.omission='...'] The string to indicate text is omitted.
* @param {RegExp|string} [options.separator] The separator pattern to truncate to.
* @returns {string} Returns the truncated string.
* @example
*
* _.truncate('hi-diddly-ho there, neighborino');
* // => 'hi-diddly-ho there, neighbo...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'length': 24,
* 'separator': ' '
* });
* // => 'hi-diddly-ho there,...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'length': 24,
* 'separator': /,? +/
* });
* // => 'hi-diddly-ho there...'
*
* _.truncate('hi-diddly-ho there, neighborino', {
* 'omission': ' [...]'
* });
* // => 'hi-diddly-ho there, neig [...]'
*/ function(string, options) {
var length = 30, omission = '...';
if (isObject(options)) {
var separator = 'separator' in options ? options.separator : separator;
length = 'length' in options ? toInteger(options.length) : length, omission = 'omission' in options ? baseToString(options.omission) : omission;
}
var strLength = (string = toString(string)).length;
if (hasUnicode(string)) {
var strSymbols = stringToArray(string);
strLength = strSymbols.length;
}
if (length >= strLength) return string;
var end = length - stringSize(omission);
if (end < 1) return omission;
var result = strSymbols ? castSlice(strSymbols, 0, end).join('') : string.slice(0, end);
if (undefined === separator) return result + omission;
if (strSymbols && (end += result.length - end), isRegExp(separator)) {
if (string.slice(end).search(separator)) {
var match, substring = result;
for(separator.global || (separator = RegExp1(separator.source, toString(reFlags.exec(separator)) + 'g')), separator.lastIndex = 0; match = separator.exec(substring);)var newEnd = match.index;
result = result.slice(0, undefined === newEnd ? end : newEnd);
}
} else if (string.indexOf(baseToString(separator), end) != end) {
var index = result.lastIndexOf(separator);
index > -1 && (result = result.slice(0, index));
}
return result + omission;
}, lodash.unescape = /**
* The inverse of `_.escape`; this method converts the HTML entities
* `&`, `<`, `>`, `"`, and `'` in `string` to
* their corresponding characters.
*
* **Note:** No other HTML entities are unescaped. To unescape additional
* HTML entities use a third-party library like [_he_](https://mths.be/he).
*
* @static
* @memberOf _
* @since 0.6.0
* @category String
* @param {string} [string=''] The string to unescape.
* @returns {string} Returns the unescaped string.
* @example
*
* _.unescape('fred, barney, & pebbles');
* // => 'fred, barney, & pebbles'
*/ function(string) {
return (string = toString(string)) && reHasEscapedHtml.test(string) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string;
}, lodash.uniqueId = /**
* Generates a unique ID. If `prefix` is given, the ID is appended to it.
*
* @static
* @since 0.1.0
* @memberOf _
* @category Util
* @param {string} [prefix=''] The value to prefix the ID with.
* @returns {string} Returns the unique ID.
* @example
*
* _.uniqueId('contact_');
* // => 'contact_104'
*
* _.uniqueId();
* // => '105'
*/ function(prefix) {
var id = ++idCounter;
return toString(prefix) + id;
}, lodash.upperCase = upperCase, lodash.upperFirst = upperFirst, // Add aliases.
lodash.each = forEach, lodash.eachRight = forEachRight, lodash.first = head, mixin(lodash, (source = {}, baseForOwn(lodash, function(func, methodName) {
hasOwnProperty.call(lodash.prototype, methodName) || (source[methodName] = func);
}), source), {
chain: !1
}), /*------------------------------------------------------------------------*/ /**
* The semantic version number.
*
* @static
* @memberOf _
* @type {string}
*/ lodash.VERSION = '4.17.21', // Assign default placeholders.
arrayEach([
'bind',
'bindKey',
'curry',
'curryRight',
'partial',
'partialRight'
], function(methodName) {
lodash[methodName].placeholder = lodash;
}), // Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
arrayEach([
'drop',
'take'
], function(methodName, index) {
LazyWrapper.prototype[methodName] = function(n) {
n = undefined === n ? 1 : nativeMax(toInteger(n), 0);
var result = this.__filtered__ && !index ? new LazyWrapper(this) : this.clone();
return result.__filtered__ ? result.__takeCount__ = nativeMin(n, result.__takeCount__) : result.__views__.push({
size: nativeMin(n, 4294967295),
type: methodName + (result.__dir__ < 0 ? 'Right' : '')
}), result;
}, LazyWrapper.prototype[methodName + 'Right'] = function(n) {
return this.reverse()[methodName](n).reverse();
};
}), // Add `LazyWrapper` methods that accept an `iteratee` value.
arrayEach([
'filter',
'map',
'takeWhile'
], function(methodName, index) {
var type = index + 1, isFilter = 1 == type || 3 == type;
LazyWrapper.prototype[methodName] = function(iteratee) {
var result = this.clone();
return result.__iteratees__.push({
iteratee: getIteratee(iteratee, 3),
type: type
}), result.__filtered__ = result.__filtered__ || isFilter, result;
};
}), // Add `LazyWrapper` methods for `_.head` and `_.last`.
arrayEach([
'head',
'last'
], function(methodName, index) {
var takeName = 'take' + (index ? 'Right' : '');
LazyWrapper.prototype[methodName] = function() {
return this[takeName](1).value()[0];
};
}), // Add `LazyWrapper` methods for `_.initial` and `_.tail`.
arrayEach([
'initial',
'tail'
], function(methodName, index) {
var dropName = 'drop' + (index ? '' : 'Right');
LazyWrapper.prototype[methodName] = function() {
return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
};
}), LazyWrapper.prototype.compact = function() {
return this.filter(identity);
}, LazyWrapper.prototype.find = function(predicate) {
return this.filter(predicate).head();
}, LazyWrapper.prototype.findLast = function(predicate) {
return this.reverse().find(predicate);
}, LazyWrapper.prototype.invokeMap = baseRest(function(path, args) {
return 'function' == typeof path ? new LazyWrapper(this) : this.map(function(value) {
return baseInvoke(value, path, args);
});
}), LazyWrapper.prototype.reject = function(predicate) {
return this.filter(negate(getIteratee(predicate)));
}, LazyWrapper.prototype.slice = function(start, end) {
start = toInteger(start);
var result = this;
return result.__filtered__ && (start > 0 || end < 0) ? new LazyWrapper(result) : (start < 0 ? result = result.takeRight(-start) : start && (result = result.drop(start)), undefined !== end && (result = (end = toInteger(end)) < 0 ? result.dropRight(-end) : result.take(end - start)), result);
}, LazyWrapper.prototype.takeRightWhile = function(predicate) {
return this.reverse().takeWhile(predicate).reverse();
}, LazyWrapper.prototype.toArray = function() {
return this.take(4294967295);
}, // Add `LazyWrapper` methods to `lodash.prototype`.
baseForOwn(LazyWrapper.prototype, function(func, methodName) {
var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), isTaker = /^(?:head|last)$/.test(methodName), lodashFunc = lodash[isTaker ? 'take' + ('last' == methodName ? 'Right' : '') : methodName], retUnwrapped = isTaker || /^find/.test(methodName);
lodashFunc && (lodash.prototype[methodName] = function() {
var value = this.__wrapped__, args = isTaker ? [
1
] : arguments, isLazy = value instanceof LazyWrapper, iteratee = args[0], useLazy = isLazy || isArray(value), interceptor = function(value) {
var result = lodashFunc.apply(lodash, arrayPush([
value
], args));
return isTaker && chainAll ? result[0] : result;
};
useLazy && checkIteratee && 'function' == typeof iteratee && 1 != iteratee.length && // Avoid lazy use if the iteratee has a "length" value other than `1`.
(isLazy = useLazy = !1);
var chainAll = this.__chain__, isHybrid = !!this.__actions__.length, isUnwrapped = retUnwrapped && !chainAll, onlyLazy = isLazy && !isHybrid;
if (!retUnwrapped && useLazy) {
value = onlyLazy ? value : new LazyWrapper(this);
var result = func.apply(value, args);
return result.__actions__.push({
func: thru,
args: [
interceptor
],
thisArg: undefined
}), new LodashWrapper(result, chainAll);
}
return isUnwrapped && onlyLazy ? func.apply(this, args) : (result = this.thru(interceptor), isUnwrapped ? isTaker ? result.value()[0] : result.value() : result);
});
}), // Add `Array` methods to `lodash.prototype`.
arrayEach([
'pop',
'push',
'shift',
'sort',
'splice',
'unshift'
], function(methodName) {
var func = arrayProto[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', retUnwrapped = /^(?:pop|shift)$/.test(methodName);
lodash.prototype[methodName] = function() {
var args = arguments;
if (retUnwrapped && !this.__chain__) {
var value = this.value();
return func.apply(isArray(value) ? value : [], args);
}
return this[chainName](function(value) {
return func.apply(isArray(value) ? value : [], args);
});
};
}), // Map minified method names to their real names.
baseForOwn(LazyWrapper.prototype, function(func, methodName) {
var lodashFunc = lodash[methodName];
if (lodashFunc) {
var key = lodashFunc.name + '';
hasOwnProperty.call(realNames, key) || (realNames[key] = []), realNames[key].push({
name: methodName,
func: lodashFunc
});
}
}), realNames[createHybrid(undefined, 2).name] = [
{
name: 'wrapper',
func: undefined
}
], // Add methods to `LazyWrapper`.
LazyWrapper.prototype.clone = /**
* Creates a clone of the lazy wrapper object.
*
* @private
* @name clone
* @memberOf LazyWrapper
* @returns {Object} Returns the cloned `LazyWrapper` object.
*/ function() {
var result = new LazyWrapper(this.__wrapped__);
return result.__actions__ = copyArray(this.__actions__), result.__dir__ = this.__dir__, result.__filtered__ = this.__filtered__, result.__iteratees__ = copyArray(this.__iteratees__), result.__takeCount__ = this.__takeCount__, result.__views__ = copyArray(this.__views__), result;
}, LazyWrapper.prototype.reverse = /**
* Reverses the direction of lazy iteration.
*
* @private
* @name reverse
* @memberOf LazyWrapper
* @returns {Object} Returns the new reversed `LazyWrapper` object.
*/ function() {
if (this.__filtered__) {
var result = new LazyWrapper(this);
result.__dir__ = -1, result.__filtered__ = !0;
} else result = this.clone(), result.__dir__ *= -1;
return result;
}, LazyWrapper.prototype.value = /**
* Extracts the unwrapped value from its lazy wrapper.
*
* @private
* @name value
* @memberOf LazyWrapper
* @returns {*} Returns the unwrapped value.
*/ function() {
var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = /**
* Gets the view, applying any `transforms` to the `start` and `end` positions.
*
* @private
* @param {number} start The start of the view.
* @param {number} end The end of the view.
* @param {Array} transforms The transformations to apply to the view.
* @returns {Object} Returns an object containing the `start` and `end`
* positions of the view.
*/ function(start, end, transforms) {
for(var index = -1, length = transforms.length; ++index < length;){
var data = transforms[index], size = data.size;
switch(data.type){
case 'drop':
start += size;
break;
case 'dropRight':
end -= size;
break;
case 'take':
end = nativeMin(end, start + size);
break;
case 'takeRight':
start = nativeMax(start, end - size);
}
}
return {
start: start,
end: end
};
}(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : start - 1, iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__);
if (!isArr || !isRight && arrLength == length && takeCount == length) return baseWrapperValue(array, this.__actions__);
var result = [];
outer: for(; length-- && resIndex < takeCount;){
for(var iterIndex = -1, value = array[index += dir]; ++iterIndex < iterLength;){
var data = iteratees[iterIndex], iteratee = data.iteratee, type = data.type, computed = iteratee(value);
if (2 == type) value = computed;
else if (!computed) {
if (1 == type) continue outer;
break outer;
}
}
result[resIndex++] = value;
}
return result;
}, // Add chain sequence methods to the `lodash` wrapper.
lodash.prototype.at = wrapperAt, lodash.prototype.chain = /**
* Creates a `lodash` wrapper instance with explicit method chain sequences enabled.
*
* @name chain
* @memberOf _
* @since 0.1.0
* @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var users = [
* { 'user': 'barney', 'age': 36 },
* { 'user': 'fred', 'age': 40 }
* ];
*
* // A sequence without explicit chaining.
* _(users).head();
* // => { 'user': 'barney', 'age': 36 }
*
* // A sequence with explicit chaining.
* _(users)
* .chain()
* .head()
* .pick('user')
* .value();
* // => { 'user': 'barney' }
*/ function() {
return chain(this);
}, lodash.prototype.commit = /**
* Executes the chain sequence and returns the wrapped result.
*
* @name commit
* @memberOf _
* @since 3.2.0
* @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var array = [1, 2];
* var wrapped = _(array).push(3);
*
* console.log(array);
* // => [1, 2]
*
* wrapped = wrapped.commit();
* console.log(array);
* // => [1, 2, 3]
*
* wrapped.last();
* // => 3
*
* console.log(array);
* // => [1, 2, 3]
*/ function() {
return new LodashWrapper(this.value(), this.__chain__);
}, lodash.prototype.next = /**
* Gets the next value on a wrapped object following the
* [iterator protocol](https://mdn.io/iteration_protocols#iterator).
*
* @name next
* @memberOf _
* @since 4.0.0
* @category Seq
* @returns {Object} Returns the next iterator value.
* @example
*
* var wrapped = _([1, 2]);
*
* wrapped.next();
* // => { 'done': false, 'value': 1 }
*
* wrapped.next();
* // => { 'done': false, 'value': 2 }
*
* wrapped.next();
* // => { 'done': true, 'value': undefined }
*/ function() {
this.__values__ === undefined && (this.__values__ = toArray(this.value()));
var done = this.__index__ >= this.__values__.length, value = done ? undefined : this.__values__[this.__index__++];
return {
done: done,
value: value
};
}, lodash.prototype.plant = /**
* Creates a clone of the chain sequence planting `value` as the wrapped value.
*
* @name plant
* @memberOf _
* @since 3.2.0
* @category Seq
* @param {*} value The value to plant.
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* function square(n) {
* return n * n;
* }
*
* var wrapped = _([1, 2]).map(square);
* var other = wrapped.plant([3, 4]);
*
* other.value();
* // => [9, 16]
*
* wrapped.value();
* // => [1, 4]
*/ function(value) {
for(var result, parent = this; parent instanceof baseLodash;){
var clone = wrapperClone(parent);
clone.__index__ = 0, clone.__values__ = undefined, result ? previous.__wrapped__ = clone : result = clone;
var previous = clone;
parent = parent.__wrapped__;
}
return previous.__wrapped__ = value, result;
}, lodash.prototype.reverse = /**
* This method is the wrapper version of `_.reverse`.
*
* **Note:** This method mutates the wrapped array.
*
* @name reverse
* @memberOf _
* @since 0.1.0
* @category Seq
* @returns {Object} Returns the new `lodash` wrapper instance.
* @example
*
* var array = [1, 2, 3];
*
* _(array).reverse().value()
* // => [3, 2, 1]
*
* console.log(array);
* // => [3, 2, 1]
*/ function() {
var value = this.__wrapped__;
if (value instanceof LazyWrapper) {
var wrapped = value;
return this.__actions__.length && (wrapped = new LazyWrapper(this)), (wrapped = wrapped.reverse()).__actions__.push({
func: thru,
args: [
reverse
],
thisArg: undefined
}), new LodashWrapper(wrapped, this.__chain__);
}
return this.thru(reverse);
}, lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = /**
* Executes the chain sequence to resolve the unwrapped value.
*
* @name value
* @memberOf _
* @since 0.1.0
* @alias toJSON, valueOf
* @category Seq
* @returns {*} Returns the resolved unwrapped value.
* @example
*
* _([1, 2, 3]).value();
* // => [1, 2, 3]
*/ function() {
return baseWrapperValue(this.__wrapped__, this.__actions__);
}, // Add lazy aliases.
lodash.prototype.first = lodash.prototype.head, symIterator && (lodash.prototype[symIterator] = /**
* Enables the wrapper to be iterable.
*
* @name Symbol.iterator
* @memberOf _
* @since 4.0.0
* @category Seq
* @returns {Object} Returns the wrapper object.
* @example
*
* var wrapped = _([1, 2]);
*
* wrapped[Symbol.iterator]() === wrapped;
* // => true
*
* Array.from(wrapped);
* // => [1, 2]
*/ function() {
return this;
}), lodash);
}();
'function' == typeof define && 'object' == typeof define.amd && define.amd ? (// Expose Lodash on the global object to prevent errors when Lodash is
// loaded by a script tag in the presence of an AMD loader.
// See http://requirejs.org/docs/errors.html#mismatch for more details.
// Use `_.noConflict` to remove Lodash from the global object.
root._ = _, // Define as an anonymous module so, through path mapping, it can be
// referenced as the "underscore" module.
define(function() {
return _;
})) : freeModule ? (// Export for Node.js.
(freeModule.exports = _)._ = _, // Export for CommonJS support.
freeExports._ = _) : // Export to the global object.
root._ = _;
}).call(this);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/benches-full/moment.js | JavaScript | //! moment.js
//! version : 2.29.1
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com
!function(global, factory) {
'object' == typeof exports && 'undefined' != typeof module ? module.exports = factory() : 'function' == typeof define && define.amd ? define(factory) : global.moment = factory();
}(this, function() {
'use strict';
function hooks() {
return hookCallback.apply(null, arguments);
}
function isArray(input) {
return input instanceof Array || '[object Array]' === Object.prototype.toString.call(input);
}
function isObject(input) {
// IE8 will treat undefined and null as object if it wasn't for
// input != null
return null != input && '[object Object]' === Object.prototype.toString.call(input);
}
function hasOwnProp(a, b) {
return Object.prototype.hasOwnProperty.call(a, b);
}
function isObjectEmpty(obj) {
var k;
if (Object.getOwnPropertyNames) return 0 === Object.getOwnPropertyNames(obj).length;
for(k in obj)if (hasOwnProp(obj, k)) return !1;
return !0;
}
function isUndefined(input) {
return void 0 === input;
}
function isNumber(input) {
return 'number' == typeof input || '[object Number]' === Object.prototype.toString.call(input);
}
function isDate(input) {
return input instanceof Date || '[object Date]' === Object.prototype.toString.call(input);
}
function map(arr, fn) {
var i, res = [];
for(i = 0; i < arr.length; ++i)res.push(fn(arr[i], i));
return res;
}
function extend(a, b) {
for(var i in b)hasOwnProp(b, i) && (a[i] = b[i]);
return hasOwnProp(b, 'toString') && (a.toString = b.toString), hasOwnProp(b, 'valueOf') && (a.valueOf = b.valueOf), a;
}
function createUTC(input, format, locale, strict) {
return createLocalOrUTC(input, format, locale, strict, !0).utc();
}
function getParsingFlags(m) {
return null == m._pf && (m._pf = {
empty: !1,
unusedTokens: [],
unusedInput: [],
overflow: -2,
charsLeftOver: 0,
nullInput: !1,
invalidEra: null,
invalidMonth: null,
invalidFormat: !1,
userInvalidated: !1,
iso: !1,
parsedDateParts: [],
era: null,
meridiem: null,
rfc2822: !1,
weekdayMismatch: !1
}), m._pf;
}
function isValid(m) {
if (null == m._isValid) {
var flags = getParsingFlags(m), parsedParts = some.call(flags.parsedDateParts, function(i) {
return null != i;
}), isNowValid = !isNaN(m._d.getTime()) && flags.overflow < 0 && !flags.empty && !flags.invalidEra && !flags.invalidMonth && !flags.invalidWeekday && !flags.weekdayMismatch && !flags.nullInput && !flags.invalidFormat && !flags.userInvalidated && (!flags.meridiem || flags.meridiem && parsedParts);
if (m._strict && (isNowValid = isNowValid && 0 === flags.charsLeftOver && 0 === flags.unusedTokens.length && void 0 === flags.bigHour), null != Object.isFrozen && Object.isFrozen(m)) return isNowValid;
m._isValid = isNowValid;
}
return m._isValid;
}
function createInvalid(flags) {
var m = createUTC(NaN);
return null != flags ? extend(getParsingFlags(m), flags) : getParsingFlags(m).userInvalidated = !0, m;
}
some = Array.prototype.some ? Array.prototype.some : function(fun) {
var i, t = Object(this), len = t.length >>> 0;
for(i = 0; i < len; i++)if (i in t && fun.call(this, t[i], i, t)) return !0;
return !1;
};
// Plugins that add properties should also add the key here (null value),
// so we can properly clone ourselves.
var token, getSetMillisecond, momentProperties = hooks.momentProperties = [], updateInProgress = !1;
function copyConfig(to, from) {
var i, prop, val;
if (isUndefined(from._isAMomentObject) || (to._isAMomentObject = from._isAMomentObject), isUndefined(from._i) || (to._i = from._i), isUndefined(from._f) || (to._f = from._f), isUndefined(from._l) || (to._l = from._l), isUndefined(from._strict) || (to._strict = from._strict), isUndefined(from._tzm) || (to._tzm = from._tzm), isUndefined(from._isUTC) || (to._isUTC = from._isUTC), isUndefined(from._offset) || (to._offset = from._offset), isUndefined(from._pf) || (to._pf = getParsingFlags(from)), isUndefined(from._locale) || (to._locale = from._locale), momentProperties.length > 0) for(i = 0; i < momentProperties.length; i++)isUndefined(val = from[prop = momentProperties[i]]) || (to[prop] = val);
return to;
}
// Moment prototype object
function Moment(config) {
copyConfig(this, config), this._d = new Date(null != config._d ? config._d.getTime() : NaN), this.isValid() || (this._d = new Date(NaN)), !1 === updateInProgress && (updateInProgress = !0, hooks.updateOffset(this), updateInProgress = !1);
}
function isMoment(obj) {
return obj instanceof Moment || null != obj && null != obj._isAMomentObject;
}
function warn(msg) {
!1 === hooks.suppressDeprecationWarnings && 'undefined' != typeof console && console.warn && console.warn('Deprecation warning: ' + msg);
}
function deprecate(msg, fn) {
var firstTime = !0;
return extend(function() {
if (null != hooks.deprecationHandler && hooks.deprecationHandler(null, msg), firstTime) {
var arg, i, key, args = [];
for(i = 0; i < arguments.length; i++){
if (arg = '', 'object' == typeof arguments[i]) {
for(key in arg += '\n[' + i + '] ', arguments[0])hasOwnProp(arguments[0], key) && (arg += key + ': ' + arguments[0][key] + ', ');
arg = arg.slice(0, -2);
} else arg = arguments[i];
args.push(arg);
}
warn(msg + '\nArguments: ' + Array.prototype.slice.call(args).join('') + '\n' + Error().stack), firstTime = !1;
}
return fn.apply(this, arguments);
}, fn);
}
var deprecations = {};
function deprecateSimple(name, msg) {
null != hooks.deprecationHandler && hooks.deprecationHandler(name, msg), deprecations[name] || (warn(msg), deprecations[name] = !0);
}
function isFunction(input) {
return 'undefined' != typeof Function && input instanceof Function || '[object Function]' === Object.prototype.toString.call(input);
}
function mergeConfigs(parentConfig, childConfig) {
var prop, res = extend({}, parentConfig);
for(prop in childConfig)hasOwnProp(childConfig, prop) && (isObject(parentConfig[prop]) && isObject(childConfig[prop]) ? (res[prop] = {}, extend(res[prop], parentConfig[prop]), extend(res[prop], childConfig[prop])) : null != childConfig[prop] ? res[prop] = childConfig[prop] : delete res[prop]);
for(prop in parentConfig)hasOwnProp(parentConfig, prop) && !hasOwnProp(childConfig, prop) && isObject(parentConfig[prop]) && // make sure changes to properties don't modify parent config
(res[prop] = extend({}, res[prop]));
return res;
}
function Locale(config) {
null != config && this.set(config);
}
function zeroFill(number, targetLength, forceSign) {
var absNumber = '' + Math.abs(number);
return (number >= 0 ? forceSign ? '+' : '' : '-') + Math.pow(10, Math.max(0, targetLength - absNumber.length)).toString().substr(1) + absNumber;
}
hooks.suppressDeprecationWarnings = !1, hooks.deprecationHandler = null, keys = Object.keys ? Object.keys : function(obj) {
var i, res = [];
for(i in obj)hasOwnProp(obj, i) && res.push(i);
return res;
};
var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, formatFunctions = {}, formatTokenFunctions = {};
// token: 'M'
// padded: ['MM', 2]
// ordinal: 'Mo'
// callback: function () { this.month() + 1 }
function addFormatToken(token, padded, ordinal, callback) {
var func = callback;
'string' == typeof callback && (func = function() {
return this[callback]();
}), token && (formatTokenFunctions[token] = func), padded && (formatTokenFunctions[padded[0]] = function() {
return zeroFill(func.apply(this, arguments), padded[1], padded[2]);
}), ordinal && (formatTokenFunctions[ordinal] = function() {
return this.localeData().ordinal(func.apply(this, arguments), token);
});
}
// format date using native date object
function formatMoment(m, format) {
return m.isValid() ? (formatFunctions[format = expandFormat(format, m.localeData())] = formatFunctions[format] || function(format) {
var input, i, length, array = format.match(formattingTokens);
for(i = 0, length = array.length; i < length; i++)formatTokenFunctions[array[i]] ? array[i] = formatTokenFunctions[array[i]] : array[i] = (input = array[i]).match(/\[[\s\S]/) ? input.replace(/^\[|\]$/g, '') : input.replace(/\\/g, '');
return function(mom) {
var i, output = '';
for(i = 0; i < length; i++)output += isFunction(array[i]) ? array[i].call(mom, format) : array[i];
return output;
};
}(format), formatFunctions[format](m)) : m.localeData().invalidDate();
}
function expandFormat(format, locale) {
var i = 5;
function replaceLongDateFormatTokens(input) {
return locale.longDateFormat(input) || input;
}
for(localFormattingTokens.lastIndex = 0; i >= 0 && localFormattingTokens.test(format);)format = format.replace(localFormattingTokens, replaceLongDateFormatTokens), localFormattingTokens.lastIndex = 0, i -= 1;
return format;
}
var aliases = {};
function addUnitAlias(unit, shorthand) {
var lowerCase = unit.toLowerCase();
aliases[lowerCase] = aliases[lowerCase + 's'] = aliases[shorthand] = unit;
}
function normalizeUnits(units) {
return 'string' == typeof units ? aliases[units] || aliases[units.toLowerCase()] : void 0;
}
function normalizeObjectUnits(inputObject) {
var normalizedProp, prop, normalizedInput = {};
for(prop in inputObject)hasOwnProp(inputObject, prop) && (normalizedProp = normalizeUnits(prop)) && (normalizedInput[normalizedProp] = inputObject[prop]);
return normalizedInput;
}
var priorities = {};
function isLeapYear(year) {
return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
}
function absFloor(number) {
return number < 0 ? Math.ceil(number) || 0 : Math.floor(number);
}
function toInt(argumentForCoercion) {
var coercedNumber = +argumentForCoercion, value = 0;
return 0 !== coercedNumber && isFinite(coercedNumber) && (value = absFloor(coercedNumber)), value;
}
function makeGetSet(unit, keepTime) {
return function(value) {
return null != value ? (set$1(this, unit, value), hooks.updateOffset(this, keepTime), this) : get(this, unit);
};
}
function get(mom, unit) {
return mom.isValid() ? mom._d['get' + (mom._isUTC ? 'UTC' : '') + unit]() : NaN;
}
function set$1(mom, unit, value) {
mom.isValid() && !isNaN(value) && ('FullYear' === unit && isLeapYear(mom.year()) && 1 === mom.month() && 29 === mom.date() ? (value = toInt(value), mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value, mom.month(), daysInMonth(value, mom.month()))) : mom._d['set' + (mom._isUTC ? 'UTC' : '') + unit](value));
}
var hookCallback, some, keys, regexes, match1 = /\d/, match2 = /\d\d/, match3 = /\d{3}/, match4 = /\d{4}/, match6 = /[+-]?\d{6}/, match1to2 = /\d\d?/, match3to4 = /\d\d\d\d?/, match5to6 = /\d\d\d\d\d\d?/, match1to3 = /\d{1,3}/, match1to4 = /\d{1,4}/, match1to6 = /[+-]?\d{1,6}/, matchUnsigned = /\d+/, matchSigned = /[+-]?\d+/, matchOffset = /Z|[+-]\d\d:?\d\d/gi, matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, // any word (or two) characters or numbers including two/three word month in arabic.
// includes scottish gaelic two word and hyphenated months
matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i;
function addRegexToken(token, regex, strictRegex) {
regexes[token] = isFunction(regex) ? regex : function(isStrict, localeData) {
return isStrict && strictRegex ? strictRegex : regex;
};
}
function regexEscape(s) {
return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
regexes = {};
var tokens = {};
function addParseToken(token, callback) {
var i, func = callback;
for('string' == typeof token && (token = [
token
]), isNumber(callback) && (func = function(input, array) {
array[callback] = toInt(input);
}), i = 0; i < token.length; i++)tokens[token[i]] = func;
}
function addWeekParseToken(token, callback) {
addParseToken(token, function(input, array, config, token) {
config._w = config._w || {}, callback(input, config._w, config, token);
});
}
function daysInMonth(year, month) {
if (isNaN(year) || isNaN(month)) return NaN;
var modMonth = (month % 12 + 12) % 12;
return year += (month - modMonth) / 12, 1 === modMonth ? isLeapYear(year) ? 29 : 28 : 31 - modMonth % 7 % 2;
}
indexOf = Array.prototype.indexOf ? Array.prototype.indexOf : function(o) {
// I know
var i;
for(i = 0; i < this.length; ++i)if (this[i] === o) return i;
return -1;
}, // FORMATTING
addFormatToken('M', [
'MM',
2
], 'Mo', function() {
return this.month() + 1;
}), addFormatToken('MMM', 0, 0, function(format) {
return this.localeData().monthsShort(this, format);
}), addFormatToken('MMMM', 0, 0, function(format) {
return this.localeData().months(this, format);
}), // ALIASES
addUnitAlias('month', 'M'), priorities.month = 8, // PARSING
addRegexToken('M', match1to2), addRegexToken('MM', match1to2, match2), addRegexToken('MMM', function(isStrict, locale) {
return locale.monthsShortRegex(isStrict);
}), addRegexToken('MMMM', function(isStrict, locale) {
return locale.monthsRegex(isStrict);
}), addParseToken([
'M',
'MM'
], function(input, array) {
array[1] = toInt(input) - 1;
}), addParseToken([
'MMM',
'MMMM'
], function(input, array, config, token) {
var month = config._locale.monthsParse(input, token, config._strict);
// if we didn't find a month name, mark the date as invalid.
null != month ? array[1] = month : getParsingFlags(config).invalidMonth = input;
});
// LOCALES
var defaultLocaleMonthsShort = 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/;
function handleStrictParse(monthName, format, strict) {
var i, ii, mom, llc = monthName.toLocaleLowerCase();
if (!this._monthsParse) for(i = 0, // this is not used
this._monthsParse = [], this._longMonthsParse = [], this._shortMonthsParse = []; i < 12; ++i)mom = createUTC([
2000,
i
]), this._shortMonthsParse[i] = this.monthsShort(mom, '').toLocaleLowerCase(), this._longMonthsParse[i] = this.months(mom, '').toLocaleLowerCase();
return strict ? 'MMM' === format ? -1 !== (ii = indexOf.call(this._shortMonthsParse, llc)) ? ii : null : -1 !== (ii = indexOf.call(this._longMonthsParse, llc)) ? ii : null : 'MMM' === format ? -1 !== (ii = indexOf.call(this._shortMonthsParse, llc)) ? ii : -1 !== (ii = indexOf.call(this._longMonthsParse, llc)) ? ii : null : -1 !== (ii = indexOf.call(this._longMonthsParse, llc)) ? ii : -1 !== (ii = indexOf.call(this._shortMonthsParse, llc)) ? ii : null;
}
// MOMENTS
function setMonth(mom, value) {
var dayOfMonth;
if (!mom.isValid()) // No op
return mom;
if ('string' == typeof value) {
if (/^\d+$/.test(value)) value = toInt(value);
else // TODO: Another silent failure?
if (!isNumber(value = mom.localeData().monthsParse(value))) return mom;
}
return dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)), mom._d['set' + (mom._isUTC ? 'UTC' : '') + 'Month'](value, dayOfMonth), mom;
}
function getSetMonth(value) {
return null != value ? (setMonth(this, value), hooks.updateOffset(this, !0), this) : get(this, 'Month');
}
function computeMonthsParse() {
function cmpLenRev(a, b) {
return b.length - a.length;
}
var i, mom, shortPieces = [], longPieces = [], mixedPieces = [];
for(i = 0; i < 12; i++)// make the regex if we don't have it already
mom = createUTC([
2000,
i
]), shortPieces.push(this.monthsShort(mom, '')), longPieces.push(this.months(mom, '')), mixedPieces.push(this.months(mom, '')), mixedPieces.push(this.monthsShort(mom, ''));
for(// Sorting makes sure if one month (or abbr) is a prefix of another it
// will match the longer piece.
shortPieces.sort(cmpLenRev), longPieces.sort(cmpLenRev), mixedPieces.sort(cmpLenRev), i = 0; i < 12; i++)shortPieces[i] = regexEscape(shortPieces[i]), longPieces[i] = regexEscape(longPieces[i]);
for(i = 0; i < 24; i++)mixedPieces[i] = regexEscape(mixedPieces[i]);
this._monthsRegex = RegExp('^(' + mixedPieces.join('|') + ')', 'i'), this._monthsShortRegex = this._monthsRegex, this._monthsStrictRegex = RegExp('^(' + longPieces.join('|') + ')', 'i'), this._monthsShortStrictRegex = RegExp('^(' + shortPieces.join('|') + ')', 'i');
}
// HELPERS
function daysInYear(year) {
return isLeapYear(year) ? 366 : 365;
}
// FORMATTING
addFormatToken('Y', 0, 0, function() {
var y = this.year();
return y <= 9999 ? zeroFill(y, 4) : '+' + y;
}), addFormatToken(0, [
'YY',
2
], 0, function() {
return this.year() % 100;
}), addFormatToken(0, [
'YYYY',
4
], 0, 'year'), addFormatToken(0, [
'YYYYY',
5
], 0, 'year'), addFormatToken(0, [
'YYYYYY',
6,
!0
], 0, 'year'), // ALIASES
addUnitAlias('year', 'y'), priorities.year = 1, // PARSING
addRegexToken('Y', matchSigned), addRegexToken('YY', match1to2, match2), addRegexToken('YYYY', match1to4, match4), addRegexToken('YYYYY', match1to6, match6), addRegexToken('YYYYYY', match1to6, match6), addParseToken([
'YYYYY',
'YYYYYY'
], 0), addParseToken('YYYY', function(input, array) {
array[0] = 2 === input.length ? hooks.parseTwoDigitYear(input) : toInt(input);
}), addParseToken('YY', function(input, array) {
array[0] = hooks.parseTwoDigitYear(input);
}), addParseToken('Y', function(input, array) {
array[0] = parseInt(input, 10);
}), // HOOKS
hooks.parseTwoDigitYear = function(input) {
return toInt(input) + (toInt(input) > 68 ? 1900 : 2000);
};
// MOMENTS
var getSetYear = makeGetSet('FullYear', !0);
function createDate(y, m, d, h, M, s, ms) {
// can't just apply() to create a date:
// https://stackoverflow.com/q/181348
var date;
return y < 100 && y >= 0 ? isFinite(// preserve leap years using a full 400 year cycle, then reset
(date = new Date(y + 400, m, d, h, M, s, ms)).getFullYear()) && date.setFullYear(y) : date = new Date(y, m, d, h, M, s, ms), date;
}
function createUTCDate(y) {
var date, args;
return y < 100 && y >= 0 ? (args = Array.prototype.slice.call(arguments), // preserve leap years using a full 400 year cycle, then reset
args[0] = y + 400, isFinite((date = new Date(Date.UTC.apply(null, args))).getUTCFullYear()) && date.setUTCFullYear(y)) : date = new Date(Date.UTC.apply(null, arguments)), date;
}
// start-of-first-week - start-of-year
function firstWeekOffset(year, dow, doy) {
var fwd = 7 + dow - doy;
return -((7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7) + fwd - 1;
}
// https://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday
function dayOfYearFromWeeks(year, week, weekday, dow, doy) {
var resYear, resDayOfYear, dayOfYear = 1 + 7 * (week - 1) + (7 + weekday - dow) % 7 + firstWeekOffset(year, dow, doy);
return dayOfYear <= 0 ? resDayOfYear = daysInYear(resYear = year - 1) + dayOfYear : dayOfYear > daysInYear(year) ? (resYear = year + 1, resDayOfYear = dayOfYear - daysInYear(year)) : (resYear = year, resDayOfYear = dayOfYear), {
year: resYear,
dayOfYear: resDayOfYear
};
}
function weekOfYear(mom, dow, doy) {
var resWeek, resYear, weekOffset = firstWeekOffset(mom.year(), dow, doy), week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1;
return week < 1 ? resWeek = week + weeksInYear(resYear = mom.year() - 1, dow, doy) : week > weeksInYear(mom.year(), dow, doy) ? (resWeek = week - weeksInYear(mom.year(), dow, doy), resYear = mom.year() + 1) : (resYear = mom.year(), resWeek = week), {
week: resWeek,
year: resYear
};
}
function weeksInYear(year, dow, doy) {
var weekOffset = firstWeekOffset(year, dow, doy), weekOffsetNext = firstWeekOffset(year + 1, dow, doy);
return (daysInYear(year) - weekOffset + weekOffsetNext) / 7;
}
// LOCALES
function shiftWeekdays(ws, n) {
return ws.slice(n, 7).concat(ws.slice(0, n));
}
// FORMATTING
addFormatToken('w', [
'ww',
2
], 'wo', 'week'), addFormatToken('W', [
'WW',
2
], 'Wo', 'isoWeek'), // ALIASES
addUnitAlias('week', 'w'), addUnitAlias('isoWeek', 'W'), priorities.week = 5, priorities.isoWeek = 5, // PARSING
addRegexToken('w', match1to2), addRegexToken('ww', match1to2, match2), addRegexToken('W', match1to2), addRegexToken('WW', match1to2, match2), addWeekParseToken([
'w',
'ww',
'W',
'WW'
], function(input, week, config, token) {
week[token.substr(0, 1)] = toInt(input);
}), // FORMATTING
addFormatToken('d', 0, 'do', 'day'), addFormatToken('dd', 0, 0, function(format) {
return this.localeData().weekdaysMin(this, format);
}), addFormatToken('ddd', 0, 0, function(format) {
return this.localeData().weekdaysShort(this, format);
}), addFormatToken('dddd', 0, 0, function(format) {
return this.localeData().weekdays(this, format);
}), addFormatToken('e', 0, 0, 'weekday'), addFormatToken('E', 0, 0, 'isoWeekday'), // ALIASES
addUnitAlias('day', 'd'), addUnitAlias('weekday', 'e'), addUnitAlias('isoWeekday', 'E'), priorities.day = 11, priorities.weekday = 11, priorities.isoWeekday = 11, // PARSING
addRegexToken('d', match1to2), addRegexToken('e', match1to2), addRegexToken('E', match1to2), addRegexToken('dd', function(isStrict, locale) {
return locale.weekdaysMinRegex(isStrict);
}), addRegexToken('ddd', function(isStrict, locale) {
return locale.weekdaysShortRegex(isStrict);
}), addRegexToken('dddd', function(isStrict, locale) {
return locale.weekdaysRegex(isStrict);
}), addWeekParseToken([
'dd',
'ddd',
'dddd'
], function(input, week, config, token) {
var weekday = config._locale.weekdaysParse(input, token, config._strict);
// if we didn't get a weekday name, mark the date as invalid
null != weekday ? week.d = weekday : getParsingFlags(config).invalidWeekday = input;
}), addWeekParseToken([
'd',
'e',
'E'
], function(input, week, config, token) {
week[token] = toInt(input);
});
var defaultLocaleWeekdaysShort = 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_');
function handleStrictParse$1(weekdayName, format, strict) {
var i, ii, mom, llc = weekdayName.toLocaleLowerCase();
if (!this._weekdaysParse) for(i = 0, this._weekdaysParse = [], this._shortWeekdaysParse = [], this._minWeekdaysParse = []; i < 7; ++i)mom = createUTC([
2000,
1
]).day(i), this._minWeekdaysParse[i] = this.weekdaysMin(mom, '').toLocaleLowerCase(), this._shortWeekdaysParse[i] = this.weekdaysShort(mom, '').toLocaleLowerCase(), this._weekdaysParse[i] = this.weekdays(mom, '').toLocaleLowerCase();
return strict ? 'dddd' === format ? -1 !== (ii = indexOf.call(this._weekdaysParse, llc)) ? ii : null : 'ddd' === format ? -1 !== (ii = indexOf.call(this._shortWeekdaysParse, llc)) ? ii : null : -1 !== (ii = indexOf.call(this._minWeekdaysParse, llc)) ? ii : null : 'dddd' === format ? -1 !== (ii = indexOf.call(this._weekdaysParse, llc)) || -1 !== (ii = indexOf.call(this._shortWeekdaysParse, llc)) ? ii : -1 !== (ii = indexOf.call(this._minWeekdaysParse, llc)) ? ii : null : 'ddd' === format ? -1 !== (ii = indexOf.call(this._shortWeekdaysParse, llc)) || -1 !== (ii = indexOf.call(this._weekdaysParse, llc)) ? ii : -1 !== (ii = indexOf.call(this._minWeekdaysParse, llc)) ? ii : null : -1 !== (ii = indexOf.call(this._minWeekdaysParse, llc)) || -1 !== (ii = indexOf.call(this._weekdaysParse, llc)) ? ii : -1 !== (ii = indexOf.call(this._shortWeekdaysParse, llc)) ? ii : null;
}
function computeWeekdaysParse() {
function cmpLenRev(a, b) {
return b.length - a.length;
}
var i, mom, minp, shortp, longp, minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [];
for(i = 0; i < 7; i++)// make the regex if we don't have it already
mom = createUTC([
2000,
1
]).day(i), minp = regexEscape(this.weekdaysMin(mom, '')), shortp = regexEscape(this.weekdaysShort(mom, '')), longp = regexEscape(this.weekdays(mom, '')), minPieces.push(minp), shortPieces.push(shortp), longPieces.push(longp), mixedPieces.push(minp), mixedPieces.push(shortp), mixedPieces.push(longp);
// Sorting makes sure if one weekday (or abbr) is a prefix of another it
// will match the longer piece.
minPieces.sort(cmpLenRev), shortPieces.sort(cmpLenRev), longPieces.sort(cmpLenRev), mixedPieces.sort(cmpLenRev), this._weekdaysRegex = RegExp('^(' + mixedPieces.join('|') + ')', 'i'), this._weekdaysShortRegex = this._weekdaysRegex, this._weekdaysMinRegex = this._weekdaysRegex, this._weekdaysStrictRegex = RegExp('^(' + longPieces.join('|') + ')', 'i'), this._weekdaysShortStrictRegex = RegExp('^(' + shortPieces.join('|') + ')', 'i'), this._weekdaysMinStrictRegex = RegExp('^(' + minPieces.join('|') + ')', 'i');
}
// FORMATTING
function hFormat() {
return this.hours() % 12 || 12;
}
function meridiem(token, lowercase) {
addFormatToken(token, 0, 0, function() {
return this.localeData().meridiem(this.hours(), this.minutes(), lowercase);
});
}
// PARSING
function matchMeridiem(isStrict, locale) {
return locale._meridiemParse;
}
addFormatToken('H', [
'HH',
2
], 0, 'hour'), addFormatToken('h', [
'hh',
2
], 0, hFormat), addFormatToken('k', [
'kk',
2
], 0, function() {
return this.hours() || 24;
}), addFormatToken('hmm', 0, 0, function() {
return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2);
}), addFormatToken('hmmss', 0, 0, function() {
return '' + hFormat.apply(this) + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2);
}), addFormatToken('Hmm', 0, 0, function() {
return '' + this.hours() + zeroFill(this.minutes(), 2);
}), addFormatToken('Hmmss', 0, 0, function() {
return '' + this.hours() + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2);
}), meridiem('a', !0), meridiem('A', !1), // ALIASES
addUnitAlias('hour', 'h'), priorities.hour = 13, addRegexToken('a', matchMeridiem), addRegexToken('A', matchMeridiem), addRegexToken('H', match1to2), addRegexToken('h', match1to2), addRegexToken('k', match1to2), addRegexToken('HH', match1to2, match2), addRegexToken('hh', match1to2, match2), addRegexToken('kk', match1to2, match2), addRegexToken('hmm', match3to4), addRegexToken('hmmss', match5to6), addRegexToken('Hmm', match3to4), addRegexToken('Hmmss', match5to6), addParseToken([
'H',
'HH'
], 3), addParseToken([
'k',
'kk'
], function(input, array, config) {
var kInput = toInt(input);
array[3] = 24 === kInput ? 0 : kInput;
}), addParseToken([
'a',
'A'
], function(input, array, config) {
config._isPm = config._locale.isPM(input), config._meridiem = input;
}), addParseToken([
'h',
'hh'
], function(input, array, config) {
array[3] = toInt(input), getParsingFlags(config).bigHour = !0;
}), addParseToken('hmm', function(input, array, config) {
var pos = input.length - 2;
array[3] = toInt(input.substr(0, pos)), array[4] = toInt(input.substr(pos)), getParsingFlags(config).bigHour = !0;
}), addParseToken('hmmss', function(input, array, config) {
var pos1 = input.length - 4, pos2 = input.length - 2;
array[3] = toInt(input.substr(0, pos1)), array[4] = toInt(input.substr(pos1, 2)), array[5] = toInt(input.substr(pos2)), getParsingFlags(config).bigHour = !0;
}), addParseToken('Hmm', function(input, array, config) {
var pos = input.length - 2;
array[3] = toInt(input.substr(0, pos)), array[4] = toInt(input.substr(pos));
}), addParseToken('Hmmss', function(input, array, config) {
var pos1 = input.length - 4, pos2 = input.length - 2;
array[3] = toInt(input.substr(0, pos1)), array[4] = toInt(input.substr(pos1, 2)), array[5] = toInt(input.substr(pos2));
});
var indexOf, globalLocale, // Setting the hour should keep the time, because the user explicitly
// specified which hour they want. So trying to maintain the same hour (in
// a new timezone) makes sense. Adding/subtracting hours does not follow
// this rule.
getSetHour = makeGetSet('Hours', !0), baseConfig = {
calendar: {
sameDay: '[Today at] LT',
nextDay: '[Tomorrow at] LT',
nextWeek: 'dddd [at] LT',
lastDay: '[Yesterday at] LT',
lastWeek: '[Last] dddd [at] LT',
sameElse: 'L'
},
longDateFormat: {
LTS: 'h:mm:ss A',
LT: 'h:mm A',
L: 'MM/DD/YYYY',
LL: 'MMMM D, YYYY',
LLL: 'MMMM D, YYYY h:mm A',
LLLL: 'dddd, MMMM D, YYYY h:mm A'
},
invalidDate: 'Invalid date',
ordinal: '%d',
dayOfMonthOrdinalParse: /\d{1,2}/,
relativeTime: {
future: 'in %s',
past: '%s ago',
s: 'a few seconds',
ss: '%d seconds',
m: 'a minute',
mm: '%d minutes',
h: 'an hour',
hh: '%d hours',
d: 'a day',
dd: '%d days',
w: 'a week',
ww: '%d weeks',
M: 'a month',
MM: '%d months',
y: 'a year',
yy: '%d years'
},
months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'),
monthsShort: defaultLocaleMonthsShort,
week: {
dow: 0,
doy: 6
},
weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'),
weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),
weekdaysShort: defaultLocaleWeekdaysShort,
meridiemParse: /[ap]\.?m?\.?/i
}, locales = {}, localeFamilies = {};
function normalizeLocale(key) {
return key ? key.toLowerCase().replace('_', '-') : key;
}
function loadLocale(name) {
var oldLocale = null;
// TODO: Find a better way to register and load all the locales in Node
if (void 0 === locales[name] && 'undefined' != typeof module && module && module.exports) try {
oldLocale = globalLocale._abbr, require('./locale/' + name), getSetGlobalLocale(oldLocale);
} catch (e) {
// mark as not found to avoid repeating expensive file require call causing high CPU
// when trying to find en-US, en_US, en-us for every format call
locales[name] = null; // null means not found
}
return locales[name];
}
// This function will load locale and then set the global locale. If
// no arguments are passed in, it will simply return the current global
// locale key.
function getSetGlobalLocale(key, values) {
var data;
return key && ((data = isUndefined(values) ? getLocale(key) : defineLocale(key, values)) ? // moment.duration._locale = moment._locale = data;
globalLocale = data : 'undefined' != typeof console && console.warn && //warn user if arguments are passed but the locale could not be set
console.warn('Locale ' + key + ' not found. Did you forget to load it?')), globalLocale._abbr;
}
function defineLocale(name, config) {
if (null === config) return(// useful for testing
delete locales[name], null);
var locale, parentConfig = baseConfig;
if (config.abbr = name, null != locales[name]) deprecateSimple('defineLocaleOverride', "use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."), parentConfig = locales[name]._config;
else if (null != config.parentLocale) {
if (null != locales[config.parentLocale]) parentConfig = locales[config.parentLocale]._config;
else {
if (null == (locale = loadLocale(config.parentLocale))) return localeFamilies[config.parentLocale] || (localeFamilies[config.parentLocale] = []), localeFamilies[config.parentLocale].push({
name: name,
config: config
}), null;
parentConfig = locale._config;
}
}
return locales[name] = new Locale(mergeConfigs(parentConfig, config)), localeFamilies[name] && localeFamilies[name].forEach(function(x) {
defineLocale(x.name, x.config);
}), // backwards compat for now: also set the locale
// make sure we set the locale AFTER all child locales have been
// created, so we won't end up with the child locale set.
getSetGlobalLocale(name), locales[name];
}
// returns locale data
function getLocale(key) {
var locale;
if (key && key._locale && key._locale._abbr && (key = key._locale._abbr), !key) return globalLocale;
if (!isArray(key)) {
if (//short-circuit everything else
locale = loadLocale(key)) return locale;
key = [
key
];
}
return(// pick the locale from the array
// try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each
// substring from most specific to least, but move to the next array item if it's a more specific variant than the current root
function(names) {
for(var j, next, locale, split, i = 0; i < names.length;){
for(j = (split = normalizeLocale(names[i]).split('-')).length, next = (next = normalizeLocale(names[i + 1])) ? next.split('-') : null; j > 0;){
if (locale = loadLocale(split.slice(0, j).join('-'))) return locale;
if (next && next.length >= j && function(arr1, arr2) {
var i, minl = Math.min(arr1.length, arr2.length);
for(i = 0; i < minl; i += 1)if (arr1[i] !== arr2[i]) return i;
return minl;
}(split, next) >= j - 1) break;
j--;
}
i++;
}
return globalLocale;
}(key));
}
function checkOverflow(m) {
var overflow, a = m._a;
return a && -2 === getParsingFlags(m).overflow && (overflow = a[1] < 0 || a[1] > 11 ? 1 : a[2] < 1 || a[2] > daysInMonth(a[0], a[1]) ? 2 : a[3] < 0 || a[3] > 24 || 24 === a[3] && (0 !== a[4] || 0 !== a[5] || 0 !== a[6]) ? 3 : a[4] < 0 || a[4] > 59 ? 4 : a[5] < 0 || a[5] > 59 ? 5 : a[6] < 0 || a[6] > 999 ? 6 : -1, getParsingFlags(m)._overflowDayOfYear && (overflow < 0 || overflow > 2) && (overflow = 2), getParsingFlags(m)._overflowWeeks && -1 === overflow && (overflow = 7), getParsingFlags(m)._overflowWeekday && -1 === overflow && (overflow = 8), getParsingFlags(m).overflow = overflow), m;
}
// iso 8601 regex
// 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00)
var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, tzRegex = /Z|[+-]\d\d(?::?\d\d)?/, isoDates = [
[
'YYYYYY-MM-DD',
/[+-]\d{6}-\d\d-\d\d/
],
[
'YYYY-MM-DD',
/\d{4}-\d\d-\d\d/
],
[
'GGGG-[W]WW-E',
/\d{4}-W\d\d-\d/
],
[
'GGGG-[W]WW',
/\d{4}-W\d\d/,
!1
],
[
'YYYY-DDD',
/\d{4}-\d{3}/
],
[
'YYYY-MM',
/\d{4}-\d\d/,
!1
],
[
'YYYYYYMMDD',
/[+-]\d{10}/
],
[
'YYYYMMDD',
/\d{8}/
],
[
'GGGG[W]WWE',
/\d{4}W\d{3}/
],
[
'GGGG[W]WW',
/\d{4}W\d{2}/,
!1
],
[
'YYYYDDD',
/\d{7}/
],
[
'YYYYMM',
/\d{6}/,
!1
],
[
'YYYY',
/\d{4}/,
!1
]
], // iso time formats and regexes
isoTimes = [
[
'HH:mm:ss.SSSS',
/\d\d:\d\d:\d\d\.\d+/
],
[
'HH:mm:ss,SSSS',
/\d\d:\d\d:\d\d,\d+/
],
[
'HH:mm:ss',
/\d\d:\d\d:\d\d/
],
[
'HH:mm',
/\d\d:\d\d/
],
[
'HHmmss.SSSS',
/\d\d\d\d\d\d\.\d+/
],
[
'HHmmss,SSSS',
/\d\d\d\d\d\d,\d+/
],
[
'HHmmss',
/\d\d\d\d\d\d/
],
[
'HHmm',
/\d\d\d\d/
],
[
'HH',
/\d\d/
]
], aspNetJsonRegex = /^\/?Date\((-?\d+)/i, // RFC 2822 regex: For details see https://tools.ietf.org/html/rfc2822#section-3.3
rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/, obsOffsets = {
UT: 0,
GMT: 0,
EDT: -240,
EST: -300,
CDT: -300,
CST: -360,
MDT: -360,
MST: -420,
PDT: -420,
PST: -480
};
// date from iso format
function configFromISO(config) {
var i, l, allowTime, dateFormat, timeFormat, tzFormat, string = config._i, match = extendedIsoRegex.exec(string) || basicIsoRegex.exec(string);
if (match) {
for(i = 0, getParsingFlags(config).iso = !0, l = isoDates.length; i < l; i++)if (isoDates[i][1].exec(match[1])) {
dateFormat = isoDates[i][0], allowTime = !1 !== isoDates[i][2];
break;
}
if (null == dateFormat) {
config._isValid = !1;
return;
}
if (match[3]) {
for(i = 0, l = isoTimes.length; i < l; i++)if (isoTimes[i][1].exec(match[3])) {
// match[2] should be 'T' or space
timeFormat = (match[2] || ' ') + isoTimes[i][0];
break;
}
if (null == timeFormat) {
config._isValid = !1;
return;
}
}
if (!allowTime && null != timeFormat) {
config._isValid = !1;
return;
}
if (match[4]) {
if (tzRegex.exec(match[4])) tzFormat = 'Z';
else {
config._isValid = !1;
return;
}
}
config._f = dateFormat + (timeFormat || '') + (tzFormat || ''), configFromStringAndFormat(config);
} else config._isValid = !1;
}
// date and time from ref 2822 format
function configFromRFC2822(config) {
var year, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr, result, weekdayStr, match = rfc2822.exec(config._i.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, ''));
if (match) {
if (yearStr = match[4], monthStr = match[3], dayStr = match[2], hourStr = match[5], minuteStr = match[6], secondStr = match[7], result = [
(year = parseInt(yearStr, 10)) <= 49 ? 2000 + year : year <= 999 ? 1900 + year : year,
defaultLocaleMonthsShort.indexOf(monthStr),
parseInt(dayStr, 10),
parseInt(hourStr, 10),
parseInt(minuteStr, 10)
], secondStr && result.push(parseInt(secondStr, 10)), (weekdayStr = match[1]) && defaultLocaleWeekdaysShort.indexOf(weekdayStr) !== new Date(result[0], result[1], result[2]).getDay() && (getParsingFlags(config).weekdayMismatch = !0, config._isValid = !1, 1)) return;
config._a = result, config._tzm = function(obsOffset, militaryOffset, numOffset) {
if (obsOffset) return obsOffsets[obsOffset];
if (militaryOffset) // the only allowed military tz is Z
return 0;
var hm = parseInt(numOffset, 10), m = hm % 100;
return (hm - m) / 100 * 60 + m;
}(match[8], match[9], match[10]), config._d = createUTCDate.apply(null, config._a), config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm), getParsingFlags(config).rfc2822 = !0;
} else config._isValid = !1;
}
// Pick the first defined of two or three arguments.
function defaults(a, b, c) {
return null != a ? a : null != b ? b : c;
}
// convert an array to a date.
// the array should mirror the parameters below
// note: all values past the year are optional and will default to the lowest possible value.
// [year, month, day , hour, minute, second, millisecond]
function configFromArray(config) {
var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek, nowValue, i, date, currentDate, expectedWeekday, yearToUse, input = [];
if (!config._d) {
// Default to current date.
// * if no year, month, day of month are given, default to today
// * if day of month is given, default month and year
// * if month is given, default only year
// * if year is given, don't default anything
for(nowValue = new Date(hooks.now()), currentDate = config._useUTC ? [
nowValue.getUTCFullYear(),
nowValue.getUTCMonth(),
nowValue.getUTCDate()
] : [
nowValue.getFullYear(),
nowValue.getMonth(),
nowValue.getDate()
], config._w && null == config._a[2] && null == config._a[1] && (null != (w = config._w).GG || null != w.W || null != w.E ? (dow = 1, doy = 4, // TODO: We need to take the current isoWeekYear, but that depends on
// how we interpret now (local, utc, fixed offset). So create
// a now version of current config (take local/utc/offset flags, and
// create now).
weekYear = defaults(w.GG, config._a[0], weekOfYear(createLocal(), 1, 4).year), week = defaults(w.W, 1), ((weekday = defaults(w.E, 1)) < 1 || weekday > 7) && (weekdayOverflow = !0)) : (dow = config._locale._week.dow, doy = config._locale._week.doy, curWeek = weekOfYear(createLocal(), dow, doy), weekYear = defaults(w.gg, config._a[0], curWeek.year), // Default to current week.
week = defaults(w.w, curWeek.week), null != w.d ? (// weekday -- low day numbers are considered next week
(weekday = w.d) < 0 || weekday > 6) && (weekdayOverflow = !0) : null != w.e ? (// local weekday -- counting starts from beginning of week
weekday = w.e + dow, (w.e < 0 || w.e > 6) && (weekdayOverflow = !0)) : // default to beginning of week
weekday = dow), week < 1 || week > weeksInYear(weekYear, dow, doy) ? getParsingFlags(config)._overflowWeeks = !0 : null != weekdayOverflow ? getParsingFlags(config)._overflowWeekday = !0 : (temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), config._a[0] = temp.year, config._dayOfYear = temp.dayOfYear)), null != config._dayOfYear && (yearToUse = defaults(config._a[0], currentDate[0]), (config._dayOfYear > daysInYear(yearToUse) || 0 === config._dayOfYear) && (getParsingFlags(config)._overflowDayOfYear = !0), date = createUTCDate(yearToUse, 0, config._dayOfYear), config._a[1] = date.getUTCMonth(), config._a[2] = date.getUTCDate()), i = 0; i < 3 && null == config._a[i]; ++i)config._a[i] = input[i] = currentDate[i];
// Zero out whatever was not defaulted, including time
for(; i < 7; i++)config._a[i] = input[i] = null == config._a[i] ? +(2 === i) : config._a[i];
24 === config._a[3] && 0 === config._a[4] && 0 === config._a[5] && 0 === config._a[6] && (config._nextDay = !0, config._a[3] = 0), config._d = (config._useUTC ? createUTCDate : createDate).apply(null, input), expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay(), null != config._tzm && config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm), config._nextDay && (config._a[3] = 24), config._w && void 0 !== config._w.d && config._w.d !== expectedWeekday && (getParsingFlags(config).weekdayMismatch = !0);
}
}
// date from string and format string
function configFromStringAndFormat(config) {
// TODO: Move this to another part of the creation flow to prevent circular deps
if (config._f === hooks.ISO_8601) {
configFromISO(config);
return;
}
if (config._f === hooks.RFC_2822) {
configFromRFC2822(config);
return;
}
config._a = [], getParsingFlags(config).empty = !0;
// This array is used to make a Date, either with `new Date` or `Date.UTC`
var locale, hour, meridiem, isPm, i, parsedInput, tokens1, token, skipped, era, string = '' + config._i, stringLength = string.length, totalParsedInputLength = 0;
for(i = 0, tokens1 = expandFormat(config._f, config._locale).match(formattingTokens) || []; i < tokens1.length; i++)// don't parse if it's not a known token
(token = tokens1[i], (parsedInput = (string.match(hasOwnProp(regexes, token) ? regexes[token](config._strict, config._locale) : new RegExp(regexEscape(token.replace('\\', '').replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function(matched, p1, p2, p3, p4) {
return p1 || p2 || p3 || p4;
})))) || [])[0]) && ((skipped = string.substr(0, string.indexOf(parsedInput))).length > 0 && getParsingFlags(config).unusedInput.push(skipped), string = string.slice(string.indexOf(parsedInput) + parsedInput.length), totalParsedInputLength += parsedInput.length), formatTokenFunctions[token]) ? (parsedInput ? getParsingFlags(config).empty = !1 : getParsingFlags(config).unusedTokens.push(token), null != parsedInput && hasOwnProp(tokens, token) && tokens[token](parsedInput, config._a, config, token)) : config._strict && !parsedInput && getParsingFlags(config).unusedTokens.push(token);
// add remaining unparsed input length to the string
getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength, string.length > 0 && getParsingFlags(config).unusedInput.push(string), config._a[3] <= 12 && !0 === getParsingFlags(config).bigHour && config._a[3] > 0 && (getParsingFlags(config).bigHour = void 0), getParsingFlags(config).parsedDateParts = config._a.slice(0), getParsingFlags(config).meridiem = config._meridiem, // handle meridiem
config._a[3] = (locale = config._locale, hour = config._a[3], null == (meridiem = config._meridiem) ? hour : null != locale.meridiemHour ? locale.meridiemHour(hour, meridiem) : (null != locale.isPM && (// Fallback
(isPm = locale.isPM(meridiem)) && hour < 12 && (hour += 12), isPm || 12 !== hour || (hour = 0)), hour)), null !== // handle era
(era = getParsingFlags(config).era) && (config._a[0] = config._locale.erasConvertYear(era, config._a[0])), configFromArray(config), checkOverflow(config);
}
function prepareConfig(config) {
var input, input1 = config._i, format = config._f;
return (config._locale = config._locale || getLocale(config._l), null === input1 || void 0 === format && '' === input1) ? createInvalid({
nullInput: !0
}) : ('string' == typeof input1 && (config._i = input1 = config._locale.preparse(input1)), isMoment(input1)) ? new Moment(checkOverflow(input1)) : (isDate(input1) ? config._d = input1 : isArray(format) ? // date from string and array of format strings
function(config) {
var tempConfig, bestMoment, scoreToBeat, i, currentScore, validFormatFound, bestFormatIsValid = !1;
if (0 === config._f.length) {
getParsingFlags(config).invalidFormat = !0, config._d = new Date(NaN);
return;
}
for(i = 0; i < config._f.length; i++)currentScore = 0, validFormatFound = !1, tempConfig = copyConfig({}, config), null != config._useUTC && (tempConfig._useUTC = config._useUTC), tempConfig._f = config._f[i], configFromStringAndFormat(tempConfig), isValid(tempConfig) && (validFormatFound = !0), // if there is any input that was not parsed add a penalty for that format
currentScore += getParsingFlags(tempConfig).charsLeftOver, //or tokens
currentScore += 10 * getParsingFlags(tempConfig).unusedTokens.length, getParsingFlags(tempConfig).score = currentScore, bestFormatIsValid ? currentScore < scoreToBeat && (scoreToBeat = currentScore, bestMoment = tempConfig) : (null == scoreToBeat || currentScore < scoreToBeat || validFormatFound) && (scoreToBeat = currentScore, bestMoment = tempConfig, validFormatFound && (bestFormatIsValid = !0));
extend(config, bestMoment || tempConfig);
}(config) : format ? configFromStringAndFormat(config) : isUndefined(input = config._i) ? config._d = new Date(hooks.now()) : isDate(input) ? config._d = new Date(input.valueOf()) : 'string' == typeof input ? // date from 1) ASP.NET, 2) ISO, 3) RFC 2822 formats, or 4) optional fallback if parsing isn't strict
function(config) {
var matched = aspNetJsonRegex.exec(config._i);
if (null !== matched) {
config._d = new Date(+matched[1]);
return;
}
configFromISO(config), !1 === config._isValid && (delete config._isValid, configFromRFC2822(config), !1 === config._isValid && (delete config._isValid, config._strict ? config._isValid = !1 : // Final attempt, use Input Fallback
hooks.createFromInputFallback(config)));
}(config) : isArray(input) ? (config._a = map(input.slice(0), function(obj) {
return parseInt(obj, 10);
}), configFromArray(config)) : isObject(input) ? function(config) {
if (!config._d) {
var i = normalizeObjectUnits(config._i), dayOrDate = void 0 === i.day ? i.date : i.day;
config._a = map([
i.year,
i.month,
dayOrDate,
i.hour,
i.minute,
i.second,
i.millisecond
], function(obj) {
return obj && parseInt(obj, 10);
}), configFromArray(config);
}
}(config) : isNumber(input) ? // from milliseconds
config._d = new Date(input) : hooks.createFromInputFallback(config), isValid(config) || (config._d = null), config);
}
function createLocalOrUTC(input, format, locale, strict, isUTC) {
var res, c = {};
return (!0 === format || !1 === format) && (strict = format, format = void 0), (!0 === locale || !1 === locale) && (strict = locale, locale = void 0), (isObject(input) && isObjectEmpty(input) || isArray(input) && 0 === input.length) && (input = void 0), // object construction must be done this way.
// https://github.com/moment/moment/issues/1423
c._isAMomentObject = !0, c._useUTC = c._isUTC = isUTC, c._l = locale, c._i = input, c._f = format, c._strict = strict, (res = new Moment(checkOverflow(prepareConfig(c))))._nextDay && (// Adding is smart enough around DST
res.add(1, 'd'), res._nextDay = void 0), res;
}
function createLocal(input, format, locale, strict) {
return createLocalOrUTC(input, format, locale, strict, !1);
}
hooks.createFromInputFallback = deprecate("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.", function(config) {
config._d = new Date(config._i + (config._useUTC ? ' UTC' : ''));
}), // constant that refers to the ISO standard
hooks.ISO_8601 = function() {}, // constant that refers to the RFC 2822 form
hooks.RFC_2822 = function() {};
var prototypeMin = deprecate('moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/', function() {
var other = createLocal.apply(null, arguments);
return this.isValid() && other.isValid() ? other < this ? this : other : createInvalid();
}), prototypeMax = deprecate('moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/', function() {
var other = createLocal.apply(null, arguments);
return this.isValid() && other.isValid() ? other > this ? this : other : createInvalid();
});
// Pick a moment m from moments so that m[fn](other) is true for all
// other. This relies on the function fn to be transitive.
//
// moments should either be an array of moment objects or an array, whose
// first element is an array of moment objects.
function pickBy(fn, moments) {
var res, i;
if (1 === moments.length && isArray(moments[0]) && (moments = moments[0]), !moments.length) return createLocal();
for(i = 1, res = moments[0]; i < moments.length; ++i)(!moments[i].isValid() || moments[i][fn](res)) && (res = moments[i]);
return res;
}
var ordering = [
'year',
'quarter',
'month',
'week',
'day',
'hour',
'minute',
'second',
'millisecond'
];
function Duration(duration) {
var normalizedInput = normalizeObjectUnits(duration), years = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months = normalizedInput.month || 0, weeks = normalizedInput.week || normalizedInput.isoWeek || 0, days = normalizedInput.day || 0, hours = normalizedInput.hour || 0, minutes = normalizedInput.minute || 0, seconds = normalizedInput.second || 0, milliseconds = normalizedInput.millisecond || 0;
this._isValid = function(m) {
var key, i, unitHasDecimal = !1;
for(key in m)if (hasOwnProp(m, key) && !(-1 !== indexOf.call(ordering, key) && (null == m[key] || !isNaN(m[key])))) return !1;
for(i = 0; i < ordering.length; ++i)if (m[ordering[i]]) {
if (unitHasDecimal) return !1; // only allow non-integers for smallest unit
parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]]) && (unitHasDecimal = !0);
}
return !0;
}(normalizedInput), // representation for dateAddRemove
this._milliseconds = +milliseconds + 1e3 * seconds + // 1000
6e4 * minutes + // 1000 * 60
3600000 * hours, // Because of dateAddRemove treats 24 hours as different from a
// day when working around DST, we need to store them separately
this._days = +days + 7 * weeks, // It is impossible to translate months into days without knowing
// which months you are are talking about, so we have to store
// it separately.
this._months = +months + 3 * quarters + 12 * years, this._data = {}, this._locale = getLocale(), this._bubble();
}
function isDuration(obj) {
return obj instanceof Duration;
}
function absRound(number) {
return number < 0 ? -1 * Math.round(-1 * number) : Math.round(number);
}
// FORMATTING
function offset(token, separator) {
addFormatToken(token, 0, 0, function() {
var offset = this.utcOffset(), sign = '+';
return offset < 0 && (offset = -offset, sign = '-'), sign + zeroFill(~~(offset / 60), 2) + separator + zeroFill(~~offset % 60, 2);
});
}
offset('Z', ':'), offset('ZZ', ''), // PARSING
addRegexToken('Z', matchShortOffset), addRegexToken('ZZ', matchShortOffset), addParseToken([
'Z',
'ZZ'
], function(input, array, config) {
config._useUTC = !0, config._tzm = offsetFromString(matchShortOffset, input);
});
// HELPERS
// timezone chunker
// '+10:00' > ['10', '00']
// '-1530' > ['-15', '30']
var chunkOffset = /([\+\-]|\d\d)/gi;
function offsetFromString(matcher, string) {
var parts, minutes, matches = (string || '').match(matcher);
return null === matches ? null : 0 === (minutes = +(60 * (parts = ((matches[matches.length - 1] || []) + '').match(chunkOffset) || [
'-',
0,
0
])[1]) + toInt(parts[2])) ? 0 : '+' === parts[0] ? minutes : -minutes;
}
// Return a moment from input, that is local/utc/zone equivalent to model.
function cloneWithOffset(input, model) {
var res, diff;
return model._isUTC ? (res = model.clone(), diff = (isMoment(input) || isDate(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf(), // Use low-level api, because this fn is low-level api.
res._d.setTime(res._d.valueOf() + diff), hooks.updateOffset(res, !1), res) : createLocal(input).local();
}
function getDateOffset(m) {
// On Firefox.24 Date#getTimezoneOffset returns a floating point.
// https://github.com/moment/moment/pull/1871
return -Math.round(m._d.getTimezoneOffset());
}
function isUtc() {
return !!this.isValid() && this._isUTC && 0 === this._offset;
}
// HOOKS
// This function will be called whenever a moment is mutated.
// It is intended to keep the offset in sync with the timezone.
hooks.updateOffset = function() {};
// ASP.NET json date format regex
var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/, // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html
// somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere
// and further modified to allow for strings containing both week and day
isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
function createDuration(input, key) {
var base, other, res, sign, ret, diffRes, duration = input, // matching against regexp is expensive, do it on demand
match = null;
return isDuration(input) ? duration = {
ms: input._milliseconds,
d: input._days,
M: input._months
} : isNumber(input) || !isNaN(+input) ? (duration = {}, key ? duration[key] = +input : duration.milliseconds = +input) : (match = aspNetRegex.exec(input)) ? (sign = '-' === match[1] ? -1 : 1, duration = {
y: 0,
d: toInt(match[2]) * sign,
h: toInt(match[3]) * sign,
m: toInt(match[4]) * sign,
s: toInt(match[5]) * sign,
ms: toInt(absRound(1000 * match[6])) * sign
}) : (match = isoRegex.exec(input)) ? (sign = '-' === match[1] ? -1 : 1, duration = {
y: parseIso(match[2], sign),
M: parseIso(match[3], sign),
w: parseIso(match[4], sign),
d: parseIso(match[5], sign),
h: parseIso(match[6], sign),
m: parseIso(match[7], sign),
s: parseIso(match[8], sign)
}) : null == duration ? // checks for null or undefined
duration = {} : 'object' == typeof duration && ('from' in duration || 'to' in duration) && (base = createLocal(duration.from), other = createLocal(duration.to), diffRes = base.isValid() && other.isValid() ? (other = cloneWithOffset(other, base), base.isBefore(other) ? res = positiveMomentsDifference(base, other) : ((res = positiveMomentsDifference(other, base)).milliseconds = -res.milliseconds, res.months = -res.months), res) : {
milliseconds: 0,
months: 0
}, (duration = {}).ms = diffRes.milliseconds, duration.M = diffRes.months), ret = new Duration(duration), isDuration(input) && hasOwnProp(input, '_locale') && (ret._locale = input._locale), isDuration(input) && hasOwnProp(input, '_isValid') && (ret._isValid = input._isValid), ret;
}
function parseIso(inp, sign) {
// We'd normally use ~~inp for this, but unfortunately it also
// converts floats to ints.
// inp may be undefined, so careful calling replace on it.
var res = inp && parseFloat(inp.replace(',', '.'));
// apply sign while we're at it
return (isNaN(res) ? 0 : res) * sign;
}
function positiveMomentsDifference(base, other) {
var res = {};
return res.months = other.month() - base.month() + (other.year() - base.year()) * 12, base.clone().add(res.months, 'M').isAfter(other) && --res.months, res.milliseconds = +other - +base.clone().add(res.months, 'M'), res;
}
// TODO: remove 'name' arg after deprecation is removed
function createAdder(direction, name) {
return function(val, period) {
var tmp;
return null === period || isNaN(+period) || (deprecateSimple(name, 'moment().' + name + '(period, number) is deprecated. Please use moment().' + name + "(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."), tmp = val, val = period, period = tmp), addSubtract(this, createDuration(val, period), direction), this;
};
}
function addSubtract(mom, duration, isAdding, updateOffset) {
var milliseconds = duration._milliseconds, days = absRound(duration._days), months = absRound(duration._months);
mom.isValid() && (updateOffset = null == updateOffset || updateOffset, months && setMonth(mom, get(mom, 'Month') + months * isAdding), days && set$1(mom, 'Date', get(mom, 'Date') + days * isAdding), milliseconds && mom._d.setTime(mom._d.valueOf() + milliseconds * isAdding), updateOffset && hooks.updateOffset(mom, days || months));
}
createDuration.fn = Duration.prototype, createDuration.invalid = function() {
return createDuration(NaN);
};
var add = createAdder(1, 'add'), subtract = createAdder(-1, 'subtract');
function isString(input) {
return 'string' == typeof input || input instanceof String;
}
function monthDiff(a, b) {
if (a.date() < b.date()) // end-of-month calculations work correct when the start month has more
// days than the end month.
return -monthDiff(b, a);
// difference in months
var adjust, wholeMonthDiff = (b.year() - a.year()) * 12 + (b.month() - a.month()), // b is in (anchor - 1 month, anchor + 1 month)
anchor = a.clone().add(wholeMonthDiff, 'months');
//check for negative zero, return zero if negative zero
return(// linear across the month
adjust = b - anchor < 0 ? (b - anchor) / (anchor - a.clone().add(wholeMonthDiff - 1, 'months')) : (b - anchor) / (a.clone().add(wholeMonthDiff + 1, 'months') - anchor), -(wholeMonthDiff + adjust) || 0);
}
// If passed a locale key, it will set the locale for this
// instance. Otherwise, it will return the locale configuration
// variables for this instance.
function locale(key) {
var newLocaleData;
return void 0 === key ? this._locale._abbr : (null != (newLocaleData = getLocale(key)) && (this._locale = newLocaleData), this);
}
hooks.defaultFormat = 'YYYY-MM-DDTHH:mm:ssZ', hooks.defaultFormatUtc = 'YYYY-MM-DDTHH:mm:ss[Z]';
var lang = deprecate('moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.', function(key) {
return void 0 === key ? this.localeData() : this.locale(key);
});
function localeData() {
return this._locale;
}
function localStartOfDate(y, m, d) {
return(// the date constructor remaps years 0-99 to 1900-1999
y < 100 && y >= 0 ? new Date(y + 400, m, d) - 12622780800000 : new Date(y, m, d).valueOf());
}
function utcStartOfDate(y, m, d) {
return(// Date.UTC remaps years 0-99 to 1900-1999
y < 100 && y >= 0 ? Date.UTC(y + 400, m, d) - 12622780800000 : Date.UTC(y, m, d));
}
function matchEraAbbr(isStrict, locale) {
return locale.erasAbbrRegex(isStrict);
}
function computeErasParse() {
var i, l, abbrPieces = [], namePieces = [], narrowPieces = [], mixedPieces = [], eras = this.eras();
for(i = 0, l = eras.length; i < l; ++i)namePieces.push(regexEscape(eras[i].name)), abbrPieces.push(regexEscape(eras[i].abbr)), narrowPieces.push(regexEscape(eras[i].narrow)), mixedPieces.push(regexEscape(eras[i].name)), mixedPieces.push(regexEscape(eras[i].abbr)), mixedPieces.push(regexEscape(eras[i].narrow));
this._erasRegex = RegExp('^(' + mixedPieces.join('|') + ')', 'i'), this._erasNameRegex = RegExp('^(' + namePieces.join('|') + ')', 'i'), this._erasAbbrRegex = RegExp('^(' + abbrPieces.join('|') + ')', 'i'), this._erasNarrowRegex = RegExp('^(' + narrowPieces.join('|') + ')', 'i');
}
function addWeekYearFormatToken(token, getter) {
addFormatToken(0, [
token,
token.length
], 0, getter);
}
function getSetWeekYearHelper(input, week, weekday, dow, doy) {
var weeksTarget;
return null == input ? weekOfYear(this, dow, doy).year : (week > (weeksTarget = weeksInYear(input, dow, doy)) && (week = weeksTarget), setWeekAll.call(this, input, week, weekday, dow, doy));
}
function setWeekAll(weekYear, week, weekday, dow, doy) {
var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear);
return this.year(date.getUTCFullYear()), this.month(date.getUTCMonth()), this.date(date.getUTCDate()), this;
}
addFormatToken('N', 0, 0, 'eraAbbr'), addFormatToken('NN', 0, 0, 'eraAbbr'), addFormatToken('NNN', 0, 0, 'eraAbbr'), addFormatToken('NNNN', 0, 0, 'eraName'), addFormatToken('NNNNN', 0, 0, 'eraNarrow'), addFormatToken('y', [
'y',
1
], 'yo', 'eraYear'), addFormatToken('y', [
'yy',
2
], 0, 'eraYear'), addFormatToken('y', [
'yyy',
3
], 0, 'eraYear'), addFormatToken('y', [
'yyyy',
4
], 0, 'eraYear'), addRegexToken('N', matchEraAbbr), addRegexToken('NN', matchEraAbbr), addRegexToken('NNN', matchEraAbbr), addRegexToken('NNNN', function(isStrict, locale) {
return locale.erasNameRegex(isStrict);
}), addRegexToken('NNNNN', function(isStrict, locale) {
return locale.erasNarrowRegex(isStrict);
}), addParseToken([
'N',
'NN',
'NNN',
'NNNN',
'NNNNN'
], function(input, array, config, token) {
var era = config._locale.erasParse(input, token, config._strict);
era ? getParsingFlags(config).era = era : getParsingFlags(config).invalidEra = input;
}), addRegexToken('y', matchUnsigned), addRegexToken('yy', matchUnsigned), addRegexToken('yyy', matchUnsigned), addRegexToken('yyyy', matchUnsigned), addRegexToken('yo', function(isStrict, locale) {
return locale._eraYearOrdinalRegex || matchUnsigned;
}), addParseToken([
'y',
'yy',
'yyy',
'yyyy'
], 0), addParseToken([
'yo'
], function(input, array, config, token) {
var match;
config._locale._eraYearOrdinalRegex && (match = input.match(config._locale._eraYearOrdinalRegex)), config._locale.eraYearOrdinalParse ? array[0] = config._locale.eraYearOrdinalParse(input, match) : array[0] = parseInt(input, 10);
}), // FORMATTING
addFormatToken(0, [
'gg',
2
], 0, function() {
return this.weekYear() % 100;
}), addFormatToken(0, [
'GG',
2
], 0, function() {
return this.isoWeekYear() % 100;
}), addWeekYearFormatToken('gggg', 'weekYear'), addWeekYearFormatToken('ggggg', 'weekYear'), addWeekYearFormatToken('GGGG', 'isoWeekYear'), addWeekYearFormatToken('GGGGG', 'isoWeekYear'), // ALIASES
addUnitAlias('weekYear', 'gg'), addUnitAlias('isoWeekYear', 'GG'), priorities.weekYear = 1, priorities.isoWeekYear = 1, // PARSING
addRegexToken('G', matchSigned), addRegexToken('g', matchSigned), addRegexToken('GG', match1to2, match2), addRegexToken('gg', match1to2, match2), addRegexToken('GGGG', match1to4, match4), addRegexToken('gggg', match1to4, match4), addRegexToken('GGGGG', match1to6, match6), addRegexToken('ggggg', match1to6, match6), addWeekParseToken([
'gggg',
'ggggg',
'GGGG',
'GGGGG'
], function(input, week, config, token) {
week[token.substr(0, 2)] = toInt(input);
}), addWeekParseToken([
'gg',
'GG'
], function(input, week, config, token) {
week[token] = hooks.parseTwoDigitYear(input);
}), // FORMATTING
addFormatToken('Q', 0, 'Qo', 'quarter'), // ALIASES
addUnitAlias('quarter', 'Q'), priorities.quarter = 7, // PARSING
addRegexToken('Q', match1), addParseToken('Q', function(input, array) {
array[1] = (toInt(input) - 1) * 3;
}), // FORMATTING
addFormatToken('D', [
'DD',
2
], 'Do', 'date'), // ALIASES
addUnitAlias('date', 'D'), priorities.date = 9, // PARSING
addRegexToken('D', match1to2), addRegexToken('DD', match1to2, match2), addRegexToken('Do', function(isStrict, locale) {
// TODO: Remove "ordinalParse" fallback in next major release.
return isStrict ? locale._dayOfMonthOrdinalParse || locale._ordinalParse : locale._dayOfMonthOrdinalParseLenient;
}), addParseToken([
'D',
'DD'
], 2), addParseToken('Do', function(input, array) {
array[2] = toInt(input.match(match1to2)[0]);
});
// MOMENTS
var getSetDayOfMonth = makeGetSet('Date', !0);
// FORMATTING
addFormatToken('DDD', [
'DDDD',
3
], 'DDDo', 'dayOfYear'), // ALIASES
addUnitAlias('dayOfYear', 'DDD'), priorities.dayOfYear = 4, // PARSING
addRegexToken('DDD', match1to3), addRegexToken('DDDD', match3), addParseToken([
'DDD',
'DDDD'
], function(input, array, config) {
config._dayOfYear = toInt(input);
}), // FORMATTING
addFormatToken('m', [
'mm',
2
], 0, 'minute'), // ALIASES
addUnitAlias('minute', 'm'), priorities.minute = 14, // PARSING
addRegexToken('m', match1to2), addRegexToken('mm', match1to2, match2), addParseToken([
'm',
'mm'
], 4);
// MOMENTS
var getSetMinute = makeGetSet('Minutes', !1);
// FORMATTING
addFormatToken('s', [
'ss',
2
], 0, 'second'), // ALIASES
addUnitAlias('second', 's'), priorities.second = 15, // PARSING
addRegexToken('s', match1to2), addRegexToken('ss', match1to2, match2), addParseToken([
's',
'ss'
], 5);
// MOMENTS
var getSetSecond = makeGetSet('Seconds', !1);
for(// FORMATTING
addFormatToken('S', 0, 0, function() {
return ~~(this.millisecond() / 100);
}), addFormatToken(0, [
'SS',
2
], 0, function() {
return ~~(this.millisecond() / 10);
}), addFormatToken(0, [
'SSS',
3
], 0, 'millisecond'), addFormatToken(0, [
'SSSS',
4
], 0, function() {
return 10 * this.millisecond();
}), addFormatToken(0, [
'SSSSS',
5
], 0, function() {
return 100 * this.millisecond();
}), addFormatToken(0, [
'SSSSSS',
6
], 0, function() {
return 1000 * this.millisecond();
}), addFormatToken(0, [
'SSSSSSS',
7
], 0, function() {
return 10000 * this.millisecond();
}), addFormatToken(0, [
'SSSSSSSS',
8
], 0, function() {
return 100000 * this.millisecond();
}), addFormatToken(0, [
'SSSSSSSSS',
9
], 0, function() {
return 1000000 * this.millisecond();
}), // ALIASES
addUnitAlias('millisecond', 'ms'), priorities.millisecond = 16, // PARSING
addRegexToken('S', match1to3, match1), addRegexToken('SS', match1to3, match2), addRegexToken('SSS', match1to3, match3), token = 'SSSS'; token.length <= 9; token += 'S')addRegexToken(token, matchUnsigned);
function parseMs(input, array) {
array[6] = toInt(('0.' + input) * 1000);
}
for(token = 'S'; token.length <= 9; token += 'S')addParseToken(token, parseMs);
getSetMillisecond = makeGetSet('Milliseconds', !1), // FORMATTING
addFormatToken('z', 0, 0, 'zoneAbbr'), addFormatToken('zz', 0, 0, 'zoneName');
var proto = Moment.prototype;
function preParsePostFormat(string) {
return string;
}
proto.add = add, proto.calendar = function(time, formats) {
// Support for single parameter, formats only overload to the calendar function
if (1 == arguments.length) {
if (arguments[0]) {
var input, arrayTest, dataTypeTest;
(input = arguments[0], isMoment(input) || isDate(input) || isString(input) || isNumber(input) || (arrayTest = isArray(input), dataTypeTest = !1, arrayTest && (dataTypeTest = 0 === input.filter(function(item) {
return !isNumber(item) && isString(input);
}).length), arrayTest && dataTypeTest) || function(input) {
var i, property, objectTest = isObject(input) && !isObjectEmpty(input), propertyTest = !1, properties = [
'years',
'year',
'y',
'months',
'month',
'M',
'days',
'day',
'd',
'dates',
'date',
'D',
'hours',
'hour',
'h',
'minutes',
'minute',
'm',
'seconds',
'second',
's',
'milliseconds',
'millisecond',
'ms'
];
for(i = 0; i < properties.length; i += 1)property = properties[i], propertyTest = propertyTest || hasOwnProp(input, property);
return objectTest && propertyTest;
}(input) || null == input) ? (time = arguments[0], formats = void 0) : function(input) {
var i, property, objectTest = isObject(input) && !isObjectEmpty(input), propertyTest = !1, properties = [
'sameDay',
'nextDay',
'lastDay',
'nextWeek',
'lastWeek',
'sameElse'
];
for(i = 0; i < properties.length; i += 1)property = properties[i], propertyTest = propertyTest || hasOwnProp(input, property);
return objectTest && propertyTest;
}(arguments[0]) && (formats = arguments[0], time = void 0);
} else time = void 0, formats = void 0;
}
// We want to compare the start of today, vs this.
// Getting start-of-today depends on whether we're local/utc/offset or not.
var now = time || createLocal(), sod = cloneWithOffset(now, this).startOf('day'), format = hooks.calendarFormat(this, sod) || 'sameElse', output = formats && (isFunction(formats[format]) ? formats[format].call(this, now) : formats[format]);
return this.format(output || this.localeData().calendar(format, this, createLocal(now)));
}, proto.clone = function() {
return new Moment(this);
}, proto.diff = function(input, units, asFloat) {
var that, zoneDelta, output;
if (!this.isValid() || !(that = cloneWithOffset(input, this)).isValid()) return NaN;
switch(zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4, units = normalizeUnits(units)){
case 'year':
output = monthDiff(this, that) / 12;
break;
case 'month':
output = monthDiff(this, that);
break;
case 'quarter':
output = monthDiff(this, that) / 3;
break;
case 'second':
output = (this - that) / 1e3;
break; // 1000
case 'minute':
output = (this - that) / 6e4;
break; // 1000 * 60
case 'hour':
output = (this - that) / 36e5;
break; // 1000 * 60 * 60
case 'day':
output = (this - that - zoneDelta) / 864e5;
break; // 1000 * 60 * 60 * 24, negate dst
case 'week':
output = (this - that - zoneDelta) / 6048e5;
break; // 1000 * 60 * 60 * 24 * 7, negate dst
default:
output = this - that;
}
return asFloat ? output : absFloor(output);
}, proto.endOf = function(units) {
var time, startOfDate;
if (void 0 === (units = normalizeUnits(units)) || 'millisecond' === units || !this.isValid()) return this;
switch(startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate, units){
case 'year':
time = startOfDate(this.year() + 1, 0, 1) - 1;
break;
case 'quarter':
time = startOfDate(this.year(), this.month() - this.month() % 3 + 3, 1) - 1;
break;
case 'month':
time = startOfDate(this.year(), this.month() + 1, 1) - 1;
break;
case 'week':
time = startOfDate(this.year(), this.month(), this.date() - this.weekday() + 7) - 1;
break;
case 'isoWeek':
time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1) + 7) - 1;
break;
case 'day':
case 'date':
time = startOfDate(this.year(), this.month(), this.date() + 1) - 1;
break;
case 'hour':
time = this._d.valueOf(), time += 3600000 - ((time + (this._isUTC ? 0 : 60000 * this.utcOffset())) % 3600000 + 3600000) % 3600000 - 1;
break;
case 'minute':
time = this._d.valueOf(), time += 60000 - (time % 60000 + 60000) % 60000 - 1;
break;
case 'second':
time = this._d.valueOf(), time += 1000 - (time % 1000 + 1000) % 1000 - 1;
}
return this._d.setTime(time), hooks.updateOffset(this, !0), this;
}, proto.format = function(inputString) {
inputString || (inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat);
var output = formatMoment(this, inputString);
return this.localeData().postformat(output);
}, proto.from = function(time, withoutSuffix) {
return this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid()) ? createDuration({
to: this,
from: time
}).locale(this.locale()).humanize(!withoutSuffix) : this.localeData().invalidDate();
}, proto.fromNow = function(withoutSuffix) {
return this.from(createLocal(), withoutSuffix);
}, proto.to = function(time, withoutSuffix) {
return this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid()) ? createDuration({
from: this,
to: time
}).locale(this.locale()).humanize(!withoutSuffix) : this.localeData().invalidDate();
}, proto.toNow = function(withoutSuffix) {
return this.to(createLocal(), withoutSuffix);
}, proto.get = // MOMENTS
function(units) {
return isFunction(this[units = normalizeUnits(units)]) ? this[units]() : this;
}, proto.invalidAt = function() {
return getParsingFlags(this).overflow;
}, proto.isAfter = function(input, units) {
var localInput = isMoment(input) ? input : createLocal(input);
return !!(this.isValid() && localInput.isValid()) && ('millisecond' === (units = normalizeUnits(units) || 'millisecond') ? this.valueOf() > localInput.valueOf() : localInput.valueOf() < this.clone().startOf(units).valueOf());
}, proto.isBefore = function(input, units) {
var localInput = isMoment(input) ? input : createLocal(input);
return !!(this.isValid() && localInput.isValid()) && ('millisecond' === (units = normalizeUnits(units) || 'millisecond') ? this.valueOf() < localInput.valueOf() : this.clone().endOf(units).valueOf() < localInput.valueOf());
}, proto.isBetween = function(from, to, units, inclusivity) {
var localFrom = isMoment(from) ? from : createLocal(from), localTo = isMoment(to) ? to : createLocal(to);
return !!(this.isValid() && localFrom.isValid() && localTo.isValid()) && ('(' === (inclusivity = inclusivity || '()')[0] ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) && (')' === inclusivity[1] ? this.isBefore(localTo, units) : !this.isAfter(localTo, units));
}, proto.isSame = function(input, units) {
var inputMs, localInput = isMoment(input) ? input : createLocal(input);
return !!(this.isValid() && localInput.isValid()) && ('millisecond' === (units = normalizeUnits(units) || 'millisecond') ? this.valueOf() === localInput.valueOf() : (inputMs = localInput.valueOf(), this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf()));
}, proto.isSameOrAfter = function(input, units) {
return this.isSame(input, units) || this.isAfter(input, units);
}, proto.isSameOrBefore = function(input, units) {
return this.isSame(input, units) || this.isBefore(input, units);
}, proto.isValid = function() {
return isValid(this);
}, proto.lang = lang, proto.locale = locale, proto.localeData = localeData, proto.max = prototypeMax, proto.min = prototypeMin, proto.parsingFlags = function() {
return extend({}, getParsingFlags(this));
}, proto.set = function(units, value) {
if ('object' == typeof units) {
var i, prioritized = function(unitsObj) {
var u, units = [];
for(u in unitsObj)hasOwnProp(unitsObj, u) && units.push({
unit: u,
priority: priorities[u]
});
return units.sort(function(a, b) {
return a.priority - b.priority;
}), units;
}(units = normalizeObjectUnits(units));
for(i = 0; i < prioritized.length; i++)this[prioritized[i].unit](units[prioritized[i].unit]);
} else if (isFunction(this[units = normalizeUnits(units)])) return this[units](value);
return this;
}, proto.startOf = function(units) {
var time, startOfDate;
if (void 0 === (units = normalizeUnits(units)) || 'millisecond' === units || !this.isValid()) return this;
switch(startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate, units){
case 'year':
time = startOfDate(this.year(), 0, 1);
break;
case 'quarter':
time = startOfDate(this.year(), this.month() - this.month() % 3, 1);
break;
case 'month':
time = startOfDate(this.year(), this.month(), 1);
break;
case 'week':
time = startOfDate(this.year(), this.month(), this.date() - this.weekday());
break;
case 'isoWeek':
time = startOfDate(this.year(), this.month(), this.date() - (this.isoWeekday() - 1));
break;
case 'day':
case 'date':
time = startOfDate(this.year(), this.month(), this.date());
break;
case 'hour':
time = this._d.valueOf(), time -= ((time + (this._isUTC ? 0 : 60000 * this.utcOffset())) % 3600000 + 3600000) % 3600000;
break;
case 'minute':
time = this._d.valueOf(), time -= (time % 60000 + 60000) % 60000;
break;
case 'second':
time = this._d.valueOf(), time -= (time % 1000 + 1000) % 1000;
}
return this._d.setTime(time), hooks.updateOffset(this, !0), this;
}, proto.subtract = subtract, proto.toArray = function() {
return [
this.year(),
this.month(),
this.date(),
this.hour(),
this.minute(),
this.second(),
this.millisecond()
];
}, proto.toObject = function() {
return {
years: this.year(),
months: this.month(),
date: this.date(),
hours: this.hours(),
minutes: this.minutes(),
seconds: this.seconds(),
milliseconds: this.milliseconds()
};
}, proto.toDate = function() {
return new Date(this.valueOf());
}, proto.toISOString = function(keepOffset) {
if (!this.isValid()) return null;
var utc = !0 !== keepOffset, m = utc ? this.clone().utc() : this;
return 0 > m.year() || m.year() > 9999 ? formatMoment(m, utc ? 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYYYY-MM-DD[T]HH:mm:ss.SSSZ') : isFunction(Date.prototype.toISOString) ? // native implementation is ~50x faster, use it when we can
utc ? this.toDate().toISOString() : new Date(this.valueOf() + 60000 * this.utcOffset()).toISOString().replace('Z', formatMoment(m, 'Z')) : formatMoment(m, utc ? 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]' : 'YYYY-MM-DD[T]HH:mm:ss.SSSZ');
}, proto.inspect = /**
* Return a human readable representation of a moment that can
* also be evaluated to get a new moment which is the same
*
* @link https://nodejs.org/dist/latest/docs/api/util.html#util_custom_inspect_function_on_objects
*/ function() {
if (!this.isValid()) return 'moment.invalid(/* ' + this._i + ' */)';
var prefix, year, suffix, func = 'moment', zone = '';
return this.isLocal() || (func = 0 === this.utcOffset() ? 'moment.utc' : 'moment.parseZone', zone = 'Z'), prefix = '[' + func + '("]', year = 0 <= this.year() && 9999 >= this.year() ? 'YYYY' : 'YYYYYY', suffix = zone + '[")]', this.format(prefix + year + '-MM-DD[T]HH:mm:ss.SSS' + suffix);
}, 'undefined' != typeof Symbol && null != Symbol.for && (proto[Symbol.for('nodejs.util.inspect.custom')] = function() {
return 'Moment<' + this.format() + '>';
}), proto.toJSON = function() {
// new Date(NaN).toJSON() === null
return this.isValid() ? this.toISOString() : null;
}, proto.toString = function() {
return this.clone().locale('en').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ');
}, proto.unix = function() {
return Math.floor(this.valueOf() / 1000);
}, proto.valueOf = function() {
return this._d.valueOf() - 60000 * (this._offset || 0);
}, proto.creationData = function() {
return {
input: this._i,
format: this._f,
locale: this._locale,
isUTC: this._isUTC,
strict: this._strict
};
}, proto.eraName = function() {
var i, l, val, eras = this.localeData().eras();
for(i = 0, l = eras.length; i < l; ++i)if (// truncate time
val = this.clone().startOf('day').valueOf(), eras[i].since <= val && val <= eras[i].until || eras[i].until <= val && val <= eras[i].since) return eras[i].name;
return '';
}, proto.eraNarrow = function() {
var i, l, val, eras = this.localeData().eras();
for(i = 0, l = eras.length; i < l; ++i)if (// truncate time
val = this.clone().startOf('day').valueOf(), eras[i].since <= val && val <= eras[i].until || eras[i].until <= val && val <= eras[i].since) return eras[i].narrow;
return '';
}, proto.eraAbbr = function() {
var i, l, val, eras = this.localeData().eras();
for(i = 0, l = eras.length; i < l; ++i)if (// truncate time
val = this.clone().startOf('day').valueOf(), eras[i].since <= val && val <= eras[i].until || eras[i].until <= val && val <= eras[i].since) return eras[i].abbr;
return '';
}, proto.eraYear = function() {
var i, l, dir, val, eras = this.localeData().eras();
for(i = 0, l = eras.length; i < l; ++i)if (dir = eras[i].since <= eras[i].until ? 1 : -1, // truncate time
val = this.clone().startOf('day').valueOf(), eras[i].since <= val && val <= eras[i].until || eras[i].until <= val && val <= eras[i].since) return (this.year() - hooks(eras[i].since).year()) * dir + eras[i].offset;
return this.year();
}, proto.year = getSetYear, proto.isLeapYear = function() {
return isLeapYear(this.year());
}, proto.weekYear = // MOMENTS
function(input) {
return getSetWeekYearHelper.call(this, input, this.week(), this.weekday(), this.localeData()._week.dow, this.localeData()._week.doy);
}, proto.isoWeekYear = function(input) {
return getSetWeekYearHelper.call(this, input, this.isoWeek(), this.isoWeekday(), 1, 4);
}, proto.quarter = proto.quarters = // MOMENTS
function(input) {
return null == input ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3);
}, proto.month = getSetMonth, proto.daysInMonth = function() {
return daysInMonth(this.year(), this.month());
}, proto.week = proto.weeks = // MOMENTS
function(input) {
var week = this.localeData().week(this);
return null == input ? week : this.add((input - week) * 7, 'd');
}, proto.isoWeek = proto.isoWeeks = function(input) {
var week = weekOfYear(this, 1, 4).week;
return null == input ? week : this.add((input - week) * 7, 'd');
}, proto.weeksInYear = function() {
var weekInfo = this.localeData()._week;
return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy);
}, proto.weeksInWeekYear = function() {
var weekInfo = this.localeData()._week;
return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy);
}, proto.isoWeeksInYear = function() {
return weeksInYear(this.year(), 1, 4);
}, proto.isoWeeksInISOWeekYear = function() {
return weeksInYear(this.isoWeekYear(), 1, 4);
}, proto.date = getSetDayOfMonth, proto.day = proto.days = // MOMENTS
function(input) {
if (!this.isValid()) return null != input ? this : NaN;
var input1, locale, day = this._isUTC ? this._d.getUTCDay() : this._d.getDay();
return null == input ? day : (input1 = input, locale = this.localeData(), input = 'string' != typeof input1 ? input1 : isNaN(input1) ? 'number' == typeof (input1 = locale.weekdaysParse(input1)) ? input1 : null : parseInt(input1, 10), this.add(input - day, 'd'));
}, proto.weekday = function(input) {
if (!this.isValid()) return null != input ? this : NaN;
var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7;
return null == input ? weekday : this.add(input - weekday, 'd');
}, proto.isoWeekday = function(input) {
if (!this.isValid()) return null != input ? this : NaN;
// behaves the same as moment#day except
// as a getter, returns 7 instead of 0 (1-7 range instead of 0-6)
// as a setter, sunday should belong to the previous week.
if (null == input) return this.day() || 7;
var locale, weekday = (locale = this.localeData(), 'string' == typeof input ? locale.weekdaysParse(input) % 7 || 7 : isNaN(input) ? null : input);
return this.day(this.day() % 7 ? weekday : weekday - 7);
}, proto.dayOfYear = // HELPERS
// MOMENTS
function(input) {
var dayOfYear = Math.round((this.clone().startOf('day') - this.clone().startOf('year')) / 864e5) + 1;
return null == input ? dayOfYear : this.add(input - dayOfYear, 'd');
}, proto.hour = proto.hours = getSetHour, proto.minute = proto.minutes = getSetMinute, proto.second = proto.seconds = getSetSecond, proto.millisecond = proto.milliseconds = getSetMillisecond, proto.utcOffset = // MOMENTS
// keepLocalTime = true means only change the timezone, without
// affecting the local hour. So 5:31:26 +0300 --[utcOffset(2, true)]-->
// 5:31:26 +0200 It is possible that 5:31:26 doesn't exist with offset
// +0200, so we adjust the time as needed, to be valid.
//
// Keeping the time actually adds/subtracts (one hour)
// from the actual represented time. That is why we call updateOffset
// a second time. In case it wants us to change the offset again
// _changeInProgress == true case, then we have to adjust, because
// there is no such time in the given timezone.
function(input, keepLocalTime, keepMinutes) {
var localAdjust, offset = this._offset || 0;
if (!this.isValid()) return null != input ? this : NaN;
if (null == input) return this._isUTC ? offset : getDateOffset(this);
if ('string' == typeof input) {
if (null === (input = offsetFromString(matchShortOffset, input))) return this;
} else 16 > Math.abs(input) && !keepMinutes && (input *= 60);
return !this._isUTC && keepLocalTime && (localAdjust = getDateOffset(this)), this._offset = input, this._isUTC = !0, null != localAdjust && this.add(localAdjust, 'm'), offset === input || (!keepLocalTime || this._changeInProgress ? addSubtract(this, createDuration(input - offset, 'm'), 1, !1) : this._changeInProgress || (this._changeInProgress = !0, hooks.updateOffset(this, !0), this._changeInProgress = null)), this;
}, proto.utc = function(keepLocalTime) {
return this.utcOffset(0, keepLocalTime);
}, proto.local = function(keepLocalTime) {
return this._isUTC && (this.utcOffset(0, keepLocalTime), this._isUTC = !1, keepLocalTime && this.subtract(getDateOffset(this), 'm')), this;
}, proto.parseZone = function() {
if (null != this._tzm) this.utcOffset(this._tzm, !1, !0);
else if ('string' == typeof this._i) {
var tZone = offsetFromString(matchOffset, this._i);
null != tZone ? this.utcOffset(tZone) : this.utcOffset(0, !0);
}
return this;
}, proto.hasAlignedHourOffset = function(input) {
return !!this.isValid() && (input = input ? createLocal(input).utcOffset() : 0, (this.utcOffset() - input) % 60 == 0);
}, proto.isDST = function() {
return this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset();
}, proto.isLocal = function() {
return !!this.isValid() && !this._isUTC;
}, proto.isUtcOffset = function() {
return !!this.isValid() && this._isUTC;
}, proto.isUtc = isUtc, proto.isUTC = isUtc, proto.zoneAbbr = // MOMENTS
function() {
return this._isUTC ? 'UTC' : '';
}, proto.zoneName = function() {
return this._isUTC ? 'Coordinated Universal Time' : '';
}, proto.dates = deprecate('dates accessor is deprecated. Use date instead.', getSetDayOfMonth), proto.months = deprecate('months accessor is deprecated. Use month instead', getSetMonth), proto.years = deprecate('years accessor is deprecated. Use year instead', getSetYear), proto.zone = deprecate('moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/', function(input, keepLocalTime) {
return null != input ? ('string' != typeof input && (input = -input), this.utcOffset(input, keepLocalTime), this) : -this.utcOffset();
}), proto.isDSTShifted = deprecate('isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information', function() {
if (!isUndefined(this._isDSTShifted)) return this._isDSTShifted;
var other, c = {};
return copyConfig(c, this), (c = prepareConfig(c))._a ? (other = c._isUTC ? createUTC(c._a) : createLocal(c._a), this._isDSTShifted = this.isValid() && // compare two arrays, return the number of differences
function(array1, array2, dontConvert) {
var i, len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0;
for(i = 0; i < len; i++)toInt(array1[i]) !== toInt(array2[i]) && diffs++;
return diffs + lengthDiff;
}(c._a, other.toArray()) > 0) : this._isDSTShifted = !1, this._isDSTShifted;
});
var proto$1 = Locale.prototype;
function get$1(format, index, field, setter) {
var locale = getLocale(), utc = createUTC().set(setter, index);
return locale[field](utc, format);
}
function listMonthsImpl(format, index, field) {
if (isNumber(format) && (index = format, format = void 0), format = format || '', null != index) return get$1(format, index, field, 'month');
var i, out = [];
for(i = 0; i < 12; i++)out[i] = get$1(format, i, field, 'month');
return out;
}
// ()
// (5)
// (fmt, 5)
// (fmt)
// (true)
// (true, 5)
// (true, fmt, 5)
// (true, fmt)
function listWeekdaysImpl(localeSorted, format, index, field) {
'boolean' == typeof localeSorted || (index = format = localeSorted, localeSorted = !1), isNumber(format) && (index = format, format = void 0), format = format || '';
var i, locale = getLocale(), shift = localeSorted ? locale._week.dow : 0, out = [];
if (null != index) return get$1(format, (index + shift) % 7, field, 'day');
for(i = 0; i < 7; i++)out[i] = get$1(format, (i + shift) % 7, field, 'day');
return out;
}
proto$1.calendar = function(key, mom, now) {
var output = this._calendar[key] || this._calendar.sameElse;
return isFunction(output) ? output.call(mom, now) : output;
}, proto$1.longDateFormat = function(key) {
var format = this._longDateFormat[key], formatUpper = this._longDateFormat[key.toUpperCase()];
return format || !formatUpper ? format : (this._longDateFormat[key] = formatUpper.match(formattingTokens).map(function(tok) {
return 'MMMM' === tok || 'MM' === tok || 'DD' === tok || 'dddd' === tok ? tok.slice(1) : tok;
}).join(''), this._longDateFormat[key]);
}, proto$1.invalidDate = function() {
return this._invalidDate;
}, proto$1.ordinal = function(number) {
return this._ordinal.replace('%d', number);
}, proto$1.preparse = preParsePostFormat, proto$1.postformat = preParsePostFormat, proto$1.relativeTime = function(number, withoutSuffix, string, isFuture) {
var output = this._relativeTime[string];
return isFunction(output) ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number);
}, proto$1.pastFuture = function(diff, output) {
var format = this._relativeTime[diff > 0 ? 'future' : 'past'];
return isFunction(format) ? format(output) : format.replace(/%s/i, output);
}, proto$1.set = function(config) {
var prop, i;
for(i in config)hasOwnProp(config, i) && (isFunction(prop = config[i]) ? this[i] = prop : this['_' + i] = prop);
this._config = config, // Lenient ordinal parsing accepts just a number in addition to
// number + (possibly) stuff coming from _dayOfMonthOrdinalParse.
// TODO: Remove "ordinalParse" fallback in next major release.
this._dayOfMonthOrdinalParseLenient = 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('string' == typeof eras[i].since && (// truncate time
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':
// truncate time
date = hooks(eras[i].until).startOf('day').valueOf(), eras[i].until = date.valueOf();
}
return eras;
}, proto$1.erasParse = function(eraName, format, strict) {
var i, l, name, abbr, narrow, eras = this.eras();
for(i = 0, eraName = eraName.toUpperCase(), l = eras.length; i < l; ++i)if (name = eras[i].name.toUpperCase(), abbr = eras[i].abbr.toUpperCase(), narrow = eras[i].narrow.toUpperCase(), strict) switch(format){
case 'N':
case 'NN':
case 'NNN':
if (abbr === eraName) return eras[i];
break;
case 'NNNN':
if (name === eraName) return eras[i];
break;
case 'NNNNN':
if (narrow === eraName) return eras[i];
}
else if ([
name,
abbr,
narrow
].indexOf(eraName) >= 0) return eras[i];
}, proto$1.erasConvertYear = function(era, year) {
var dir = era.since <= era.until ? 1 : -1;
return void 0 === year ? hooks(era.since).year() : hooks(era.since).year() + (year - era.offset) * dir;
}, proto$1.erasAbbrRegex = function(isStrict) {
return hasOwnProp(this, '_erasAbbrRegex') || computeErasParse.call(this), isStrict ? this._erasAbbrRegex : this._erasRegex;
}, proto$1.erasNameRegex = function(isStrict) {
return hasOwnProp(this, '_erasNameRegex') || computeErasParse.call(this), isStrict ? this._erasNameRegex : this._erasRegex;
}, proto$1.erasNarrowRegex = function(isStrict) {
return hasOwnProp(this, '_erasNarrowRegex') || computeErasParse.call(this), isStrict ? this._erasNarrowRegex : this._erasRegex;
}, proto$1.months = function(m, format) {
return m ? isArray(this._months) ? this._months[m.month()] : this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format) ? 'format' : 'standalone'][m.month()] : isArray(this._months) ? this._months : this._months.standalone;
}, proto$1.monthsShort = function(m, format) {
return m ? isArray(this._monthsShort) ? this._monthsShort[m.month()] : this._monthsShort[MONTHS_IN_FORMAT.test(format) ? 'format' : 'standalone'][m.month()] : isArray(this._monthsShort) ? this._monthsShort : this._monthsShort.standalone;
}, proto$1.monthsParse = function(monthName, format, strict) {
var i, mom, regex;
if (this._monthsParseExact) return handleStrictParse.call(this, monthName, format, strict);
// TODO: add sorting
// Sorting makes sure if one month (or abbr) is a prefix of another
// see sorting in computeMonthsParse
for(this._monthsParse || (this._monthsParse = [], this._longMonthsParse = [], this._shortMonthsParse = []), i = 0; i < 12; i++)// test the regex
if (// make the regex if we don't have it already
mom = createUTC([
2000,
i
]), strict && !this._longMonthsParse[i] && (this._longMonthsParse[i] = RegExp('^' + this.months(mom, '').replace('.', '') + '$', 'i'), this._shortMonthsParse[i] = RegExp('^' + this.monthsShort(mom, '').replace('.', '') + '$', 'i')), strict || this._monthsParse[i] || (regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''), this._monthsParse[i] = RegExp(regex.replace('.', ''), 'i')), strict && 'MMMM' === format && this._longMonthsParse[i].test(monthName) || strict && 'MMM' === format && this._shortMonthsParse[i].test(monthName) || !strict && this._monthsParse[i].test(monthName)) return i;
}, proto$1.monthsRegex = function(isStrict) {
return this._monthsParseExact ? (hasOwnProp(this, '_monthsRegex') || computeMonthsParse.call(this), isStrict) ? this._monthsStrictRegex : this._monthsRegex : (hasOwnProp(this, '_monthsRegex') || (this._monthsRegex = matchWord), this._monthsStrictRegex && isStrict ? this._monthsStrictRegex : this._monthsRegex);
}, proto$1.monthsShortRegex = function(isStrict) {
return this._monthsParseExact ? (hasOwnProp(this, '_monthsRegex') || computeMonthsParse.call(this), isStrict) ? this._monthsShortStrictRegex : this._monthsShortRegex : (hasOwnProp(this, '_monthsShortRegex') || (this._monthsShortRegex = matchWord), this._monthsShortStrictRegex && isStrict ? this._monthsShortStrictRegex : this._monthsShortRegex);
}, proto$1.week = // HELPERS
// LOCALES
function(mom) {
return weekOfYear(mom, this._week.dow, this._week.doy).week;
}, proto$1.firstDayOfYear = function() {
return this._week.doy;
}, proto$1.firstDayOfWeek = function() {
return this._week.dow;
}, proto$1.weekdays = function(m, format) {
var weekdays = isArray(this._weekdays) ? this._weekdays : this._weekdays[m && !0 !== m && this._weekdays.isFormat.test(format) ? 'format' : 'standalone'];
return !0 === m ? shiftWeekdays(weekdays, this._week.dow) : m ? weekdays[m.day()] : weekdays;
}, proto$1.weekdaysMin = function(m) {
return !0 === m ? shiftWeekdays(this._weekdaysMin, this._week.dow) : m ? this._weekdaysMin[m.day()] : this._weekdaysMin;
}, proto$1.weekdaysShort = function(m) {
return !0 === m ? shiftWeekdays(this._weekdaysShort, this._week.dow) : m ? this._weekdaysShort[m.day()] : this._weekdaysShort;
}, proto$1.weekdaysParse = function(weekdayName, format, strict) {
var i, mom, regex;
if (this._weekdaysParseExact) return handleStrictParse$1.call(this, weekdayName, format, strict);
for(this._weekdaysParse || (this._weekdaysParse = [], this._minWeekdaysParse = [], this._shortWeekdaysParse = [], this._fullWeekdaysParse = []), i = 0; i < 7; i++){
// test the regex
if (// make the regex if we don't have it already
mom = createUTC([
2000,
1
]).day(i), strict && !this._fullWeekdaysParse[i] && (this._fullWeekdaysParse[i] = RegExp('^' + this.weekdays(mom, '').replace('.', '\\.?') + '$', 'i'), this._shortWeekdaysParse[i] = RegExp('^' + this.weekdaysShort(mom, '').replace('.', '\\.?') + '$', 'i'), this._minWeekdaysParse[i] = RegExp('^' + this.weekdaysMin(mom, '').replace('.', '\\.?') + '$', 'i')), this._weekdaysParse[i] || (regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''), this._weekdaysParse[i] = RegExp(regex.replace('.', ''), 'i')), strict && 'dddd' === format && this._fullWeekdaysParse[i].test(weekdayName) || strict && 'ddd' === format && this._shortWeekdaysParse[i].test(weekdayName)) return i;
if (strict && 'dd' === format && this._minWeekdaysParse[i].test(weekdayName)) return i;
if (!strict && this._weekdaysParse[i].test(weekdayName)) return i;
}
}, proto$1.weekdaysRegex = function(isStrict) {
return this._weekdaysParseExact ? (hasOwnProp(this, '_weekdaysRegex') || computeWeekdaysParse.call(this), isStrict) ? this._weekdaysStrictRegex : this._weekdaysRegex : (hasOwnProp(this, '_weekdaysRegex') || (this._weekdaysRegex = matchWord), this._weekdaysStrictRegex && isStrict ? this._weekdaysStrictRegex : this._weekdaysRegex);
}, proto$1.weekdaysShortRegex = function(isStrict) {
return this._weekdaysParseExact ? (hasOwnProp(this, '_weekdaysRegex') || computeWeekdaysParse.call(this), isStrict) ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex : (hasOwnProp(this, '_weekdaysShortRegex') || (this._weekdaysShortRegex = matchWord), this._weekdaysShortStrictRegex && isStrict ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex);
}, proto$1.weekdaysMinRegex = function(isStrict) {
return this._weekdaysParseExact ? (hasOwnProp(this, '_weekdaysRegex') || computeWeekdaysParse.call(this), isStrict) ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex : (hasOwnProp(this, '_weekdaysMinRegex') || (this._weekdaysMinRegex = matchWord), this._weekdaysMinStrictRegex && isStrict ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex);
}, proto$1.isPM = // LOCALES
function(input) {
// IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays
// Using charAt should be more compatible.
return 'p' === (input + '').toLowerCase().charAt(0);
}, proto$1.meridiem = function(hours, minutes, isLower) {
return hours > 11 ? isLower ? 'pm' : 'PM' : isLower ? 'am' : 'AM';
}, getSetGlobalLocale('en', {
eras: [
{
since: '0001-01-01',
until: Infinity,
offset: 1,
name: 'Anno Domini',
narrow: 'AD',
abbr: 'AD'
},
{
since: '0000-12-31',
until: -1 / 0,
offset: 1,
name: 'Before Christ',
narrow: 'BC',
abbr: 'BC'
}
],
dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/,
ordinal: function(number) {
var b = number % 10, output = 1 === toInt(number % 100 / 10) ? 'th' : 1 === b ? 'st' : 2 === b ? 'nd' : 3 === b ? 'rd' : 'th';
return number + output;
}
}), // Side effect imports
hooks.lang = deprecate('moment.lang is deprecated. Use moment.locale instead.', getSetGlobalLocale), hooks.langData = deprecate('moment.langData is deprecated. Use moment.localeData instead.', getLocale);
var mathAbs = Math.abs;
function addSubtract$1(duration, input, value, direction) {
var other = createDuration(input, value);
return duration._milliseconds += direction * other._milliseconds, duration._days += direction * other._days, duration._months += direction * other._months, duration._bubble();
}
function absCeil(number) {
return number < 0 ? Math.floor(number) : Math.ceil(number);
}
function daysToMonths(days) {
// 400 years have 146097 days (taking into account leap year rules)
// 400 years have 12 months === 4800
return 4800 * days / 146097;
}
function monthsToDays(months) {
// the reverse of daysToMonths
return 146097 * months / 4800;
}
function makeAs(alias) {
return function() {
return this.as(alias);
};
}
var asMilliseconds = makeAs('ms'), asSeconds = makeAs('s'), asMinutes = makeAs('m'), asHours = makeAs('h'), asDays = makeAs('d'), asWeeks = makeAs('w'), asMonths = makeAs('M'), asQuarters = makeAs('Q'), asYears = makeAs('y');
function makeGetter(name) {
return function() {
return this.isValid() ? this._data[name] : NaN;
};
}
var milliseconds = makeGetter('milliseconds'), seconds = makeGetter('seconds'), minutes = makeGetter('minutes'), hours = makeGetter('hours'), days = makeGetter('days'), months = makeGetter('months'), years = makeGetter('years'), round = Math.round, thresholds = {
ss: 44,
s: 45,
m: 45,
h: 22,
d: 26,
w: null,
M: 11
};
// helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize
function substituteTimeAgo(string, number, withoutSuffix, isFuture, locale) {
return locale.relativeTime(number || 1, !!withoutSuffix, string, isFuture);
}
var abs$1 = Math.abs;
function sign(x) {
return (x > 0) - (x < 0) || +x;
}
function toISOString$1() {
// for ISO strings we do not use the normal bubbling rules:
// * milliseconds bubble up until they become hours
// * days do not bubble at all
// * months bubble up until they become years
// This is because there is no context-free conversion between hours and days
// (think of clock changes)
// and also not between days and months (28-31 days per month)
if (!this.isValid()) return this.localeData().invalidDate();
var minutes, hours, years, s, totalSign, ymSign, daysSign, hmsSign, seconds = abs$1(this._milliseconds) / 1000, days = abs$1(this._days), months = abs$1(this._months), total = this.asSeconds();
return total ? (// 3600 seconds -> 60 minutes -> 1 hour
minutes = absFloor(seconds / 60), hours = absFloor(minutes / 60), seconds %= 60, minutes %= 60, // 12 months -> 1 year
years = absFloor(months / 12), months %= 12, // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js
s = seconds ? seconds.toFixed(3).replace(/\.?0+$/, '') : '', totalSign = total < 0 ? '-' : '', ymSign = sign(this._months) !== sign(total) ? '-' : '', daysSign = sign(this._days) !== sign(total) ? '-' : '', hmsSign = sign(this._milliseconds) !== sign(total) ? '-' : '', totalSign + 'P' + (years ? ymSign + years + 'Y' : '') + (months ? ymSign + months + 'M' : '') + (days ? daysSign + days + 'D' : '') + (hours || minutes || seconds ? 'T' : '') + (hours ? hmsSign + hours + 'H' : '') + (minutes ? hmsSign + minutes + 'M' : '') + (seconds ? hmsSign + s + 'S' : '')) : 'P0D';
}
var proto$2 = Duration.prototype;
return proto$2.isValid = function() {
return this._isValid;
}, proto$2.abs = function() {
var data = this._data;
return this._milliseconds = mathAbs(this._milliseconds), this._days = mathAbs(this._days), this._months = mathAbs(this._months), data.milliseconds = mathAbs(data.milliseconds), data.seconds = mathAbs(data.seconds), data.minutes = mathAbs(data.minutes), data.hours = mathAbs(data.hours), data.months = mathAbs(data.months), data.years = mathAbs(data.years), this;
}, proto$2.add = // supports only 2.0-style add(1, 's') or add(duration)
function(input, value) {
return addSubtract$1(this, input, value, 1);
}, proto$2.subtract = // supports only 2.0-style subtract(1, 's') or subtract(duration)
function(input, value) {
return addSubtract$1(this, input, value, -1);
}, proto$2.as = function(units) {
if (!this.isValid()) return NaN;
var days, months, milliseconds = this._milliseconds;
if ('month' === (units = normalizeUnits(units)) || 'quarter' === units || 'year' === units) switch(days = this._days + milliseconds / 864e5, months = this._months + daysToMonths(days), units){
case 'month':
return months;
case 'quarter':
return months / 3;
case 'year':
return months / 12;
}
else switch(// handle milliseconds separately because of floating point math errors (issue #1867)
days = this._days + Math.round(monthsToDays(this._months)), units){
case 'week':
return days / 7 + milliseconds / 6048e5;
case 'day':
return days + milliseconds / 864e5;
case 'hour':
return 24 * days + milliseconds / 36e5;
case 'minute':
return 1440 * days + milliseconds / 6e4;
case 'second':
return 86400 * days + milliseconds / 1000;
// Math.floor prevents floating point math errors here
case 'millisecond':
return Math.floor(864e5 * days) + milliseconds;
default:
throw Error('Unknown unit ' + units);
}
}, proto$2.asMilliseconds = asMilliseconds, proto$2.asSeconds = asSeconds, proto$2.asMinutes = asMinutes, proto$2.asHours = asHours, proto$2.asDays = asDays, proto$2.asWeeks = asWeeks, proto$2.asMonths = asMonths, proto$2.asQuarters = asQuarters, proto$2.asYears = asYears, proto$2.valueOf = // TODO: Use this.as('ms')?
function() {
return this.isValid() ? this._milliseconds + 864e5 * this._days + this._months % 12 * 2592e6 + 31536e6 * toInt(this._months / 12) : NaN;
}, proto$2._bubble = function() {
var seconds, minutes, hours, years, monthsFromDays, milliseconds = this._milliseconds, days = this._days, months = this._months, data = this._data;
return milliseconds >= 0 && days >= 0 && months >= 0 || milliseconds <= 0 && days <= 0 && months <= 0 || (milliseconds += 864e5 * absCeil(monthsToDays(months) + days), days = 0, months = 0), // The following code bubbles up values, see the tests for
// examples of what that means.
data.milliseconds = milliseconds % 1000, data.seconds = (seconds = absFloor(milliseconds / 1000)) % 60, data.minutes = (minutes = absFloor(seconds / 60)) % 60, data.hours = (hours = absFloor(minutes / 60)) % 24, days += absFloor(hours / 24), months += // convert days to months
monthsFromDays = absFloor(daysToMonths(days)), days -= absCeil(monthsToDays(monthsFromDays)), // 12 months -> 1 year
years = absFloor(months / 12), months %= 12, data.days = days, data.months = months, data.years = years, this;
}, proto$2.clone = function() {
return createDuration(this);
}, proto$2.get = function(units) {
return units = normalizeUnits(units), this.isValid() ? this[units + 's']() : NaN;
}, proto$2.milliseconds = milliseconds, proto$2.seconds = seconds, proto$2.minutes = minutes, proto$2.hours = hours, proto$2.days = days, proto$2.weeks = function() {
return absFloor(this.days() / 7);
}, proto$2.months = months, proto$2.years = years, proto$2.humanize = function(argWithSuffix, argThresholds) {
if (!this.isValid()) return this.localeData().invalidDate();
var withoutSuffix, thresholds1, duration, seconds, minutes, hours, days, months, weeks, years, a, locale, output, withSuffix = !1, th = thresholds;
return 'object' == typeof argWithSuffix && (argThresholds = argWithSuffix, argWithSuffix = !1), 'boolean' == typeof argWithSuffix && (withSuffix = argWithSuffix), 'object' == typeof argThresholds && (th = Object.assign({}, thresholds, argThresholds), null != argThresholds.s && null == argThresholds.ss && (th.ss = argThresholds.s - 1)), locale = this.localeData(), withoutSuffix = !withSuffix, thresholds1 = th, duration = createDuration(this).abs(), seconds = round(duration.as('s')), minutes = round(duration.as('m')), hours = round(duration.as('h')), days = round(duration.as('d')), months = round(duration.as('M')), weeks = round(duration.as('w')), years = round(duration.as('y')), a = seconds <= thresholds1.ss && [
's',
seconds
] || seconds < thresholds1.s && [
'ss',
seconds
] || minutes <= 1 && [
'm'
] || minutes < thresholds1.m && [
'mm',
minutes
] || hours <= 1 && [
'h'
] || hours < thresholds1.h && [
'hh',
hours
] || days <= 1 && [
'd'
] || days < thresholds1.d && [
'dd',
days
], null != thresholds1.w && (a = a || weeks <= 1 && [
'w'
] || weeks < thresholds1.w && [
'ww',
weeks
]), (a = a || months <= 1 && [
'M'
] || months < thresholds1.M && [
'MM',
months
] || years <= 1 && [
'y'
] || [
'yy',
years
])[2] = withoutSuffix, a[3] = +this > 0, a[4] = locale, output = substituteTimeAgo.apply(null, a), withSuffix && (output = locale.pastFuture(+this, output)), locale.postformat(output);
}, proto$2.toISOString = toISOString$1, proto$2.toString = toISOString$1, proto$2.toJSON = toISOString$1, proto$2.locale = locale, proto$2.localeData = localeData, proto$2.toIsoString = deprecate('toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)', toISOString$1), proto$2.lang = lang, // FORMATTING
addFormatToken('X', 0, 0, 'unix'), addFormatToken('x', 0, 0, 'valueOf'), // PARSING
addRegexToken('x', matchSigned), addRegexToken('X', /[+-]?\d+(\.\d{1,3})?/), addParseToken('X', function(input, array, config) {
config._d = new Date(1000 * parseFloat(input));
}), addParseToken('x', function(input, array, config) {
config._d = new Date(toInt(input));
}), //! moment.js
hooks.version = '2.29.1', hookCallback = createLocal, hooks.fn = proto, hooks.min = // TODO: Use [].sort instead?
function() {
var args = [].slice.call(arguments, 0);
return pickBy('isBefore', args);
}, hooks.max = function() {
var args = [].slice.call(arguments, 0);
return pickBy('isAfter', args);
}, hooks.now = function() {
return Date.now ? Date.now() : +new Date();
}, hooks.utc = createUTC, hooks.unix = function(input) {
return createLocal(1000 * input);
}, hooks.months = function(format, index) {
return listMonthsImpl(format, index, 'months');
}, hooks.isDate = isDate, hooks.locale = getSetGlobalLocale, hooks.invalid = createInvalid, hooks.duration = createDuration, hooks.isMoment = isMoment, hooks.weekdays = function(localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
}, hooks.parseZone = function() {
return createLocal.apply(null, arguments).parseZone();
}, hooks.localeData = getLocale, hooks.isDuration = isDuration, hooks.monthsShort = function(format, index) {
return listMonthsImpl(format, index, 'monthsShort');
}, hooks.weekdaysMin = function(localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
}, hooks.defineLocale = defineLocale, hooks.updateLocale = function(name, config) {
if (null != config) {
var locale, tmpLocale, parentConfig = baseConfig;
null != locales[name] && null != locales[name].parentLocale ? // Update existing child locale in-place to avoid memory-leaks
locales[name].set(mergeConfigs(locales[name]._config, config)) : (null != // MERGE
(tmpLocale = loadLocale(name)) && (parentConfig = tmpLocale._config), config = mergeConfigs(parentConfig, config), null == tmpLocale && // updateLocale is called for creating a new locale
// Set abbr so it will have a name (getters return
// undefined otherwise).
(config.abbr = name), (locale = new Locale(config)).parentLocale = locales[name], locales[name] = locale), // backwards compat for now: also set the locale
getSetGlobalLocale(name);
} else // pass null for config to unupdate, useful for tests
null != locales[name] && (null != locales[name].parentLocale ? (locales[name] = locales[name].parentLocale, name === getSetGlobalLocale() && getSetGlobalLocale(name)) : null != locales[name] && delete locales[name]);
return locales[name];
}, hooks.locales = function() {
return keys(locales);
}, hooks.weekdaysShort = function(localeSorted, format, index) {
return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
}, hooks.normalizeUnits = normalizeUnits, hooks.relativeTimeRounding = // This function allows you to set the rounding function for relative time strings
function(roundingFunction) {
return void 0 === roundingFunction ? round : 'function' == typeof roundingFunction && (round = roundingFunction, !0);
}, hooks.relativeTimeThreshold = // This function allows you to set a threshold for relative time strings
function(threshold, limit) {
return void 0 !== thresholds[threshold] && (void 0 === limit ? thresholds[threshold] : (thresholds[threshold] = limit, 's' === threshold && (thresholds.ss = limit - 1), !0));
}, hooks.calendarFormat = function(myMoment, now) {
var diff = myMoment.diff(now, 'days', !0);
return diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse';
}, hooks.prototype = proto, // currently HTML5 input type only supports 24-hour formats
hooks.HTML5_FMT = {
DATETIME_LOCAL: 'YYYY-MM-DDTHH:mm',
DATETIME_LOCAL_SECONDS: 'YYYY-MM-DDTHH:mm:ss',
DATETIME_LOCAL_MS: 'YYYY-MM-DDTHH:mm:ss.SSS',
DATE: 'YYYY-MM-DD',
TIME: 'HH:mm',
TIME_SECONDS: 'HH:mm:ss',
TIME_MS: 'HH:mm:ss.SSS',
WEEK: 'GGGG-[W]WW',
MONTH: 'YYYY-MM'
}, hooks;
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/benches-full/react.js | JavaScript | /** @license React v17.0.1
* react.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/ 'use strict';
"production" !== process.env.NODE_ENV && function() {
var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs, prevLog, prevInfo, prevWarn, prevError, prevGroup, prevGroupCollapsed, prevGroupEnd, prefix, componentFrameCache, propTypesMisspellWarningShown, _assign = require('object-assign'), REACT_ELEMENT_TYPE = 0xeac7, REACT_PORTAL_TYPE = 0xeaca;
exports.Fragment = 0xeacb, exports.StrictMode = 0xeacc, exports.Profiler = 0xead2;
var REACT_PROVIDER_TYPE = 0xeacd, REACT_CONTEXT_TYPE = 0xeace, REACT_FORWARD_REF_TYPE = 0xead0;
exports.Suspense = 0xead1;
var REACT_SUSPENSE_LIST_TYPE = 0xead8, REACT_MEMO_TYPE = 0xead3, REACT_LAZY_TYPE = 0xead4, REACT_BLOCK_TYPE = 0xead9, REACT_SERVER_BLOCK_TYPE = 0xeada, REACT_FUNDAMENTAL_TYPE = 0xead5, REACT_DEBUG_TRACING_MODE_TYPE = 0xeae1, REACT_LEGACY_HIDDEN_TYPE = 0xeae3;
if ('function' == typeof Symbol && Symbol.for) {
var symbolFor = Symbol.for;
REACT_ELEMENT_TYPE = symbolFor('react.element'), REACT_PORTAL_TYPE = symbolFor('react.portal'), exports.Fragment = symbolFor('react.fragment'), exports.StrictMode = symbolFor('react.strict_mode'), exports.Profiler = symbolFor('react.profiler'), REACT_PROVIDER_TYPE = symbolFor('react.provider'), REACT_CONTEXT_TYPE = symbolFor('react.context'), REACT_FORWARD_REF_TYPE = symbolFor('react.forward_ref'), exports.Suspense = symbolFor('react.suspense'), REACT_SUSPENSE_LIST_TYPE = symbolFor('react.suspense_list'), REACT_MEMO_TYPE = symbolFor('react.memo'), REACT_LAZY_TYPE = symbolFor('react.lazy'), REACT_BLOCK_TYPE = symbolFor('react.block'), REACT_SERVER_BLOCK_TYPE = symbolFor('react.server.block'), REACT_FUNDAMENTAL_TYPE = symbolFor('react.fundamental'), symbolFor('react.scope'), symbolFor('react.opaque.id'), REACT_DEBUG_TRACING_MODE_TYPE = symbolFor('react.debug_trace_mode'), symbolFor('react.offscreen'), REACT_LEGACY_HIDDEN_TYPE = symbolFor('react.legacy_hidden');
}
var MAYBE_ITERATOR_SYMBOL = 'function' == typeof Symbol && Symbol.iterator;
function getIteratorFn(maybeIterable) {
if (null === maybeIterable || 'object' != typeof maybeIterable) return null;
var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable['@@iterator'];
return 'function' == typeof maybeIterator ? maybeIterator : null;
}
/**
* Keeps track of the current dispatcher.
*/ var ReactCurrentDispatcher = {
/**
* @internal
* @type {ReactComponent}
*/ current: null
}, ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/ current: null
}, ReactDebugCurrentFrame = {}, currentExtraStackFrame = null;
ReactDebugCurrentFrame.setExtraStackFrame = function(stack) {
currentExtraStackFrame = stack;
}, ReactDebugCurrentFrame.getCurrentStack = null, ReactDebugCurrentFrame.getStackAddendum = function() {
var stack = ''; // Add an extra top frame while an element is being validated
currentExtraStackFrame && (stack += currentExtraStackFrame);
var impl = ReactDebugCurrentFrame.getCurrentStack;
return impl && (stack += impl() || ''), stack;
};
var ReactSharedInternals = {
ReactCurrentDispatcher: ReactCurrentDispatcher,
ReactCurrentBatchConfig: {
transition: 0
},
ReactCurrentOwner: ReactCurrentOwner,
IsSomeRendererActing: {
current: !1
},
// Used by renderers to avoid bundling object-assign twice in UMD bundles:
assign: _assign
};
// by calls to these methods by a Babel plugin.
//
// In PROD (or in packages without access to React internals),
// they are left as they are instead.
function warn(format) {
for(var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++)args[_key - 1] = arguments[_key];
printWarning('warn', format, args);
}
function error(format) {
for(var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++)args[_key2 - 1] = arguments[_key2];
printWarning('error', format, args);
}
function printWarning(level, format, args) {
var stack = ReactSharedInternals.ReactDebugCurrentFrame.getStackAddendum();
'' !== stack && (format += '%s', args = args.concat([
stack
]));
var argsWithFormat = args.map(function(item) {
return '' + item;
}); // Careful: RN currently depends on this prefix
argsWithFormat.unshift('Warning: ' + format), // breaks IE9: https://github.com/facebook/react/issues/13610
// eslint-disable-next-line react-internal/no-production-logging
Function.prototype.apply.call(console[level], console, argsWithFormat);
}
ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame;
var didWarnStateUpdateForUnmountedComponent = {};
function warnNoop(publicInstance, callerName) {
var _constructor = publicInstance.constructor, componentName = _constructor && (_constructor.displayName || _constructor.name) || 'ReactClass', warningKey = componentName + "." + callerName;
didWarnStateUpdateForUnmountedComponent[warningKey] || (error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", callerName, componentName), didWarnStateUpdateForUnmountedComponent[warningKey] = !0);
}
/**
* This is the abstract API for an update queue.
*/ var ReactNoopUpdateQueue = {
/**
* Checks whether or not this composite component is mounted.
* @param {ReactClass} publicInstance The instance we want to test.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/ isMounted: function(publicInstance) {
return !1;
},
/**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {?function} callback Called after component is updated.
* @param {?string} callerName name of the calling function in the public API.
* @internal
*/ enqueueForceUpdate: function(publicInstance, callback, callerName) {
warnNoop(publicInstance, 'forceUpdate');
},
/**
* Replaces all of the state. Always use this or `setState` to mutate state.
* You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} completeState Next state.
* @param {?function} callback Called after component is updated.
* @param {?string} callerName name of the calling function in the public API.
* @internal
*/ enqueueReplaceState: function(publicInstance, completeState, callback, callerName) {
warnNoop(publicInstance, 'replaceState');
},
/**
* Sets a subset of the state. This only exists because _pendingState is
* internal. This provides a merging strategy that is not available to deep
* properties which is confusing. TODO: Expose pendingState or don't use it
* during the merge.
*
* @param {ReactClass} publicInstance The instance that should rerender.
* @param {object} partialState Next partial state to be merged with state.
* @param {?function} callback Called after component is updated.
* @param {?string} Name of the calling function in the public API.
* @internal
*/ enqueueSetState: function(publicInstance, partialState, callback, callerName) {
warnNoop(publicInstance, 'setState');
}
}, emptyObject = {};
/**
* Base class helpers for the updating state of a component.
*/ function Component(props, context, updater) {
this.props = props, this.context = context, this.refs = emptyObject, // renderer.
this.updater = updater || ReactNoopUpdateQueue;
}
Object.freeze(emptyObject), Component.prototype.isReactComponent = {}, /**
* Sets a subset of the state. Always use this to mutate
* state. You should treat `this.state` as immutable.
*
* There is no guarantee that `this.state` will be immediately updated, so
* accessing `this.state` after calling this method may return the old value.
*
* There is no guarantee that calls to `setState` will run synchronously,
* as they may eventually be batched together. You can provide an optional
* callback that will be executed when the call to setState is actually
* completed.
*
* When a function is provided to setState, it will be called at some point in
* the future (not synchronously). It will be called with the up to date
* component arguments (state, props, context). These values can be different
* from this.* because your function may be called after receiveProps but before
* shouldComponentUpdate, and this new state, props, and context will not yet be
* assigned to this.
*
* @param {object|function} partialState Next partial state or function to
* produce next partial state to be merged with current state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/ Component.prototype.setState = function(partialState, callback) {
if ('object' != typeof partialState && 'function' != typeof partialState && null != partialState) throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");
this.updater.enqueueSetState(this, partialState, callback, 'setState');
}, /**
* Forces an update. This should only be invoked when it is known with
* certainty that we are **not** in a DOM transaction.
*
* You may want to call this when you know that some deeper aspect of the
* component's state has changed but `setState` was not called.
*
* This will not invoke `shouldComponentUpdate`, but it will invoke
* `componentWillUpdate` and `componentDidUpdate`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/ Component.prototype.forceUpdate = function(callback) {
this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
};
var deprecatedAPIs = {
isMounted: [
'isMounted',
"Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."
],
replaceState: [
'replaceState',
"Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."
]
}, defineDeprecationWarning = function(methodName, info) {
Object.defineProperty(Component.prototype, methodName, {
get: function() {
warn('%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]);
}
});
};
for(var fnName in deprecatedAPIs)deprecatedAPIs.hasOwnProperty(fnName) && defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
function ComponentDummy() {}
/**
* Convenience component with default shallow equality check for sCU.
*/ function PureComponent(props, context, updater) {
this.props = props, this.context = context, this.refs = emptyObject, this.updater = updater || ReactNoopUpdateQueue;
}
ComponentDummy.prototype = Component.prototype;
var pureComponentPrototype = PureComponent.prototype = new ComponentDummy();
function getContextName(type) {
return type.displayName || 'Context';
}
function getComponentName(type) {
if (null == type) // Host root, text node or just invalid type.
return null;
if ('number' == typeof type.tag && error("Received an unexpected object in getComponentName(). This is likely a bug in React. Please file an issue."), 'function' == typeof type) return type.displayName || type.name || null;
if ('string' == typeof type) return type;
switch(type){
case exports.Fragment:
return 'Fragment';
case REACT_PORTAL_TYPE:
return 'Portal';
case exports.Profiler:
return 'Profiler';
case exports.StrictMode:
return 'StrictMode';
case exports.Suspense:
return 'Suspense';
case REACT_SUSPENSE_LIST_TYPE:
return 'SuspenseList';
}
if ('object' == typeof type) switch(type.$$typeof){
case REACT_CONTEXT_TYPE:
return getContextName(type) + '.Consumer';
case REACT_PROVIDER_TYPE:
return getContextName(type._context) + '.Provider';
case REACT_FORWARD_REF_TYPE:
var innerType, wrapperName, functionName;
return innerType = type.render, wrapperName = 'ForwardRef', functionName = innerType.displayName || innerType.name || '', type.displayName || ('' !== functionName ? wrapperName + "(" + functionName + ")" : wrapperName);
case REACT_MEMO_TYPE:
return getComponentName(type.type);
case REACT_BLOCK_TYPE:
return getComponentName(type._render);
case REACT_LAZY_TYPE:
var payload = type._payload, init = type._init;
try {
return getComponentName(init(payload));
} catch (x) {}
}
return null;
}
pureComponentPrototype.constructor = PureComponent, _assign(pureComponentPrototype, Component.prototype), pureComponentPrototype.isPureReactComponent = !0;
var hasOwnProperty = Object.prototype.hasOwnProperty, RESERVED_PROPS = {
key: !0,
ref: !0,
__self: !0,
__source: !0
};
function hasValidRef(config) {
if (hasOwnProperty.call(config, 'ref')) {
var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
if (getter && getter.isReactWarning) return !1;
}
return void 0 !== config.ref;
}
function hasValidKey(config) {
if (hasOwnProperty.call(config, 'key')) {
var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
if (getter && getter.isReactWarning) return !1;
}
return void 0 !== config.key;
}
didWarnAboutStringRefs = {};
/**
* Factory method to create a new React element. This no longer adheres to
* the class pattern, so do not use new to call it. Also, instanceof check
* will not work. Instead test $$typeof field against Symbol.for('react.element') to check
* if something is a React Element.
*
* @param {*} type
* @param {*} props
* @param {*} key
* @param {string|object} ref
* @param {*} owner
* @param {*} self A *temporary* helper to detect places where `this` is
* different from the `owner` when React.createElement is called, so that we
* can warn. We want to get rid of owner and replace string `ref`s with arrow
* functions, and as long as `this` and owner are the same, there will be no
* change in behavior.
* @param {*} source An annotation object (added by a transpiler or otherwise)
* indicating filename, line number, and/or other information.
* @internal
*/ var ReactElement = function(type, key, ref, self, source, owner, props) {
var element = {
// This tag allows us to uniquely identify this as a React Element
$$typeof: REACT_ELEMENT_TYPE,
// Built-in properties that belong on the element
type: type,
key: key,
ref: ref,
props: props,
// Record the component responsible for creating this element.
_owner: owner
};
return(// The validation flag is currently mutative. We put it on
// an external backing store so that we can freeze the whole object.
// This can be replaced with a WeakMap once they are implemented in
// commonly used development environments.
element._store = {}, // the validation flag non-enumerable (where possible, which should
// include every environment we run tests in), so the test framework
// ignores it.
Object.defineProperty(element._store, 'validated', {
configurable: !1,
enumerable: !1,
writable: !0,
value: !1
}), Object.defineProperty(element, '_self', {
configurable: !1,
enumerable: !1,
writable: !1,
value: self
}), // equal for testing purposes and therefore we hide it from enumeration.
Object.defineProperty(element, '_source', {
configurable: !1,
enumerable: !1,
writable: !1,
value: source
}), Object.freeze && (Object.freeze(element.props), Object.freeze(element)), element);
};
/**
* Create and return a new ReactElement of the given type.
* See https://reactjs.org/docs/react-api.html#createelement
*/ function createElement(type, config, children) {
var propName, props = {}, key = null, ref = null, self = null, source = null;
if (null != config) for(propName in hasValidRef(config) && (ref = config.ref, function(config) {
if ('string' == typeof config.ref && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) {
var componentName = getComponentName(ReactCurrentOwner.current.type);
didWarnAboutStringRefs[componentName] || (error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref), didWarnAboutStringRefs[componentName] = !0);
}
}(config)), hasValidKey(config) && (key = '' + config.key), self = void 0 === config.__self ? null : config.__self, source = void 0 === config.__source ? null : config.__source, config)hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName) && (props[propName] = config[propName]);
// Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (1 === childrenLength) props.children = children;
else if (childrenLength > 1) {
for(var childArray = Array(childrenLength), i = 0; i < childrenLength; i++)childArray[i] = arguments[i + 2];
Object.freeze && Object.freeze(childArray), props.children = childArray;
} // Resolve default props
if (type && type.defaultProps) {
var defaultProps = type.defaultProps;
for(propName in defaultProps)void 0 === props[propName] && (props[propName] = defaultProps[propName]);
}
if (key || ref) {
var warnAboutAccessingKey, warnAboutAccessingRef, displayName = 'function' == typeof type ? type.displayName || type.name || 'Unknown' : type;
key && ((warnAboutAccessingKey = function() {
specialPropKeyWarningShown || (specialPropKeyWarningShown = !0, error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName));
}).isReactWarning = !0, Object.defineProperty(props, 'key', {
get: warnAboutAccessingKey,
configurable: !0
})), ref && ((warnAboutAccessingRef = function() {
specialPropRefWarningShown || (specialPropRefWarningShown = !0, error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName));
}).isReactWarning = !0, Object.defineProperty(props, 'ref', {
get: warnAboutAccessingRef,
configurable: !0
}));
}
return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
}
/**
* Clone and return a new ReactElement using element as the starting point.
* See https://reactjs.org/docs/react-api.html#cloneelement
*/ function cloneElement(element, config, children) {
if (null == element) throw Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + ".");
var propName, defaultProps, props = _assign({}, element.props), key = element.key, ref = element.ref, self = element._self, source = element._source, owner = element._owner; // Reserved names are extracted
if (null != config) for(propName in hasValidRef(config) && (// Silently steal the ref from the parent.
ref = config.ref, owner = ReactCurrentOwner.current), hasValidKey(config) && (key = '' + config.key), element.type && element.type.defaultProps && (defaultProps = element.type.defaultProps), config)hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName) && (void 0 === config[propName] && void 0 !== defaultProps ? // Resolve default props
props[propName] = defaultProps[propName] : props[propName] = config[propName]);
// Children can be more than one argument, and those are transferred onto
// the newly allocated props object.
var childrenLength = arguments.length - 2;
if (1 === childrenLength) props.children = children;
else if (childrenLength > 1) {
for(var childArray = Array(childrenLength), i = 0; i < childrenLength; i++)childArray[i] = arguments[i + 2];
props.children = childArray;
}
return ReactElement(element.type, key, ref, self, source, owner, props);
}
/**
* Verifies the object is a ReactElement.
* See https://reactjs.org/docs/react-api.html#isvalidelement
* @param {?object} object
* @return {boolean} True if `object` is a ReactElement.
* @final
*/ function isValidElement(object) {
return 'object' == typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE;
}
/**
* TODO: Test that a single child and an array with one item have the same key
* pattern.
*/ var didWarnAboutMaps = !1, userProvidedKeyEscapeRegex = /\/+/g;
function escapeUserProvidedKey(text) {
return text.replace(userProvidedKeyEscapeRegex, '$&/');
}
/**
* Generate a key string that identifies a element within a set.
*
* @param {*} element A element that could contain a manual key.
* @param {number} index Index that is used if a manual key is not provided.
* @return {string}
*/ function getElementKey(element, index) {
// Do some typechecking here since we call this blindly. We want to ensure
// that we don't block potential future ES APIs.
if ('object' == typeof element && null !== element && null != element.key) {
var key, escaperLookup;
// Explicit key
return key = '' + element.key, escaperLookup = {
'=': '=0',
':': '=2'
}, '$' + key.replace(/[=:]/g, function(match) {
return escaperLookup[match];
});
} // Implicit key determined by the index in the set
return index.toString(36);
}
/**
* Maps children that are typically specified as `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenmap
*
* The provided mapFunction(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} func The map function.
* @param {*} context Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/ function mapChildren(children, func, context) {
if (null == children) return children;
var result = [], count = 0;
return !function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
var type = typeof children;
('undefined' === type || 'boolean' === type) && // All of the above are perceived as null.
(children = null);
var invokeCallback = !1;
if (null === children) invokeCallback = !0;
else switch(type){
case 'string':
case 'number':
invokeCallback = !0;
break;
case 'object':
switch(children.$$typeof){
case REACT_ELEMENT_TYPE:
case REACT_PORTAL_TYPE:
invokeCallback = !0;
}
}
if (invokeCallback) {
var oldElement, newKey, _child = children, mappedChild = callback(_child), childKey = '' === nameSoFar ? '.' + getElementKey(_child, 0) : nameSoFar;
if (Array.isArray(mappedChild)) {
var escapedChildKey = '';
null != childKey && (escapedChildKey = escapeUserProvidedKey(childKey) + '/'), mapIntoArray(mappedChild, array, escapedChildKey, '', function(c) {
return c;
});
} else null != mappedChild && (isValidElement(mappedChild) && (oldElement = mappedChild, newKey = // traverseAllChildren used to do for objects as children
escapedPrefix + (mappedChild.key && (!_child || _child.key !== mappedChild.key) ? escapeUserProvidedKey('' + mappedChild.key) + '/' : '') + childKey, mappedChild = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props)), array.push(mappedChild));
return 1;
}
var subtreeCount = 0, nextNamePrefix = '' === nameSoFar ? '.' : nameSoFar + ':'; // Count of children found in the current subtree.
if (Array.isArray(children)) for(var i = 0; i < children.length; i++)nextName = nextNamePrefix + getElementKey(child = children[i], i), subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
else {
var iteratorFn = getIteratorFn(children);
if ('function' == typeof iteratorFn) {
var child, nextName, step, iterableChildren = children;
// Warn about using Maps as children
iteratorFn === iterableChildren.entries && (didWarnAboutMaps || warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."), didWarnAboutMaps = !0);
for(var iterator = iteratorFn.call(iterableChildren), ii = 0; !(step = iterator.next()).done;)nextName = nextNamePrefix + getElementKey(child = step.value, ii++), subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback);
} else if ('object' === type) {
var childrenString = '' + children;
throw Error("Objects are not valid as a React child (found: " + ('[object Object]' === childrenString ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString) + "). If you meant to render a collection of children, use an array instead.");
}
}
return subtreeCount;
}(children, result, '', '', function(child) {
return func.call(context, child, count++);
}), result;
}
function lazyInitializer(payload) {
if (-1 === payload._status) {
var thenable = (0, payload._result)(); // Transition to the next state.
payload._status = 0, payload._result = thenable, thenable.then(function(moduleObject) {
if (0 === payload._status) {
var defaultExport = moduleObject.default;
void 0 === defaultExport && error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))", moduleObject), payload._status = 1, payload._result = defaultExport;
}
}, function(error) {
0 === payload._status && (payload._status = 2, payload._result = error);
});
}
if (1 === payload._status) return payload._result;
throw payload._result;
}
function isValidElementType(type) {
return 'string' == typeof type || 'function' == typeof type || type === exports.Fragment || type === exports.Profiler || type === REACT_DEBUG_TRACING_MODE_TYPE || type === exports.StrictMode || type === exports.Suspense || type === REACT_SUSPENSE_LIST_TYPE || type === REACT_LEGACY_HIDDEN_TYPE || 'object' == typeof type && null !== type && (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_FUNDAMENTAL_TYPE || type.$$typeof === REACT_BLOCK_TYPE || type[0] === REACT_SERVER_BLOCK_TYPE) || !1 // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).
;
}
function resolveDispatcher() {
var dispatcher = ReactCurrentDispatcher.current;
if (null === dispatcher) throw Error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.");
return dispatcher;
}
// Helpers to patch console.logs to avoid logging during side-effect free
// replaying on render function. This currently only patches the object
// lazily which won't cover if the log function was extracted eagerly.
// We could also eagerly patch the method.
var disabledDepth = 0;
function disabledLog() {}
disabledLog.__reactDisabledLog = !0;
var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher;
function describeBuiltInComponentFrame(name, source, ownerFn) {
if (void 0 === prefix) // Extract the VM specific prefix used by each line.
try {
throw Error();
} catch (x) {
var match = x.stack.trim().match(/\n( *(at )?)/);
prefix = match && match[1] || '';
}
// We use the prefix to ensure our stacks line up with native stack frames.
return '\n' + prefix + name;
}
var reentry = !1;
function describeNativeComponentFrame(fn, construct) {
// If something asked for a stack inside a fake render, it should get ignored.
if (!fn || reentry) return '';
var control, previousDispatcher, frame = componentFrameCache.get(fn);
if (void 0 !== frame) return frame;
reentry = !0;
var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.
Error.prepareStackTrace = void 0, previousDispatcher = ReactCurrentDispatcher$1.current, // for warnings.
ReactCurrentDispatcher$1.current = null, function() {
if (0 === disabledDepth) {
/* eslint-disable react-internal/no-production-logging */ prevLog = console.log, prevInfo = console.info, prevWarn = console.warn, prevError = console.error, prevGroup = console.group, prevGroupCollapsed = console.groupCollapsed, prevGroupEnd = console.groupEnd;
var props = {
configurable: !0,
enumerable: !0,
value: disabledLog,
writable: !0
}; // $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console, {
info: props,
log: props,
warn: props,
error: props,
group: props,
groupCollapsed: props,
groupEnd: props
});
/* eslint-enable react-internal/no-production-logging */ }
disabledDepth++;
}();
try {
// This should throw.
if (construct) {
// Something should be setting the props in the constructor.
var Fake = function() {
throw Error();
}; // $FlowFixMe
if (Object.defineProperty(Fake.prototype, 'props', {
set: function() {
// We use a throwing setter instead of frozen or non-writable props
// because that won't throw in a non-strict mode function.
throw Error();
}
}), 'object' == typeof Reflect && Reflect.construct) {
// We construct a different control for this case to include any extra
// frames added by the construct call.
try {
Reflect.construct(Fake, []);
} catch (x) {
control = x;
}
Reflect.construct(fn, [], Fake);
} else {
try {
Fake.call();
} catch (x) {
control = x;
}
fn.call(Fake.prototype);
}
} else {
try {
throw Error();
} catch (x) {
control = x;
}
fn();
}
} catch (sample) {
// This is inlined manually because closure doesn't do it for us.
if (sample && control && 'string' == typeof sample.stack) {
for(// This extracts the first frame from the sample that isn't also in the control.
// Skipping one frame that we assume is the frame that calls the two.
var sampleLines = sample.stack.split('\n'), controlLines = control.stack.split('\n'), s = sampleLines.length - 1, c = controlLines.length - 1; s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c];)// We expect at least one stack frame to be shared.
// Typically this will be the root most one. However, stack frames may be
// cut off due to maximum stack limits. In this case, one maybe cut off
// earlier than the other. We assume that the sample is longer or the same
// and there for cut off earlier. So we should find the root most frame in
// the sample somewhere in the control.
c--;
for(; s >= 1 && c >= 0; s--, c--)// Next we find the first one that isn't the same which should be the
// frame that called our sample function and the control.
if (sampleLines[s] !== controlLines[c]) {
// In V8, the first line is describing the message but other VMs don't.
// If we're about to return the first line, and the control is also on the same
// line, that's a pretty good indicator that our sample threw at same line as
// the control. I.e. before we entered the sample frame. So we ignore this result.
// This can happen if you passed a class to function component, or non-function.
if (1 !== s || 1 !== c) do // The next one that isn't the same should be our match though.
if (s--, --c < 0 || sampleLines[s] !== controlLines[c]) {
// V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
var _frame = '\n' + sampleLines[s].replace(' at new ', ' at ');
return 'function' == typeof fn && componentFrameCache.set(fn, _frame), _frame;
}
while (s >= 1 && c >= 0)
break;
}
}
} finally{
reentry = !1, ReactCurrentDispatcher$1.current = previousDispatcher, function() {
if (0 == --disabledDepth) {
/* eslint-disable react-internal/no-production-logging */ var props = {
configurable: !0,
enumerable: !0,
writable: !0
}; // $FlowFixMe Flow thinks console is immutable.
Object.defineProperties(console, {
log: _assign({}, props, {
value: prevLog
}),
info: _assign({}, props, {
value: prevInfo
}),
warn: _assign({}, props, {
value: prevWarn
}),
error: _assign({}, props, {
value: prevError
}),
group: _assign({}, props, {
value: prevGroup
}),
groupCollapsed: _assign({}, props, {
value: prevGroupCollapsed
}),
groupEnd: _assign({}, props, {
value: prevGroupEnd
})
});
/* eslint-enable react-internal/no-production-logging */ }
disabledDepth < 0 && error("disabledDepth fell below zero. This is a bug in React. Please file an issue.");
}(), Error.prepareStackTrace = previousPrepareStackTrace;
} // Fallback to just using the name if we couldn't make it throw.
var name = fn ? fn.displayName || fn.name : '', syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
return 'function' == typeof fn && componentFrameCache.set(fn, syntheticFrame), syntheticFrame;
}
function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
if (null == type) return '';
if ('function' == typeof type) return describeNativeComponentFrame(type, !!((prototype = type.prototype) && prototype.isReactComponent));
if ('string' == typeof type) return describeBuiltInComponentFrame(type);
switch(type){
case exports.Suspense:
return describeBuiltInComponentFrame('Suspense');
case REACT_SUSPENSE_LIST_TYPE:
return describeBuiltInComponentFrame('SuspenseList');
}
if ('object' == typeof type) switch(type.$$typeof){
case REACT_FORWARD_REF_TYPE:
return describeNativeComponentFrame(type.render, !1);
case REACT_MEMO_TYPE:
// Memo may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
case REACT_BLOCK_TYPE:
return describeNativeComponentFrame(type._render, !1);
case REACT_LAZY_TYPE:
var prototype, payload = type._payload, init = type._init;
try {
// Lazy may contain any component type so we recursively resolve it.
return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
} catch (x) {}
}
return '';
}
componentFrameCache = new ('function' == typeof WeakMap ? WeakMap : Map)();
var loggedTypeFailures = {}, ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
function setCurrentlyValidatingElement(element) {
if (element) {
var owner = element._owner, stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
} else ReactDebugCurrentFrame$1.setExtraStackFrame(null);
}
function setCurrentlyValidatingElement$1(element) {
if (element) {
var owner = element._owner;
currentExtraStackFrame = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
} else currentExtraStackFrame = null;
}
function getDeclarationErrorAddendum() {
if (ReactCurrentOwner.current) {
var name = getComponentName(ReactCurrentOwner.current.type);
if (name) return '\n\nCheck the render method of `' + name + '`.';
}
return '';
}
propTypesMisspellWarningShown = !1;
/**
* Warn if there's no key explicitly set on dynamic arrays of children or
* object keys are not valid. This allows us to keep track of children between
* updates.
*/ var ownerHasKeyUseWarning = {};
/**
* Warn if the element doesn't have an explicit key assigned to it.
* This element is in an array. The array could grow and shrink or be
* reordered. All children that haven't already been validated are required to
* have a "key" property assigned to it. Error statuses are cached so a warning
* will only be shown once.
*
* @internal
* @param {ReactElement} element Element that requires a key.
* @param {*} parentType element's parent's type.
*/ function validateExplicitKey(element, parentType) {
if (element._store && !element._store.validated && null == element.key) {
element._store.validated = !0;
var currentComponentErrorInfo = function(parentType) {
var info = getDeclarationErrorAddendum();
if (!info) {
var parentName = 'string' == typeof parentType ? parentType : parentType.displayName || parentType.name;
parentName && (info = "\n\nCheck the top-level render call using <" + parentName + ">.");
}
return info;
}(parentType);
if (!ownerHasKeyUseWarning[currentComponentErrorInfo]) {
ownerHasKeyUseWarning[currentComponentErrorInfo] = !0;
// property, it may be the creator of the child that's responsible for
// assigning it a key.
var childOwner = '';
element && element._owner && element._owner !== ReactCurrentOwner.current && // Give the component that originally created this child.
(childOwner = " It was passed a child from " + getComponentName(element._owner.type) + "."), setCurrentlyValidatingElement$1(element), error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner), setCurrentlyValidatingElement$1(null);
}
}
}
/**
* Ensure that every element either is passed in a static location, in an
* array with an explicit keys property defined, or in an object literal
* with valid key property.
*
* @internal
* @param {ReactNode} node Statically passed child of any type.
* @param {*} parentType node's parent's type.
*/ function validateChildKeys(node, parentType) {
if ('object' == typeof node) {
if (Array.isArray(node)) for(var i = 0; i < node.length; i++){
var child = node[i];
isValidElement(child) && validateExplicitKey(child, parentType);
}
else if (isValidElement(node)) // This element was passed in a valid location.
node._store && (node._store.validated = !0);
else if (node) {
var iteratorFn = getIteratorFn(node);
if ('function' == typeof iteratorFn && iteratorFn !== node.entries) for(var step, iterator = iteratorFn.call(node); !(step = iterator.next()).done;)isValidElement(step.value) && validateExplicitKey(step.value, parentType);
}
}
}
/**
* Given an element, validate that its props follow the propTypes definition,
* provided by the type.
*
* @param {ReactElement} element
*/ function validatePropTypes(element) {
var propTypes, type = element.type;
if (null != type && 'string' != typeof type) {
if ('function' == typeof type) propTypes = type.propTypes;
else {
if ('object' != typeof type || type.$$typeof !== REACT_FORWARD_REF_TYPE && // Note: Memo only checks outer props here.
// Inner props are checked in the reconciler.
type.$$typeof !== REACT_MEMO_TYPE) return;
propTypes = type.propTypes;
}
if (propTypes) {
// Intentionally inside to avoid triggering lazy initializers:
var name = getComponentName(type);
!function(typeSpecs, values, location, componentName, element) {
// $FlowFixMe This is okay but Flow doesn't know it.
var has = Function.call.bind(Object.prototype.hasOwnProperty);
for(var typeSpecName in typeSpecs)if (has(typeSpecs, typeSpecName)) {
var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
// fail the render phase where it didn't fail before. So we log it.
// After these have been cleaned up, we'll let them throw.
try {
// This is intentionally an invariant that gets caught. It's the same
// behavior as without this statement except with a better message.
if ('function' != typeof typeSpecs[typeSpecName]) {
var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");
throw err.name = 'Invariant Violation', err;
}
error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
} catch (ex) {
error$1 = ex;
}
!error$1 || error$1 instanceof Error || (setCurrentlyValidatingElement(element), error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || 'React class', location, typeSpecName, typeof error$1), setCurrentlyValidatingElement(null)), error$1 instanceof Error && !(error$1.message in loggedTypeFailures) && (// Only monitor this failure once because there tends to be a lot of the
// same error.
loggedTypeFailures[error$1.message] = !0, setCurrentlyValidatingElement(element), error('Failed %s type: %s', location, error$1.message), setCurrentlyValidatingElement(null));
}
}(propTypes, element.props, 'prop', name, element);
} else void 0 === type.PropTypes || propTypesMisspellWarningShown || (propTypesMisspellWarningShown = !0, error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', getComponentName(type) || 'Unknown'));
'function' != typeof type.getDefaultProps || type.getDefaultProps.isReactClassApproved || error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.");
}
}
function createElementWithValidation(type, props, children) {
var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
// succeed and there will likely be errors in render.
if (!validType) {
var typeString, info = '';
(void 0 === type || 'object' == typeof type && null !== type && 0 === Object.keys(type).length) && (info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");
var sourceInfo = function(elementProps) {
if (null != elementProps) {
var source;
return void 0 !== (source = elementProps.__source) ? '\n\nCheck your code at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' + source.lineNumber + '.' : '';
}
return '';
}(props);
sourceInfo ? info += sourceInfo : info += getDeclarationErrorAddendum(), null === type ? typeString = 'null' : Array.isArray(type) ? typeString = 'array' : void 0 !== type && type.$$typeof === REACT_ELEMENT_TYPE ? (typeString = "<" + (getComponentName(type.type) || 'Unknown') + " />", info = ' Did you accidentally export a JSX literal instead of a component?') : typeString = typeof type, error("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info);
}
var element = createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used.
// TODO: Drop this when these are no longer allowed as the type argument.
if (null == element) return element;
// Skip key warning if the type isn't valid since our key validation logic
// doesn't expect a non-string/function type and can throw confusing errors.
// We don't want exception behavior to differ between dev and prod.
// (Rendering will throw with a helpful message and as soon as the type is
// fixed, the key warnings will appear.)
if (validType) for(var i = 2; i < arguments.length; i++)validateChildKeys(arguments[i], type);
return type === exports.Fragment ? /**
* Given a fragment, validate that it can only be provided with fragment props
* @param {ReactElement} fragment
*/ function(fragment) {
for(var keys = Object.keys(fragment.props), i = 0; i < keys.length; i++){
var key = keys[i];
if ('children' !== key && 'key' !== key) {
setCurrentlyValidatingElement$1(fragment), error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key), setCurrentlyValidatingElement$1(null);
break;
}
}
null !== fragment.ref && (setCurrentlyValidatingElement$1(fragment), error('Invalid attribute `ref` supplied to `React.Fragment`.'), setCurrentlyValidatingElement$1(null));
}(element) : validatePropTypes(element), element;
}
var didWarnAboutDeprecatedCreateFactory = !1;
try {
Object.freeze({});
/* eslint-enable no-new */ } catch (e) {}
exports.Children = {
map: mapChildren,
forEach: /**
* Iterates through children that are typically specified as `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenforeach
*
* The provided forEachFunc(child, index) will be called for each
* leaf child.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} forEachFunc
* @param {*} forEachContext Context for forEachContext.
*/ function(children, forEachFunc, forEachContext) {
mapChildren(children, function() {
forEachFunc.apply(this, arguments); // Don't return anything.
}, forEachContext);
},
count: /**
* Count the number of children that are typically specified as
* `props.children`.
*
* See https://reactjs.org/docs/react-api.html#reactchildrencount
*
* @param {?*} children Children tree container.
* @return {number} The number of children.
*/ function(children) {
var n = 0;
return mapChildren(children, function() {
n++; // Don't return anything
}), n;
},
toArray: /**
* Flatten a children object (typically specified as `props.children`) and
* return an array with appropriately re-keyed children.
*
* See https://reactjs.org/docs/react-api.html#reactchildrentoarray
*/ function(children) {
return mapChildren(children, function(child) {
return child;
}) || [];
},
only: /**
* Returns the first child in a collection of children and verifies that there
* is only one child in the collection.
*
* See https://reactjs.org/docs/react-api.html#reactchildrenonly
*
* The current implementation of this function assumes that a single child gets
* passed without a wrapper, but the purpose of this helper function is to
* abstract away the particular structure of children.
*
* @param {?object} children Child collection structure.
* @return {ReactElement} The first and only `ReactElement` contained in the
* structure.
*/ function(children) {
if (!isValidElement(children)) throw Error("React.Children.only expected to receive a single React element child.");
return children;
}
}, exports.Component = Component, exports.PureComponent = PureComponent, exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals, exports.cloneElement = function(element, props, children) {
for(var newElement = cloneElement.apply(this, arguments), i = 2; i < arguments.length; i++)validateChildKeys(arguments[i], newElement.type);
return validatePropTypes(newElement), newElement;
}, exports.createContext = function(defaultValue, calculateChangedBits) {
void 0 === calculateChangedBits ? calculateChangedBits = null : null !== calculateChangedBits && 'function' != typeof calculateChangedBits && error("createContext: Expected the optional second argument to be a function. Instead received: %s", calculateChangedBits);
var context = {
$$typeof: REACT_CONTEXT_TYPE,
_calculateChangedBits: calculateChangedBits,
// As a workaround to support multiple concurrent renderers, we categorize
// some renderers as primary and others as secondary. We only expect
// there to be two concurrent renderers at most: React Native (primary) and
// Fabric (secondary); React DOM (primary) and React ART (secondary).
// Secondary renderers store their context values on separate fields.
_currentValue: defaultValue,
_currentValue2: defaultValue,
// Used to track how many concurrent renderers this context currently
// supports within in a single renderer. Such as parallel server rendering.
_threadCount: 0,
// These are circular
Provider: null,
Consumer: null
};
context.Provider = {
$$typeof: REACT_PROVIDER_TYPE,
_context: context
};
var hasWarnedAboutUsingNestedContextConsumers = !1, hasWarnedAboutUsingConsumerProvider = !1, hasWarnedAboutDisplayNameOnConsumer = !1, Consumer = {
$$typeof: REACT_CONTEXT_TYPE,
_context: context,
_calculateChangedBits: context._calculateChangedBits
};
return Object.defineProperties(Consumer, {
Provider: {
get: function() {
return hasWarnedAboutUsingConsumerProvider || (hasWarnedAboutUsingConsumerProvider = !0, error("Rendering <Context.Consumer.Provider> is not supported and will be removed in a future major release. Did you mean to render <Context.Provider> instead?")), context.Provider;
},
set: function(_Provider) {
context.Provider = _Provider;
}
},
_currentValue: {
get: function() {
return context._currentValue;
},
set: function(_currentValue) {
context._currentValue = _currentValue;
}
},
_currentValue2: {
get: function() {
return context._currentValue2;
},
set: function(_currentValue2) {
context._currentValue2 = _currentValue2;
}
},
_threadCount: {
get: function() {
return context._threadCount;
},
set: function(_threadCount) {
context._threadCount = _threadCount;
}
},
Consumer: {
get: function() {
return hasWarnedAboutUsingNestedContextConsumers || (hasWarnedAboutUsingNestedContextConsumers = !0, error("Rendering <Context.Consumer.Consumer> is not supported and will be removed in a future major release. Did you mean to render <Context.Consumer> instead?")), context.Consumer;
}
},
displayName: {
get: function() {
return context.displayName;
},
set: function(displayName) {
hasWarnedAboutDisplayNameOnConsumer || (warn("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.", displayName), hasWarnedAboutDisplayNameOnConsumer = !0);
}
}
}), context.Consumer = Consumer, context._currentRenderer = null, context._currentRenderer2 = null, context;
}, exports.createElement = createElementWithValidation, exports.createFactory = function(type) {
var validatedFactory = createElementWithValidation.bind(null, type);
return validatedFactory.type = type, didWarnAboutDeprecatedCreateFactory || (didWarnAboutDeprecatedCreateFactory = !0, warn("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead.")), Object.defineProperty(validatedFactory, 'type', {
enumerable: !1,
get: function() {
return warn("Factory.type is deprecated. Access the class directly before passing it to createFactory."), Object.defineProperty(this, 'type', {
value: type
}), type;
}
}), validatedFactory;
}, exports.createRef = // an immutable object with a single mutable value
function() {
var refObject = {
current: null
};
return Object.seal(refObject), refObject;
}, exports.forwardRef = function(render) {
null != render && render.$$typeof === REACT_MEMO_TYPE ? error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...)).") : 'function' != typeof render ? error('forwardRef requires a render function but was given %s.', null === render ? 'null' : typeof render) : 0 !== render.length && 2 !== render.length && error('forwardRef render functions accept exactly two parameters: props and ref. %s', 1 === render.length ? 'Did you forget to use the ref parameter?' : 'Any additional parameter will be undefined.'), null != render && (null != render.defaultProps || null != render.propTypes) && error("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?");
var ownName, elementType = {
$$typeof: REACT_FORWARD_REF_TYPE,
render: render
};
return Object.defineProperty(elementType, 'displayName', {
enumerable: !1,
configurable: !0,
get: function() {
return ownName;
},
set: function(name) {
ownName = name, null == render.displayName && (render.displayName = name);
}
}), elementType;
}, exports.isValidElement = isValidElement, exports.lazy = function(ctor) {
var defaultProps, propTypes, lazyType = {
$$typeof: REACT_LAZY_TYPE,
_payload: {
// We use these fields to store the result.
_status: -1,
_result: ctor
},
_init: lazyInitializer
};
return Object.defineProperties(lazyType, {
defaultProps: {
configurable: !0,
get: function() {
return defaultProps;
},
set: function(newDefaultProps) {
error("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."), defaultProps = newDefaultProps, // $FlowFixMe
Object.defineProperty(lazyType, 'defaultProps', {
enumerable: !0
});
}
},
propTypes: {
configurable: !0,
get: function() {
return propTypes;
},
set: function(newPropTypes) {
error("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."), propTypes = newPropTypes, // $FlowFixMe
Object.defineProperty(lazyType, 'propTypes', {
enumerable: !0
});
}
}
}), lazyType;
}, exports.memo = function(type, compare) {
isValidElementType(type) || error("memo: The first argument must be a component. Instead received: %s", null === type ? 'null' : typeof type);
var ownName, elementType = {
$$typeof: REACT_MEMO_TYPE,
type: type,
compare: void 0 === compare ? null : compare
};
return Object.defineProperty(elementType, 'displayName', {
enumerable: !1,
configurable: !0,
get: function() {
return ownName;
},
set: function(name) {
ownName = name, null == type.displayName && (type.displayName = name);
}
}), elementType;
}, exports.useCallback = function(callback, deps) {
return resolveDispatcher().useCallback(callback, deps);
}, exports.useContext = function(Context, unstable_observedBits) {
var dispatcher = resolveDispatcher();
if (void 0 !== unstable_observedBits && error("useContext() second argument is reserved for future use in React. Passing it is not supported. You passed: %s.%s", unstable_observedBits, 'number' == typeof unstable_observedBits && Array.isArray(arguments[2]) ? "\n\nDid you call array.map(useContext)? Calling Hooks inside a loop is not supported. Learn more at https://reactjs.org/link/rules-of-hooks" : ''), void 0 !== Context._context) {
var realContext = Context._context; // Don't deduplicate because this legitimately causes bugs
// and nobody should be using this in existing code.
realContext.Consumer === Context ? error("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?") : realContext.Provider === Context && error("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?");
}
return dispatcher.useContext(Context, unstable_observedBits);
}, exports.useDebugValue = function(value, formatterFn) {
return resolveDispatcher().useDebugValue(value, formatterFn);
}, exports.useEffect = function(create, deps) {
return resolveDispatcher().useEffect(create, deps);
}, exports.useImperativeHandle = function(ref, create, deps) {
return resolveDispatcher().useImperativeHandle(ref, create, deps);
}, exports.useLayoutEffect = function(create, deps) {
return resolveDispatcher().useLayoutEffect(create, deps);
}, exports.useMemo = function(create, deps) {
return resolveDispatcher().useMemo(create, deps);
}, exports.useReducer = function(reducer, initialArg, init) {
return resolveDispatcher().useReducer(reducer, initialArg, init);
}, exports.useRef = function(initialValue) {
return resolveDispatcher().useRef(initialValue);
}, exports.useState = function(initialState) {
return resolveDispatcher().useState(initialState);
}, exports.version = '17.0.1';
}();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/benches-full/terser.js | JavaScript | !function(global1, factory) {
'object' == typeof exports && 'undefined' != typeof module ? factory(exports, require('source-map')) : 'function' == typeof define && define.amd ? define([
'exports',
'source-map'
], factory) : factory((global1 = 'undefined' != typeof globalThis ? globalThis : global1 || self).Terser = {}, global1.sourceMap);
}(this, function(exports1, MOZ_SourceMap) {
'use strict';
let mangle_options;
var def_is_string, def_find_defs, MOZ_SourceMap__default = MOZ_SourceMap && 'object' == typeof MOZ_SourceMap && 'default' in MOZ_SourceMap ? MOZ_SourceMap : {
default: MOZ_SourceMap
};
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
***********************************************************************/ function characters(str) {
return str.split("");
}
function member(name, array) {
return array.includes(name);
}
class DefaultsError extends Error {
constructor(msg, defs){
super(), this.name = "DefaultsError", this.message = msg, this.defs = defs;
}
}
function defaults(args, defs, croak) {
!0 === args ? args = {} : null != args && "object" == typeof args && (args = {
...args
});
const ret = args || {};
if (croak) {
for(const i in ret)if (HOP(ret, i) && !HOP(defs, i)) throw new DefaultsError("`" + i + "` is not a supported option", defs);
}
for(const i in defs)if (HOP(defs, i)) {
if (args && HOP(args, i)) {
if ("ecma" === i) {
let ecma = 0 | args[i];
ecma > 5 && ecma < 2015 && (ecma += 2009), ret[i] = ecma;
} else ret[i] = args && HOP(args, i) ? args[i] : defs[i];
} else ret[i] = defs[i];
}
return ret;
}
function noop() {}
function return_false() {
return !1;
}
function return_true() {
return !0;
}
function return_this() {
return this;
}
function return_null() {
return null;
}
var MAP = function() {
function MAP(a, f, backwards) {
var i, ret = [], top = [];
function doit() {
var val = f(a[i], i), is_last = val instanceof Last;
return is_last && (val = val.v), val instanceof AtTop ? (val = val.v) instanceof Splice ? top.push.apply(top, backwards ? val.v.slice().reverse() : val.v) : top.push(val) : val !== skip && (val instanceof Splice ? ret.push.apply(ret, backwards ? val.v.slice().reverse() : val.v) : ret.push(val)), is_last;
}
if (Array.isArray(a)) {
if (backwards) {
for(i = a.length; --i >= 0 && !doit(););
ret.reverse(), top.reverse();
} else for(i = 0; i < a.length && !doit(); ++i);
} else for(i in a)if (HOP(a, i) && doit()) break;
return top.concat(ret);
}
MAP.at_top = function(val) {
return new AtTop(val);
}, MAP.splice = function(val) {
return new Splice(val);
}, MAP.last = function(val) {
return new Last(val);
};
var skip = MAP.skip = {};
function AtTop(val) {
this.v = val;
}
function Splice(val) {
this.v = val;
}
function Last(val) {
this.v = val;
}
return MAP;
}();
function make_node(ctor, orig, props) {
return props || (props = {}), orig && (props.start || (props.start = orig.start), props.end || (props.end = orig.end)), new ctor(props);
}
function push_uniq(array, el) {
array.includes(el) || array.push(el);
}
function string_template(text, props) {
return text.replace(/{(.+?)}/g, function(str, p) {
return props && props[p];
});
}
function remove(array, el) {
for(var i = array.length; --i >= 0;)array[i] === el && array.splice(i, 1);
}
function mergeSort(array, cmp) {
return array.length < 2 ? array.slice() : function _ms(a) {
if (a.length <= 1) return a;
var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m);
return function(a, b) {
for(var r = [], ai = 0, bi = 0, i = 0; ai < a.length && bi < b.length;)0 >= cmp(a[ai], b[bi]) ? r[i++] = a[ai++] : r[i++] = b[bi++];
return ai < a.length && r.push.apply(r, a.slice(ai)), bi < b.length && r.push.apply(r, b.slice(bi)), r;
}(left = _ms(left), right = _ms(right));
}(array);
}
function makePredicate(words) {
return Array.isArray(words) || (words = words.split(" ")), new Set(words.sort());
}
function map_add(map, key, value) {
map.has(key) ? map.get(key).push(value) : map.set(key, [
value
]);
}
function HOP(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
function keep_name(keep_setting, name) {
return !0 === keep_setting || keep_setting instanceof RegExp && keep_setting.test(name);
}
var lineTerminatorEscape = {
"\0": "0",
"\n": "n",
"\r": "r",
"\u2028": "u2028",
"\u2029": "u2029"
};
function regexp_source_fix(source) {
// V8 does not escape line terminators in regexp patterns in node 12
// We'll also remove literal \0
return source.replace(/[\0\n\r\u2028\u2029]/g, function(match, offset) {
return ("\\" == source[offset - 1] && ("\\" != source[offset - 2] || /(?:^|[^\\])(?:\\{2})*$/.test(source.slice(0, offset - 1))) ? "" : "\\") + lineTerminatorEscape[match];
});
}
function has_annotation(node, annotation) {
return node._annotations & annotation;
}
function set_annotation(node, annotation) {
node._annotations |= annotation;
}
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
Parser based on parse-js (http://marijn.haverbeke.nl/parse-js/).
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
***********************************************************************/ var LATEST_RAW = "", LATEST_TEMPLATE_END = !0, KEYWORDS = "break case catch class const continue debugger default delete do else export extends finally for function if in instanceof let new return switch throw try typeof var void while with", KEYWORDS_ATOM = "false null true", RESERVED_WORDS = "enum import super this " + KEYWORDS_ATOM + " " + KEYWORDS, ALL_RESERVED_WORDS = "implements interface package private protected public static " + RESERVED_WORDS, KEYWORDS_BEFORE_EXPRESSION = "return new delete throw else case yield await"; // Only used for numbers and template strings
KEYWORDS = makePredicate(KEYWORDS), RESERVED_WORDS = makePredicate(RESERVED_WORDS), KEYWORDS_BEFORE_EXPRESSION = makePredicate(KEYWORDS_BEFORE_EXPRESSION), KEYWORDS_ATOM = makePredicate(KEYWORDS_ATOM), ALL_RESERVED_WORDS = makePredicate(ALL_RESERVED_WORDS);
var OPERATOR_CHARS = makePredicate(characters("+-*&%=<>!?|~^")), RE_NUM_LITERAL = /[0-9a-f]/i, RE_HEX_NUMBER = /^0x[0-9a-f]+$/i, RE_OCT_NUMBER = /^0[0-7]+$/, RE_ES6_OCT_NUMBER = /^0o[0-7]+$/i, RE_BIN_NUMBER = /^0b[01]+$/i, RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i, RE_BIG_INT = /^(0[xob])?[0-9a-f]+n$/i, OPERATORS = makePredicate([
"in",
"instanceof",
"typeof",
"new",
"void",
"delete",
"++",
"--",
"+",
"-",
"!",
"~",
"&",
"|",
"^",
"*",
"**",
"/",
"%",
">>",
"<<",
">>>",
"<",
">",
"<=",
">=",
"==",
"===",
"!=",
"!==",
"?",
"=",
"+=",
"-=",
"||=",
"&&=",
"??=",
"/=",
"*=",
"**=",
"%=",
">>=",
"<<=",
">>>=",
"|=",
"^=",
"&=",
"&&",
"??",
"||"
]), WHITESPACE_CHARS = makePredicate(characters(" \u00a0\n\r\t\f\u000b\u200b\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\uFEFF")), NEWLINE_CHARS = makePredicate(characters("\n\r\u2028\u2029")), PUNC_AFTER_EXPRESSION = makePredicate(characters(";]),:")), PUNC_BEFORE_EXPRESSION = makePredicate(characters("[{(,;:")), PUNC_CHARS = makePredicate(characters("[]{}(),;:")), UNICODE_ID_Start = /[$A-Z_a-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/, UNICODE_ID_Continue = /(?:[$0-9A-Z_a-z\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF])+/;
function get_full_char(str, pos) {
if (is_surrogate_pair_head(str.charCodeAt(pos))) {
if (is_surrogate_pair_tail(str.charCodeAt(pos + 1))) return str.charAt(pos) + str.charAt(pos + 1);
} else if (is_surrogate_pair_tail(str.charCodeAt(pos)) && is_surrogate_pair_head(str.charCodeAt(pos - 1))) return str.charAt(pos - 1) + str.charAt(pos);
return str.charAt(pos);
}
function is_surrogate_pair_head(code) {
return code >= 0xd800 && code <= 0xdbff;
}
function is_surrogate_pair_tail(code) {
return code >= 0xdc00 && code <= 0xdfff;
}
function is_digit(code) {
return code >= 48 && code <= 57;
}
function is_identifier_start(ch) {
return UNICODE_ID_Start.test(ch);
}
function is_identifier_char(ch) {
return UNICODE_ID_Continue.test(ch);
}
const BASIC_IDENT = /^[a-z_$][a-z0-9_$]*$/i;
function is_basic_identifier_string(str) {
return BASIC_IDENT.test(str);
}
function is_identifier_string(str, allow_surrogates) {
if (BASIC_IDENT.test(str)) return !0;
if (!allow_surrogates && /[\ud800-\udfff]/.test(str)) return !1;
var match = UNICODE_ID_Start.exec(str);
return !!match && 0 === match.index && (!(str = str.slice(match[0].length)) || !!(match = UNICODE_ID_Continue.exec(str)) && match[0].length === str.length);
}
function parse_js_number(num, allow_e = !0) {
if (!allow_e && num.includes("e")) return NaN;
if (RE_HEX_NUMBER.test(num)) return parseInt(num.substr(2), 16);
if (RE_OCT_NUMBER.test(num)) return parseInt(num.substr(1), 8);
if (RE_ES6_OCT_NUMBER.test(num)) return parseInt(num.substr(2), 8);
if (RE_BIN_NUMBER.test(num)) return parseInt(num.substr(2), 2);
if (RE_DEC_NUMBER.test(num)) return parseFloat(num);
var val = parseFloat(num);
if (val == num) return val;
}
class JS_Parse_Error extends Error {
constructor(message, filename, line, col, pos){
super(), this.name = "SyntaxError", this.message = message, this.filename = filename, this.line = line, this.col = col, this.pos = pos;
}
}
function js_error(message, filename, line, col, pos) {
throw new JS_Parse_Error(message, filename, line, col, pos);
}
function is_token(token, type, val) {
return token.type == type && (null == val || token.value == val);
}
var EX_EOF = {}, UNARY_PREFIX = makePredicate([
"typeof",
"void",
"delete",
"--",
"++",
"!",
"~",
"-",
"+"
]), UNARY_POSTFIX = makePredicate([
"--",
"++"
]), ASSIGNMENT = makePredicate([
"=",
"+=",
"-=",
"??=",
"&&=",
"||=",
"/=",
"*=",
"**=",
"%=",
">>=",
"<<=",
">>>=",
"|=",
"^=",
"&="
]), LOGICAL_ASSIGNMENT = makePredicate([
"??=",
"&&=",
"||="
]), PRECEDENCE = function(a, ret) {
for(var i = 0; i < a.length; ++i)for(var b = a[i], j = 0; j < b.length; ++j)ret[b[j]] = i + 1;
return ret;
}([
[
"||"
],
[
"??"
],
[
"&&"
],
[
"|"
],
[
"^"
],
[
"&"
],
[
"==",
"===",
"!=",
"!=="
],
[
"<",
">",
"<=",
">=",
"in",
"instanceof"
],
[
">>",
"<<",
">>>"
],
[
"+",
"-"
],
[
"*",
"/",
"%"
],
[
"**"
]
], {}), ATOMIC_START_TOKEN = makePredicate([
"atom",
"num",
"big_int",
"string",
"regexp",
"name"
]);
/* -----[ Parser ]----- */ function parse($TEXT, options) {
// maps start tokens to count of comments found outside of their parens
// Example: /* I count */ ( /* I don't */ foo() )
// Useful because comments_before property of call with parens outside
// contains both comments inside and outside these parens. Used to find the
const outer_comments_before_counts = new WeakMap();
options = defaults(options, {
bare_returns: !1,
ecma: null,
expression: !1,
filename: null,
html5_comments: !0,
module: !1,
shebang: !0,
strict: !1,
toplevel: null
}, !0);
var S = {
input: "string" == typeof $TEXT ? function($TEXT, filename, html5_comments, shebang) {
var S = {
text: $TEXT,
filename: filename,
pos: 0,
tokpos: 0,
line: 1,
tokline: 0,
col: 0,
tokcol: 0,
newline_before: !1,
regex_allowed: !1,
brace_counter: 0,
template_braces: [],
comments_before: [],
directives: {},
directive_stack: []
};
function peek() {
return get_full_char(S.text, S.pos);
}
function next(signal_eof, in_string) {
var ch = get_full_char(S.text, S.pos++);
if (signal_eof && !ch) throw EX_EOF;
return NEWLINE_CHARS.has(ch) ? (S.newline_before = S.newline_before || !in_string, ++S.line, S.col = 0, "\r" == ch && "\n" == peek() && (// treat a \r\n sequence as a single \n
++S.pos, ch = "\n")) : (ch.length > 1 && (++S.pos, ++S.col), ++S.col), ch;
}
function forward(i) {
for(; i--;)next();
}
function looking_at(str) {
return S.text.substr(S.pos, str.length) == str;
}
function find(what, signal_eof) {
var pos = S.text.indexOf(what, S.pos);
if (signal_eof && -1 == pos) throw EX_EOF;
return pos;
}
function start_token() {
S.tokline = S.line, S.tokcol = S.col, S.tokpos = S.pos;
}
var prev_was_dot = !1, previous_token = null;
function token(type, value, is_comment) {
S.regex_allowed = "operator" == type && !UNARY_POSTFIX.has(value) || "keyword" == type && KEYWORDS_BEFORE_EXPRESSION.has(value) || "punc" == type && PUNC_BEFORE_EXPRESSION.has(value) || "arrow" == type, "punc" == type && ("." == value || "?." == value) ? prev_was_dot = !0 : is_comment || (prev_was_dot = !1);
const line = S.tokline, col = S.tokcol, pos = S.tokpos, nlb = S.newline_before;
let comments_before = [], comments_after = [];
is_comment || (comments_before = S.comments_before, comments_after = S.comments_before = []), S.newline_before = !1;
const tok = new AST_Token(type, value, line, col, pos, nlb, comments_before, comments_after, filename);
return is_comment || (previous_token = tok), tok;
}
function parse_error(err) {
js_error(err, filename, S.tokline, S.tokcol, S.tokpos);
}
function read_num(prefix) {
var has_e = !1, after_e = !1, has_x = !1, has_dot = "." == prefix, is_big_int = !1, numeric_separator = !1, num = function(pred) {
for(var ch, ret = "", i = 0; (ch = peek()) && pred(ch, i++);)ret += next();
return ret;
}(function(ch, i) {
if (is_big_int) return !1;
switch(ch.charCodeAt(0)){
case 95:
return numeric_separator = !0;
case 98:
case 66:
return has_x = !0; // Can occur in hex sequence, don't return false yet
case 111:
case 79:
case 120:
case 88:
return !has_x && (has_x = !0);
case 101:
case 69:
return !!has_x || !has_e && (has_e = after_e = !0);
case 45:
return after_e || 0 == i && !prefix;
case 43:
return after_e;
case after_e = !1, 46:
return !has_dot && !has_x && !has_e && (has_dot = !0);
}
return "n" === ch ? (is_big_int = !0, !0) : RE_NUM_LITERAL.test(ch);
});
if (prefix && (num = prefix + num), LATEST_RAW = num, RE_OCT_NUMBER.test(num) && next_token.has_directive("use strict") && parse_error("Legacy octal literals are not allowed in strict mode"), numeric_separator && (num.endsWith("_") ? parse_error("Numeric separators are not allowed at the end of numeric literals") : num.includes("__") && parse_error("Only one underscore is allowed as numeric separator"), num = num.replace(/_/g, "")), num.endsWith("n")) {
const without_n = num.slice(0, -1), allow_e = RE_HEX_NUMBER.test(without_n), valid = parse_js_number(without_n, allow_e);
if (!has_dot && RE_BIG_INT.test(num) && !isNaN(valid)) return token("big_int", without_n);
parse_error("Invalid or unexpected token");
}
var valid = parse_js_number(num);
if (!isNaN(valid)) return token("num", valid);
parse_error("Invalid syntax: " + num);
}
function is_octal(ch) {
return ch >= "0" && ch <= "7";
}
function read_escaped_char(in_string, strict_hex, template_string) {
var ch, p, ch1 = next(!0, in_string);
switch(ch1.charCodeAt(0)){
case 110:
return "\n";
case 114:
return "\r";
case 116:
return "\t";
case 98:
return "\b";
case 118:
return "\u000b"; // \v
case 102:
return "\f";
case 120:
return String.fromCharCode(hex_bytes(2, strict_hex)); // \x
case 117:
if ("{" == peek()) {
for(next(!0), "}" === peek() && parse_error("Expecting hex-character between {}"); "0" == peek();)next(!0); // No significance
var code, result, length = find("}", !0) - S.pos;
return (length > 6 || (result = hex_bytes(length, strict_hex)) > 0x10FFFF) && parse_error("Unicode reference out of bounds"), next(!0), // Based on https://github.com/mathiasbynens/String.fromCodePoint/blob/master/fromcodepoint.js
(code = result) > 0xFFFF ? String.fromCharCode(((code -= 0x10000) >> 10) + 0xD800) + String.fromCharCode(code % 0x400 + 0xDC00) : String.fromCharCode(code);
}
return String.fromCharCode(hex_bytes(4, strict_hex));
case 10:
return ""; // newline
case 13:
if ("\n" == peek()) return next(!0, in_string), "";
}
return is_octal(ch1) ? (template_string && strict_hex && !("0" === ch1 && !is_octal(peek())) && parse_error("Octal escape sequences are not allowed in template strings"), ch = ch1, // Parse
((p = peek()) >= "0" && p <= "7" && (ch += next(!0))[0] <= "3" && (p = peek()) >= "0" && p <= "7" && (ch += next(!0)), "0" === ch) ? "\0" : (ch.length > 0 && next_token.has_directive("use strict") && strict_hex && parse_error("Legacy octal escape sequences are not allowed in strict mode"), String.fromCharCode(parseInt(ch, 8)))) : ch1;
}
function hex_bytes(n, strict_hex) {
for(var num = 0; n > 0; --n){
if (!strict_hex && isNaN(parseInt(peek(), 16))) return parseInt(num, 16) || "";
var digit = next(!0);
isNaN(parseInt(digit, 16)) && parse_error("Invalid hex-character pattern in string"), num += digit;
}
return parseInt(num, 16);
}
var read_string = with_eof_error("Unterminated string constant", function() {
const start_pos = S.pos;
for(var quote = next(), ret = [];;){
var ch = next(!0, !0);
if ("\\" == ch) ch = read_escaped_char(!0, !0);
else if ("\r" == ch || "\n" == ch) parse_error("Unterminated string constant");
else if (ch == quote) break;
ret.push(ch);
}
var tok = token("string", ret.join(""));
return LATEST_RAW = S.text.slice(start_pos, S.pos), tok.quote = quote, tok;
}), read_template_characters = with_eof_error("Unterminated template", function(begin) {
begin && S.template_braces.push(S.brace_counter);
var ch, tok, content = "", raw = "";
for(next(!0, !0); "`" != (ch = next(!0, !0));){
if ("\r" == ch) "\n" == peek() && ++S.pos, ch = "\n";
else if ("$" == ch && "{" == peek()) return next(!0, !0), S.brace_counter++, tok = token(begin ? "template_head" : "template_substitution", content), LATEST_RAW = raw, LATEST_TEMPLATE_END = !1, tok;
if (raw += ch, "\\" == ch) {
var tmp = S.pos;
ch = read_escaped_char(!0, !(previous_token && ("name" === previous_token.type || "punc" === previous_token.type && (")" === previous_token.value || "]" === previous_token.value))), !0), raw += S.text.substr(tmp, S.pos - tmp);
}
content += ch;
}
return S.template_braces.pop(), tok = token(begin ? "template_head" : "template_substitution", content), LATEST_RAW = raw, LATEST_TEMPLATE_END = !0, tok;
});
function skip_line_comment(type) {
var ret, regex_allowed = S.regex_allowed, i = function() {
for(var text = S.text, i = S.pos, n = S.text.length; i < n; ++i){
var ch = text[i];
if (NEWLINE_CHARS.has(ch)) return i;
}
return -1;
}();
return -1 == i ? (ret = S.text.substr(S.pos), S.pos = S.text.length) : (ret = S.text.substring(S.pos, i), S.pos = i), S.col = S.tokcol + (S.pos - S.tokpos), S.comments_before.push(token(type, ret, !0)), S.regex_allowed = regex_allowed, next_token;
}
var skip_multiline_comment = with_eof_error("Unterminated multiline comment", function() {
var regex_allowed = S.regex_allowed, i = find("*/", !0), text = S.text.substring(S.pos, i).replace(/\r\n|\r|\u2028|\u2029/g, "\n");
return(// update stream position
forward(function(str) {
for(var surrogates = 0, i = 0; i < str.length; i++)is_surrogate_pair_head(str.charCodeAt(i)) && is_surrogate_pair_tail(str.charCodeAt(i + 1)) && (surrogates++, i++);
return str.length - surrogates;
}(text) + 2), S.comments_before.push(token("comment2", text, !0)), S.newline_before = S.newline_before || text.includes("\n"), S.regex_allowed = regex_allowed, next_token);
}), read_name = with_eof_error("Unterminated identifier name", function() {
var ch, name = [], escaped = !1, read_escaped_identifier_char = function() {
return escaped = !0, next(), "u" !== peek() && parse_error("Expecting UnicodeEscapeSequence -- uXXXX or u{XXXX}"), read_escaped_char(!1, !0);
};
// Read first character (ID_Start)
if ("\\" === (ch = peek())) is_identifier_start(ch = read_escaped_identifier_char()) || parse_error("First identifier char is an invalid identifier char");
else {
if (!is_identifier_start(ch)) return "";
next();
}
// Read ID_Continue
for(name.push(ch); null != (ch = peek());){
if ("\\" === (ch = peek())) is_identifier_char(ch = read_escaped_identifier_char()) || parse_error("Invalid escaped identifier char");
else {
if (!is_identifier_char(ch)) break;
next();
}
name.push(ch);
}
const name_str = name.join("");
return RESERVED_WORDS.has(name_str) && escaped && parse_error("Escaped characters are not allowed in keywords"), name_str;
}), read_regexp = with_eof_error("Unterminated regular expression", function(source) {
for(var ch, prev_backslash = !1, in_class = !1; ch = next(!0);)if (NEWLINE_CHARS.has(ch)) parse_error("Unexpected line terminator");
else if (prev_backslash) source += "\\" + ch, prev_backslash = !1;
else if ("[" == ch) in_class = !0, source += ch;
else if ("]" == ch && in_class) in_class = !1, source += ch;
else if ("/" != ch || in_class) "\\" == ch ? prev_backslash = !0 : source += ch;
else break;
return token("regexp", "/" + source + "/" + read_name());
});
function read_operator(prefix) {
return token("operator", function grow(op) {
if (!peek()) return op;
var bigger = op + peek();
return OPERATORS.has(bigger) ? (next(), grow(bigger)) : op;
}(prefix || next()));
}
function with_eof_error(eof_error, cont) {
return function(x) {
try {
return cont(x);
} catch (ex) {
if (ex === EX_EOF) parse_error(eof_error);
else throw ex;
}
};
}
function next_token(force_regexp) {
if (null != force_regexp) return read_regexp(force_regexp);
for(shebang && 0 == S.pos && looking_at("#!") && (start_token(), forward(2), skip_line_comment("comment5"));;){
if (!function() {
for(; WHITESPACE_CHARS.has(peek());)next();
}(), start_token(), html5_comments) {
if (looking_at("<!--")) {
forward(4), skip_line_comment("comment3");
continue;
}
if (looking_at("-->") && S.newline_before) {
forward(3), skip_line_comment("comment4");
continue;
}
}
var ch = peek();
if (!ch) return token("eof");
var code = ch.charCodeAt(0);
switch(code){
case 34:
case 39:
return read_string();
case 46:
return (next(), is_digit(peek().charCodeAt(0))) ? read_num(".") : "." === peek() ? (next(), next(), token("expand", "...")) : token("punc", ".");
case 47:
var tok = function() {
switch(next(), peek()){
case "/":
return next(), skip_line_comment("comment1");
case "*":
return next(), skip_multiline_comment();
}
return S.regex_allowed ? read_regexp("") : read_operator("/");
}();
if (tok === next_token) continue;
return tok;
case 61:
return (next(), ">" === peek()) ? (next(), token("arrow", "=>")) : read_operator("=");
case 63:
if (!// Used because parsing ?. involves a lookahead for a digit
function() {
if (46 !== S.text.charCodeAt(S.pos + 1)) return !1;
const cannot_be_digit = S.text.charCodeAt(S.pos + 2);
return cannot_be_digit < 48 || cannot_be_digit > 57;
}()) break; // Handled below
return next(), next(), token("punc", "?.");
case 96:
return read_template_characters(!0);
case 123:
S.brace_counter++;
break;
case 125:
if (S.brace_counter--, S.template_braces.length > 0 && S.template_braces[S.template_braces.length - 1] === S.brace_counter) return read_template_characters(!1);
}
if (is_digit(code)) return read_num();
if (PUNC_CHARS.has(ch)) return token("punc", next());
if (OPERATOR_CHARS.has(ch)) return read_operator();
if (92 == code || is_identifier_start(ch)) return function() {
var word = read_name();
return prev_was_dot ? token("name", word) : KEYWORDS_ATOM.has(word) ? token("atom", word) : KEYWORDS.has(word) ? OPERATORS.has(word) ? token("operator", word) : token("keyword", word) : token("name", word);
}();
if (35 == code) return next(), token("privatename", read_name());
break;
}
parse_error("Unexpected character '" + ch + "'");
}
return next_token.next = next, next_token.peek = peek, next_token.context = function(nc) {
return nc && (S = nc), S;
}, next_token.add_directive = function(directive) {
S.directive_stack[S.directive_stack.length - 1].push(directive), void 0 === S.directives[directive] ? S.directives[directive] = 1 : S.directives[directive]++;
}, next_token.push_directives_stack = function() {
S.directive_stack.push([]);
}, next_token.pop_directives_stack = function() {
for(var directives = S.directive_stack[S.directive_stack.length - 1], i = 0; i < directives.length; i++)S.directives[directives[i]]--;
S.directive_stack.pop();
}, next_token.has_directive = function(directive) {
return S.directives[directive] > 0;
}, next_token;
}($TEXT, options.filename, options.html5_comments, options.shebang) : $TEXT,
token: null,
prev: null,
peeked: null,
in_function: 0,
in_async: -1,
in_generator: -1,
in_directives: !0,
in_loop: 0,
labels: []
};
function is(type, value) {
return is_token(S.token, type, value);
}
function peek() {
return S.peeked || (S.peeked = S.input());
}
function next() {
return S.prev = S.token, S.peeked || peek(), S.token = S.peeked, S.peeked = null, S.in_directives = S.in_directives && ("string" == S.token.type || is("punc", ";")), S.token;
}
function prev() {
return S.prev;
}
function croak(msg, line, col, pos) {
var ctx = S.input.context();
js_error(msg, ctx.filename, null != line ? line : ctx.tokline, null != col ? col : ctx.tokcol, null != pos ? pos : ctx.tokpos);
}
function token_error(token, msg) {
croak(msg, token.line, token.col);
}
function unexpected(token) {
null == token && (token = S.token), token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")");
}
function expect_token(type, val) {
if (is(type, val)) return next();
token_error(S.token, "Unexpected token " + S.token.type + " «" + S.token.value + "», expected " + type + " «" + val + "»");
}
function expect(punc) {
return expect_token("punc", punc);
}
function has_newline_before(token) {
return token.nlb || !token.comments_before.every((comment)=>!comment.nlb);
}
function can_insert_semicolon() {
return !options.strict && (is("eof") || is("punc", "}") || has_newline_before(S.token));
}
function is_in_generator() {
return S.in_generator === S.in_function;
}
function can_await() {
return S.in_async === S.in_function || 0 === S.in_function && S.input.has_directive("use strict");
}
function semicolon(optional) {
is("punc", ";") ? next() : optional || can_insert_semicolon() || unexpected();
}
function parenthesised() {
expect("(");
var exp = expression(!0);
return expect(")"), exp;
}
function embed_tokens(parser) {
return function(...args) {
const start = S.token, expr = parser(...args);
return expr.start = start, expr.end = prev(), expr;
};
}
function handle_regexp() {
(is("operator", "/") || is("operator", "/=")) && (S.peeked = null, S.token = S.input(S.token.value.substr(1)));
}
S.token = next();
var statement = embed_tokens(function statement1(is_export_default, is_for_body, is_if_body) {
switch(handle_regexp(), S.token.type){
case "string":
if (S.in_directives) {
var token = peek();
!LATEST_RAW.includes("\\") && (is_token(token, "punc", ";") || is_token(token, "punc", "}") || has_newline_before(token) || is_token(token, "eof")) ? S.input.add_directive(S.token.value) : S.in_directives = !1;
}
var dir = S.in_directives, stat = simple_statement();
return dir && stat.body instanceof AST_String ? new AST_Directive(stat.body) : stat;
case "template_head":
case "num":
case "big_int":
case "regexp":
case "operator":
case "atom":
return simple_statement();
case "name":
if ("async" == S.token.value && is_token(peek(), "keyword", "function")) return next(), next(), is_for_body && croak("functions are not allowed as the body of a loop"), function_(AST_Defun, !1, !0, is_export_default);
if ("import" == S.token.value && !is_token(peek(), "punc", "(") && !is_token(peek(), "punc", ".")) {
next();
var label, stat1, node = function() {
var imported_name, imported_names, start = prev();
is("name") && (imported_name = as_symbol(AST_SymbolImport)), is("punc", ",") && next(), ((imported_names = map_names(!0)) || imported_name) && expect_token("name", "from");
var mod_str = S.token;
"string" !== mod_str.type && unexpected(), next();
const assert_clause = maybe_import_assertion();
return new AST_Import({
start,
imported_name,
imported_names,
module_name: new AST_String({
start: mod_str,
value: mod_str.value,
quote: mod_str.quote,
end: mod_str
}),
assert_clause,
end: S.token
});
}();
return semicolon(), node;
}
return is_token(peek(), "punc", ":") ? ("await" === (label = as_symbol(AST_Label)).name && S.in_async === S.in_function && token_error(S.prev, "await cannot be used as label inside async function"), S.labels.some((l)=>l.name === label.name) && // ECMA-262, 12.12: An ECMAScript program is considered
// syntactically incorrect if it contains a
// LabelledStatement that is enclosed by a
// LabelledStatement with the same Identifier as label.
croak("Label " + label.name + " defined twice"), expect(":"), S.labels.push(label), stat1 = statement(), S.labels.pop(), stat1 instanceof AST_IterationStatement || // check for `continue` that refers to this label.
// those should be reported as syntax errors.
// https://github.com/mishoo/UglifyJS2/issues/287
label.references.forEach(function(ref) {
ref instanceof AST_Continue && (ref = ref.label.start, croak("Continue label `" + label.name + "` refers to non-IterationStatement.", ref.line, ref.col, ref.pos));
}), new AST_LabeledStatement({
body: stat1,
label: label
})) : simple_statement();
case "punc":
switch(S.token.value){
case "{":
return new AST_BlockStatement({
start: S.token,
body: block_(),
end: prev()
});
case "[":
case "(":
return simple_statement();
case ";":
return S.in_directives = !1, next(), new AST_EmptyStatement();
default:
unexpected();
}
case "keyword":
switch(S.token.value){
case "break":
return next(), break_cont(AST_Break);
case "continue":
return next(), break_cont(AST_Continue);
case "debugger":
return next(), semicolon(), new AST_Debugger();
case "do":
next();
var cond, body, belse, body1 = in_loop(statement1);
expect_token("keyword", "while");
var condition = parenthesised();
return semicolon(!0), new AST_Do({
body: body1,
condition: condition
});
case "while":
return next(), new AST_While({
condition: parenthesised(),
body: in_loop(function() {
return statement1(!1, !0);
})
});
case "for":
return next(), function() {
var init, test, step, for_await_error = "`for await` invalid in this context", await_tok = S.token;
"name" == await_tok.type && "await" == await_tok.value ? (can_await() || token_error(await_tok, for_await_error), next()) : await_tok = !1, expect("(");
var init1 = null;
if (is("punc", ";")) await_tok && token_error(await_tok, for_await_error);
else {
init1 = is("keyword", "var") ? (next(), var_(!0)) : is("keyword", "let") ? (next(), let_(!0)) : is("keyword", "const") ? (next(), const_(!0)) : expression(!0, !0);
var init2, obj, init3, is_await, lhs, obj1, is_in = is("operator", "in"), is_of = is("name", "of");
if (await_tok && !is_of && token_error(await_tok, for_await_error), is_in || is_of) return (init1 instanceof AST_Definitions ? init1.definitions.length > 1 && token_error(init1.start, "Only one variable declaration allowed in for..in loop") : is_assignable(init1) || (init1 = to_destructuring(init1)) instanceof AST_Destructuring || token_error(init1.start, "Invalid left-hand side in for..in loop"), next(), is_in) ? (init2 = init1, obj = expression(!0), expect(")"), new AST_ForIn({
init: init2,
object: obj,
body: in_loop(function() {
return statement(!1, !0);
})
})) : (init3 = init1, is_await = !!await_tok, lhs = init3 instanceof AST_Definitions ? init3.definitions[0].name : null, obj1 = expression(!0), expect(")"), new AST_ForOf({
await: is_await,
init: init3,
name: lhs,
object: obj1,
body: in_loop(function() {
return statement(!1, !0);
})
}));
}
return init = init1, expect(";"), test = is("punc", ";") ? null : expression(!0), expect(";"), step = is("punc", ")") ? null : expression(!0), expect(")"), new AST_For({
init: init,
condition: test,
step: step,
body: in_loop(function() {
return statement(!1, !0);
})
});
}();
case "class":
return next(), is_for_body && croak("classes are not allowed as the body of a loop"), is_if_body && croak("classes are not allowed as the body of an if"), class_(AST_DefClass, is_export_default);
case "function":
return next(), is_for_body && croak("functions are not allowed as the body of a loop"), function_(AST_Defun, !1, !1, is_export_default);
case "if":
return next(), cond = parenthesised(), body = statement(!1, !1, !0), belse = null, is("keyword", "else") && (next(), belse = statement(!1, !1, !0)), new AST_If({
condition: cond,
body: body,
alternative: belse
});
case "return":
0 != S.in_function || options.bare_returns || croak("'return' outside of function"), next();
var value = null;
return is("punc", ";") ? next() : can_insert_semicolon() || (value = expression(!0), semicolon()), new AST_Return({
value: value
});
case "switch":
return next(), new AST_Switch({
expression: parenthesised(),
body: in_loop(switch_body_)
});
case "throw":
next(), has_newline_before(S.token) && croak("Illegal newline after 'throw'");
var value = expression(!0);
return semicolon(), new AST_Throw({
value: value
});
case "try":
return next(), function() {
var body = block_(), bcatch = null, bfinally = null;
if (is("keyword", "catch")) {
var start = S.token;
if (next(), is("punc", "{")) var name = null;
else {
expect("(");
var name = parameter(void 0, AST_SymbolCatch);
expect(")");
}
bcatch = new AST_Catch({
start: start,
argname: name,
body: block_(),
end: prev()
});
}
if (is("keyword", "finally")) {
var start = S.token;
next(), bfinally = new AST_Finally({
start: start,
body: block_(),
end: prev()
});
}
return bcatch || bfinally || croak("Missing catch/finally blocks"), new AST_Try({
body: body,
bcatch: bcatch,
bfinally: bfinally
});
}();
case "var":
next();
var node = var_();
return semicolon(), node;
case "let":
next();
var node = let_();
return semicolon(), node;
case "const":
next();
var node = const_();
return semicolon(), node;
case "with":
return S.input.has_directive("use strict") && croak("Strict mode may not include a with statement"), next(), new AST_With({
expression: parenthesised(),
body: statement1()
});
case "export":
if (!is_token(peek(), "punc", "(")) {
next();
var node = function() {
var is_default, exported_names, node, exported_value, exported_definition, start = S.token;
if (is("keyword", "default")) is_default = !0, next();
else if (exported_names = map_names(!1)) {
if (!is("name", "from")) return new AST_Export({
start: start,
is_default: is_default,
exported_names: exported_names,
end: prev()
});
{
next();
var mod_str = S.token;
"string" !== mod_str.type && unexpected(), next();
const assert_clause = maybe_import_assertion();
return new AST_Export({
start: start,
is_default: is_default,
exported_names: exported_names,
module_name: new AST_String({
start: mod_str,
value: mod_str.value,
quote: mod_str.quote,
end: mod_str
}),
end: prev(),
assert_clause
});
}
}
return is("punc", "{") || is_default && (is("keyword", "class") || is("keyword", "function")) && is_token(peek(), "punc") ? (exported_value = expression(!1), semicolon()) : (node = statement(is_default)) instanceof AST_Definitions && is_default ? unexpected(node.start) : node instanceof AST_Definitions || node instanceof AST_Defun || node instanceof AST_DefClass ? exported_definition = node : node instanceof AST_ClassExpression || node instanceof AST_Function ? exported_value = node : node instanceof AST_SimpleStatement ? exported_value = node.body : unexpected(node.start), new AST_Export({
start: start,
is_default: is_default,
exported_value: exported_value,
exported_definition: exported_definition,
end: prev(),
assert_clause: null
});
}();
return is("punc", ";") && semicolon(), node;
}
}
}
unexpected();
});
function simple_statement(tmp) {
return new AST_SimpleStatement({
body: (tmp = expression(!0), semicolon(), tmp)
});
}
function break_cont(type) {
var ldef, label = null;
can_insert_semicolon() || (label = as_symbol(AST_LabelRef, !0)), null != label ? ((ldef = S.labels.find((l)=>l.name === label.name)) || croak("Undefined label " + label.name), label.thedef = ldef) : 0 == S.in_loop && croak(type.TYPE + " not inside a loop or switch"), semicolon();
var stat = new type({
label: label
});
return ldef && ldef.references.push(stat), stat;
}
var arrow_function = function(start, argnames, is_async) {
has_newline_before(S.token) && croak("Unexpected newline before arrow (=>)"), expect_token("arrow", "=>");
var body = _function_body(is("punc", "{"), !1, is_async), end = body instanceof Array && body.length ? body[body.length - 1].end : body instanceof Array ? start : body.end;
return new AST_Arrow({
start: start,
end: end,
async: is_async,
argnames: argnames,
body: body
});
}, function_ = function(ctor, is_generator_property, is_async, is_export_default) {
var in_statement = ctor === AST_Defun, is_generator = is("operator", "*");
is_generator && next();
var name = is("name") ? as_symbol(in_statement ? AST_SymbolDefun : AST_SymbolLambda) : null;
in_statement && !name && (is_export_default ? ctor = AST_Function : unexpected()), !name || ctor === AST_Accessor || name instanceof AST_SymbolDeclaration || unexpected(prev());
var args = [], body = _function_body(!0, is_generator || is_generator_property, is_async, name, args);
return new ctor({
start: args.start,
end: body.end,
is_generator: is_generator,
async: is_async,
name: name,
argnames: args,
body: body
});
};
function track_used_binding_identifiers(is_parameter, strict) {
var parameters = new Set(), duplicate = !1, default_assignment = !1, spread = !1, strict_mode = !!strict, tracker = {
add_parameter: function(token) {
if (parameters.has(token.value)) !1 === duplicate && (duplicate = token), tracker.check_strict();
else if (parameters.add(token.value), is_parameter) switch(token.value){
case "arguments":
case "eval":
case "yield":
strict_mode && token_error(token, "Unexpected " + token.value + " identifier as parameter inside strict mode");
break;
default:
RESERVED_WORDS.has(token.value) && unexpected();
}
},
mark_default_assignment: function(token) {
!1 === default_assignment && (default_assignment = token);
},
mark_spread: function(token) {
!1 === spread && (spread = token);
},
mark_strict_mode: function() {
strict_mode = !0;
},
is_strict: function() {
return !1 !== default_assignment || !1 !== spread || strict_mode;
},
check_strict: function() {
tracker.is_strict() && !1 !== duplicate && token_error(duplicate, "Parameter " + duplicate.value + " was used already");
}
};
return tracker;
}
function parameter(used_parameters, symbol_type) {
var param, expand = !1;
return void 0 === used_parameters && (used_parameters = track_used_binding_identifiers(!0, S.input.has_directive("use strict"))), is("expand", "...") && (expand = S.token, used_parameters.mark_spread(S.token), next()), param = binding_element(used_parameters, symbol_type), is("operator", "=") && !1 === expand && (used_parameters.mark_default_assignment(S.token), next(), param = new AST_DefaultAssign({
start: param.start,
left: param,
operator: "=",
right: expression(!1),
end: S.token
})), !1 !== expand && (is("punc", ")") || unexpected(), param = new AST_Expansion({
start: expand,
expression: param,
end: expand
})), used_parameters.check_strict(), param;
}
function binding_element(used_parameters, symbol_type) {
var expand_token, elements = [], first = !0, is_expand = !1, first_token = S.token;
if (void 0 === used_parameters && (used_parameters = track_used_binding_identifiers(!1, S.input.has_directive("use strict"))), symbol_type = void 0 === symbol_type ? AST_SymbolFunarg : symbol_type, is("punc", "[")) {
for(next(); !is("punc", "]");){
if (first ? first = !1 : expect(","), is("expand", "...") && (is_expand = !0, expand_token = S.token, used_parameters.mark_spread(S.token), next()), is("punc")) switch(S.token.value){
case ",":
elements.push(new AST_Hole({
start: S.token,
end: S.token
}));
continue;
case "]":
break;
case "[":
case "{":
elements.push(binding_element(used_parameters, symbol_type));
break;
default:
unexpected();
}
else is("name") ? (used_parameters.add_parameter(S.token), elements.push(as_symbol(symbol_type))) : croak("Invalid function parameter");
is("operator", "=") && !1 === is_expand && (used_parameters.mark_default_assignment(S.token), next(), elements[elements.length - 1] = new AST_DefaultAssign({
start: elements[elements.length - 1].start,
left: elements[elements.length - 1],
operator: "=",
right: expression(!1),
end: S.token
})), is_expand && (is("punc", "]") || croak("Rest element must be last element"), elements[elements.length - 1] = new AST_Expansion({
start: expand_token,
expression: elements[elements.length - 1],
end: expand_token
}));
}
return expect("]"), used_parameters.check_strict(), new AST_Destructuring({
start: first_token,
names: elements,
is_array: !0,
end: prev()
});
}
if (is("punc", "{")) {
for(next(); !is("punc", "}");){
if (first ? first = !1 : expect(","), is("expand", "...") && (is_expand = !0, expand_token = S.token, used_parameters.mark_spread(S.token), next()), is("name") && (is_token(peek(), "punc") || is_token(peek(), "operator")) && [
",",
"}",
"="
].includes(peek().value)) {
used_parameters.add_parameter(S.token);
var start = prev(), value = as_symbol(symbol_type);
is_expand ? elements.push(new AST_Expansion({
start: expand_token,
expression: value,
end: value.end
})) : elements.push(new AST_ObjectKeyVal({
start: start,
key: value.name,
value: value,
end: value.end
}));
} else {
if (is("punc", "}")) continue; // Allow trailing hole
var property_token = S.token, property = as_property_name();
null === property ? unexpected(prev()) : "name" !== prev().type || is("punc", ":") ? (expect(":"), elements.push(new AST_ObjectKeyVal({
start: property_token,
quote: property_token.quote,
key: property,
value: binding_element(used_parameters, symbol_type),
end: prev()
}))) : elements.push(new AST_ObjectKeyVal({
start: prev(),
key: property,
value: new symbol_type({
start: prev(),
name: property,
end: prev()
}),
end: prev()
}));
}
is_expand ? is("punc", "}") || croak("Rest element must be last element") : is("operator", "=") && (used_parameters.mark_default_assignment(S.token), next(), elements[elements.length - 1].value = new AST_DefaultAssign({
start: elements[elements.length - 1].value.start,
left: elements[elements.length - 1].value,
operator: "=",
right: expression(!1),
end: S.token
}));
}
return expect("}"), used_parameters.check_strict(), new AST_Destructuring({
start: first_token,
names: elements,
is_array: !1,
end: prev()
});
}
if (is("name")) return used_parameters.add_parameter(S.token), as_symbol(symbol_type);
croak("Invalid function parameter");
}
function _function_body(block, generator, is_async, name, args) {
var loop = S.in_loop, labels = S.labels, current_generator = S.in_generator, current_async = S.in_async;
if (++S.in_function, generator && (S.in_generator = S.in_function), is_async && (S.in_async = S.in_function), args && function(params) {
var used_parameters = track_used_binding_identifiers(!0, S.input.has_directive("use strict"));
for(expect("("); !is("punc", ")");){
var param = parameter(used_parameters);
if (params.push(param), is("punc", ")") || expect(","), param instanceof AST_Expansion) break;
}
next();
}(args), block && (S.in_directives = !0), S.in_loop = 0, S.labels = [], block) {
S.input.push_directives_stack();
var a = block_();
name && _verify_symbol(name), args && args.forEach(_verify_symbol), S.input.pop_directives_stack();
} else var a = [
new AST_Return({
start: S.token,
value: expression(!1),
end: S.token
})
];
return --S.in_function, S.in_loop = loop, S.labels = labels, S.in_generator = current_generator, S.in_async = current_async, a;
}
function block_() {
expect("{");
for(var a = []; !is("punc", "}");)is("eof") && unexpected(), a.push(statement());
return next(), a;
}
function switch_body_() {
expect("{");
for(var tmp, a = [], cur = null, branch = null; !is("punc", "}");)is("eof") && unexpected(), is("keyword", "case") ? (branch && (branch.end = prev()), cur = [], a.push(branch = new AST_Case({
start: (tmp = S.token, next(), tmp),
expression: expression(!0),
body: cur
})), expect(":")) : is("keyword", "default") ? (branch && (branch.end = prev()), cur = [], a.push(branch = new AST_Default({
start: (tmp = S.token, next(), expect(":"), tmp),
body: cur
}))) : (cur || unexpected(), cur.push(statement()));
return branch && (branch.end = prev()), next(), a;
}
function vardefs(no_in, kind) {
for(var def, a = [];;){
var sym_type = "var" === kind ? AST_SymbolVar : "const" === kind ? AST_SymbolConst : "let" === kind ? AST_SymbolLet : null;
if (is("punc", "{") || is("punc", "[") ? def = new AST_VarDef({
start: S.token,
name: binding_element(void 0, sym_type),
value: is("operator", "=") ? (expect_token("operator", "="), expression(!1, no_in)) : null,
end: prev()
}) : "import" == (def = new AST_VarDef({
start: S.token,
name: as_symbol(sym_type),
value: is("operator", "=") ? (next(), expression(!1, no_in)) : no_in || "const" !== kind ? null : croak("Missing initializer in const declaration"),
end: prev()
})).name.name && croak("Unexpected token: import"), a.push(def), !is("punc", ",")) break;
next();
}
return a;
}
var var_ = function(no_in) {
return new AST_Var({
start: prev(),
definitions: vardefs(no_in, "var"),
end: prev()
});
}, let_ = function(no_in) {
return new AST_Let({
start: prev(),
definitions: vardefs(no_in, "let"),
end: prev()
});
}, const_ = function(no_in) {
return new AST_Const({
start: prev(),
definitions: vardefs(no_in, "const"),
end: prev()
});
}, new_ = function(allow_calls) {
var start = S.token;
if (expect_token("operator", "new"), is("punc", ".")) return next(), expect_token("name", "target"), subscripts(new AST_NewTarget({
start: start,
end: prev()
}), allow_calls);
var args, newexp = expr_atom(!1);
is("punc", "(") ? (next(), args = expr_list(")", !0)) : args = [];
var call = new AST_New({
start: start,
expression: newexp,
args: args,
end: prev()
});
return annotate(call), subscripts(call, allow_calls);
};
function as_atom_node() {
var ret, tok = S.token;
switch(tok.type){
case "name":
ret = _make_symbol(AST_SymbolRef);
break;
case "num":
ret = new AST_Number({
start: tok,
end: tok,
value: tok.value,
raw: LATEST_RAW
});
break;
case "big_int":
ret = new AST_BigInt({
start: tok,
end: tok,
value: tok.value
});
break;
case "string":
ret = new AST_String({
start: tok,
end: tok,
value: tok.value,
quote: tok.quote
});
break;
case "regexp":
const [_, source, flags] = tok.value.match(/^\/(.*)\/(\w*)$/);
ret = new AST_RegExp({
start: tok,
end: tok,
value: {
source,
flags
}
});
break;
case "atom":
switch(tok.value){
case "false":
ret = new AST_False({
start: tok,
end: tok
});
break;
case "true":
ret = new AST_True({
start: tok,
end: tok
});
break;
case "null":
ret = new AST_Null({
start: tok,
end: tok
});
}
}
return next(), ret;
}
var expr_atom = function(allow_calls, allow_arrows) {
if (is("operator", "new")) return new_(allow_calls);
if (is("operator", "import")) {
var start;
return start = S.token, expect_token("operator", "import"), expect_token("punc", "."), expect_token("name", "meta"), subscripts(new AST_ImportMeta({
start: start,
end: prev()
}), !1);
}
var peeked, start1 = S.token, async = is("name", "async") && "[" != (peeked = peek()).value && "arrow" != peeked.type && as_atom_node();
if (is("punc")) {
switch(S.token.value){
case "(":
if (async && !allow_calls) break;
var exprs = function(allow_arrows, maybe_sequence) {
var spread_token, invalid_sequence, trailing_comma, a = [];
for(expect("("); !is("punc", ")");)spread_token && unexpected(spread_token), is("expand", "...") ? (spread_token = S.token, maybe_sequence && (invalid_sequence = S.token), next(), a.push(new AST_Expansion({
start: prev(),
expression: expression(),
end: S.token
}))) : a.push(expression()), !is("punc", ")") && (expect(","), is("punc", ")") && (trailing_comma = prev(), maybe_sequence && (invalid_sequence = trailing_comma)));
return expect(")"), allow_arrows && is("arrow", "=>") ? spread_token && trailing_comma && unexpected(trailing_comma) : invalid_sequence && unexpected(invalid_sequence), a;
}(allow_arrows, !async);
if (allow_arrows && is("arrow", "=>")) return arrow_function(start1, exprs.map((e)=>(function to_fun_args(ex, default_seen_above) {
var insert_default = function(ex, default_value) {
return default_value ? new AST_DefaultAssign({
start: ex.start,
left: ex,
operator: "=",
right: default_value,
end: default_value.end
}) : ex;
};
return ex instanceof AST_Object ? insert_default(new AST_Destructuring({
start: ex.start,
end: ex.end,
is_array: !1,
names: ex.properties.map((prop)=>to_fun_args(prop))
}), default_seen_above) : ex instanceof AST_ObjectKeyVal ? (ex.value = to_fun_args(ex.value), insert_default(ex, default_seen_above)) : ex instanceof AST_Hole ? ex : ex instanceof AST_Destructuring ? (ex.names = ex.names.map((name)=>to_fun_args(name)), insert_default(ex, default_seen_above)) : ex instanceof AST_SymbolRef ? insert_default(new AST_SymbolFunarg({
name: ex.name,
start: ex.start,
end: ex.end
}), default_seen_above) : ex instanceof AST_Expansion ? (ex.expression = to_fun_args(ex.expression), insert_default(ex, default_seen_above)) : ex instanceof AST_Array ? insert_default(new AST_Destructuring({
start: ex.start,
end: ex.end,
is_array: !0,
names: ex.elements.map((elm)=>to_fun_args(elm))
}), default_seen_above) : ex instanceof AST_Assign ? insert_default(to_fun_args(ex.left, ex.right), default_seen_above) : ex instanceof AST_DefaultAssign ? (ex.left = to_fun_args(ex.left), ex) : void croak("Invalid function parameter", ex.start.line, ex.start.col);
})(e)), !!async);
var ex = async ? new AST_Call({
expression: async,
args: exprs
}) : 1 == exprs.length ? exprs[0] : new AST_Sequence({
expressions: exprs
});
if (ex.start) {
const outer_comments_before = start1.comments_before.length;
if (outer_comments_before_counts.set(start1, outer_comments_before), ex.start.comments_before.unshift(...start1.comments_before), start1.comments_before = ex.start.comments_before, 0 == outer_comments_before && start1.comments_before.length > 0) {
var comment = start1.comments_before[0];
comment.nlb || (comment.nlb = start1.nlb, start1.nlb = !1);
}
start1.comments_after = ex.start.comments_after;
}
ex.start = start1;
var end = prev();
return ex.end && (end.comments_before = ex.end.comments_before, ex.end.comments_after.push(...end.comments_after), end.comments_after = ex.end.comments_after), ex.end = end, ex instanceof AST_Call && annotate(ex), subscripts(ex, allow_calls);
case "[":
return subscripts(array_(), allow_calls);
case "{":
return subscripts(object_or_destructuring_(), allow_calls);
}
async || unexpected();
}
if (allow_arrows && is("name") && is_token(peek(), "arrow")) {
var param = new AST_SymbolFunarg({
name: S.token.value,
start: start1,
end: start1
});
return next(), arrow_function(start1, [
param
], !!async);
}
if (is("keyword", "function")) {
next();
var func = function_(AST_Function, !1, !!async);
return func.start = start1, func.end = prev(), subscripts(func, allow_calls);
}
if (async) return subscripts(async, allow_calls);
if (is("keyword", "class")) {
next();
var cls = class_(AST_ClassExpression);
return cls.start = start1, cls.end = prev(), subscripts(cls, allow_calls);
}
return is("template_head") ? subscripts(template_string(), allow_calls) : ATOMIC_START_TOKEN.has(S.token.type) ? subscripts(as_atom_node(), allow_calls) : void unexpected();
};
function template_string() {
var segments = [], start = S.token;
for(segments.push(new AST_TemplateSegment({
start: S.token,
raw: LATEST_RAW,
value: S.token.value,
end: S.token
})); !LATEST_TEMPLATE_END;)next(), handle_regexp(), segments.push(expression(!0)), segments.push(new AST_TemplateSegment({
start: S.token,
raw: LATEST_RAW,
value: S.token.value,
end: S.token
}));
return next(), new AST_TemplateString({
start: start,
segments: segments,
end: S.token
});
}
function expr_list(closing, allow_trailing_comma, allow_empty) {
for(var first = !0, a = []; !is("punc", closing) && (first ? first = !1 : expect(","), !(allow_trailing_comma && is("punc", closing)));)is("punc", ",") && allow_empty ? a.push(new AST_Hole({
start: S.token,
end: S.token
})) : is("expand", "...") ? (next(), a.push(new AST_Expansion({
start: prev(),
expression: expression(),
end: S.token
}))) : a.push(expression(!1));
return next(), a;
}
var array_ = embed_tokens(function() {
return expect("["), new AST_Array({
elements: expr_list("]", !options.strict, !0)
});
}), create_accessor = embed_tokens((is_generator, is_async)=>function_(AST_Accessor, is_generator, is_async)), object_or_destructuring_ = embed_tokens(function() {
var start = S.token, first = !0, a = [];
for(expect("{"); !is("punc", "}") && (first ? first = !1 : expect(","), !(!options.strict && is("punc", "}")));){
if ("expand" == (start = S.token).type) {
next(), a.push(new AST_Expansion({
start: start,
expression: expression(!1),
end: prev()
}));
continue;
}
var value, name = as_property_name();
// Check property and fetch value
if (is("punc", ":")) null === name ? unexpected(prev()) : (next(), value = expression(!1));
else {
var concise = concise_method_or_getset(name, start);
if (concise) {
a.push(concise);
continue;
}
value = new AST_SymbolRef({
start: prev(),
name: name,
end: prev()
});
}
is("operator", "=") && (next(), value = new AST_Assign({
start: start,
left: value,
operator: "=",
right: expression(!1),
logical: !1,
end: prev()
})), // Create property
a.push(new AST_ObjectKeyVal({
start: start,
quote: start.quote,
key: name instanceof AST_Node ? name : "" + name,
value: value,
end: prev()
}));
}
return next(), new AST_Object({
properties: a
});
});
function class_(KindOfClass, is_export_default) {
var start, method, class_name, extends_, a = [];
for(S.input.push_directives_stack(), S.input.add_directive("use strict"), "name" == S.token.type && "extends" != S.token.value && (class_name = as_symbol(KindOfClass === AST_DefClass ? AST_SymbolDefClass : AST_SymbolClass)), KindOfClass !== AST_DefClass || class_name || (is_export_default ? KindOfClass = AST_ClassExpression : unexpected()), "extends" == S.token.value && (next(), extends_ = expression(!0)), expect("{"); is("punc", ";");)next();
// Leading semicolons are okay in class bodies.
for(; !is("punc", "}");)for(start = S.token, (method = concise_method_or_getset(as_property_name(), start, !0)) || unexpected(), a.push(method); is("punc", ";");)next();
return S.input.pop_directives_stack(), next(), new KindOfClass({
start: start,
name: class_name,
extends: extends_,
properties: a,
end: prev()
});
}
function concise_method_or_getset(name, start, is_class) {
const get_symbol_ast = (name, SymbolClass = AST_SymbolMethod)=>"string" == typeof name || "number" == typeof name ? new SymbolClass({
start,
name: "" + name,
end: prev()
}) : (null === name && unexpected(), name), is_not_method_start = ()=>!is("punc", "(") && !is("punc", ",") && !is("punc", "}") && !is("punc", ";") && !is("operator", "=");
var is_async = !1, is_static = !1, is_generator = !1, is_private = !1, accessor_type = null;
is_class && "static" === name && is_not_method_start() && (is_static = !0, name = as_property_name()), "async" === name && is_not_method_start() && (is_async = !0, name = as_property_name()), "operator" === prev().type && "*" === prev().value && (is_generator = !0, name = as_property_name()), ("get" === name || "set" === name) && is_not_method_start() && (accessor_type = name, name = as_property_name()), "privatename" === prev().type && (is_private = !0);
const property_token = prev();
if (null != accessor_type) return is_private ? new ("get" === accessor_type ? AST_PrivateGetter : AST_PrivateSetter)({
start,
static: is_static,
key: get_symbol_ast(name),
value: create_accessor(),
end: prev()
}) : new ("get" === accessor_type ? AST_ObjectGetter : AST_ObjectSetter)({
start,
static: is_static,
key: name = get_symbol_ast(name),
quote: name instanceof AST_SymbolMethod ? property_token.quote : void 0,
value: create_accessor(),
end: prev()
});
if (is("punc", "(")) return new (is_private ? AST_PrivateMethod : AST_ConciseMethod)({
start: start,
static: is_static,
is_generator: is_generator,
async: is_async,
key: name = get_symbol_ast(name),
quote: name instanceof AST_SymbolMethod ? property_token.quote : void 0,
value: create_accessor(is_generator, is_async),
end: prev()
});
if (is_class) {
const key = get_symbol_ast(name, AST_SymbolClassProperty), quote = key instanceof AST_SymbolClassProperty ? property_token.quote : void 0, AST_ClassPropertyVariant = is_private ? AST_ClassPrivateProperty : AST_ClassProperty;
if (is("operator", "=")) return next(), new AST_ClassPropertyVariant({
start,
static: is_static,
quote,
key,
value: expression(!1),
end: prev()
});
if (is("name") || is("privatename") || is("operator", "*") || is("punc", ";") || is("punc", "}")) return new AST_ClassPropertyVariant({
start,
static: is_static,
quote,
key,
end: prev()
});
}
}
function maybe_import_assertion() {
return is("name", "assert") && !has_newline_before(S.token) ? (next(), object_or_destructuring_()) : null;
}
function map_names(is_import) {
var names, name, name1, foreign_name, foreign_type, type, start, end;
if (is("punc", "{")) {
for(next(), names = []; !is("punc", "}");)names.push(function(is_import) {
function make_symbol(type) {
return new type({
name: as_property_name(),
start: prev(),
end: prev()
});
}
var foreign_name, name, foreign_type = is_import ? AST_SymbolImportForeign : AST_SymbolExportForeign, type = is_import ? AST_SymbolImport : AST_SymbolExport, start = S.token;
return is_import ? foreign_name = make_symbol(foreign_type) : name = make_symbol(type), is("name", "as") ? (next(), is_import ? name = make_symbol(type) : foreign_name = make_symbol(foreign_type)) : is_import ? name = new type(foreign_name) : foreign_name = new foreign_type(name), new AST_NameMapping({
start: start,
foreign_name: foreign_name,
name: name,
end: prev()
});
}(is_import)), is("punc", ",") && next();
next();
} else is("operator", "*") && (next(), is_import && is("name", "as") && (next(), name = as_symbol(is_import ? AST_SymbolImport : AST_SymbolExportForeign)), names = [
(name1 = name, foreign_type = is_import ? AST_SymbolImportForeign : AST_SymbolExportForeign, type = is_import ? AST_SymbolImport : AST_SymbolExport, start = S.token, end = prev(), name1 = name1 || new type({
name: "*",
start: start,
end: end
}), foreign_name = new foreign_type({
name: "*",
start: start,
end: end
}), new AST_NameMapping({
start: start,
foreign_name: foreign_name,
name: name1,
end: end
}))
]);
return names;
}
function as_property_name() {
var tmp = S.token;
switch(tmp.type){
case "punc":
if ("[" === tmp.value) {
next();
var ex = expression(!1);
return expect("]"), ex;
}
unexpected(tmp);
case "operator":
if ("*" === tmp.value) return next(), null;
[
"delete",
"in",
"instanceof",
"new",
"typeof",
"void"
].includes(tmp.value) || unexpected(tmp);
/* falls through */ case "name":
case "privatename":
case "string":
case "num":
case "big_int":
case "keyword":
case "atom":
return next(), tmp.value;
default:
unexpected(tmp);
}
}
function as_name() {
var tmp = S.token;
return "name" != tmp.type && "privatename" != tmp.type && unexpected(), next(), tmp.value;
}
function _make_symbol(type) {
var name = S.token.value;
return new ("this" == name ? AST_This : "super" == name ? AST_Super : type)({
name: String(name),
start: S.token,
end: S.token
});
}
function _verify_symbol(sym) {
var name = sym.name;
is_in_generator() && "yield" == name && token_error(sym.start, "Yield cannot be used as identifier inside generators"), S.input.has_directive("use strict") && ("yield" == name && token_error(sym.start, "Unexpected yield identifier inside strict mode"), sym instanceof AST_SymbolDeclaration && ("arguments" == name || "eval" == name) && token_error(sym.start, "Unexpected " + name + " in strict mode"));
}
function as_symbol(type, noerror) {
if (!is("name")) return noerror || croak("Name expected"), null;
var sym = _make_symbol(type);
return _verify_symbol(sym), next(), sym;
}
// Annotate AST_Call, AST_Lambda or AST_New with the special comments
function annotate(node) {
var start = node.start, comments = start.comments_before;
const comments_outside_parens = outer_comments_before_counts.get(start);
for(var i = null != comments_outside_parens ? comments_outside_parens : comments.length; --i >= 0;){
var comment = comments[i];
if (/[@#]__/.test(comment.value)) {
if (/[@#]__PURE__/.test(comment.value)) {
set_annotation(node, _PURE);
break;
}
if (/[@#]__INLINE__/.test(comment.value)) {
set_annotation(node, _INLINE);
break;
}
if (/[@#]__NOINLINE__/.test(comment.value)) {
set_annotation(node, _NOINLINE);
break;
}
}
}
}
var subscripts = function(expr, allow_calls, is_chain) {
var start = expr.start;
if (is("punc", ".")) return next(), subscripts(new (is("privatename") ? AST_DotHash : AST_Dot)({
start: start,
expression: expr,
optional: !1,
property: as_name(),
end: prev()
}), allow_calls, is_chain);
if (is("punc", "[")) {
next();
var prop = expression(!0);
return expect("]"), subscripts(new AST_Sub({
start: start,
expression: expr,
optional: !1,
property: prop,
end: prev()
}), allow_calls, is_chain);
}
if (allow_calls && is("punc", "(")) {
next();
var call = new AST_Call({
start: start,
expression: expr,
optional: !1,
args: call_args(),
end: prev()
});
return annotate(call), subscripts(call, !0, is_chain);
}
if (is("punc", "?.")) {
let chain_contents;
if (next(), allow_calls && is("punc", "(")) {
next();
const call = new AST_Call({
start,
optional: !0,
expression: expr,
args: call_args(),
end: prev()
});
annotate(call), chain_contents = subscripts(call, !0, !0);
} else if (is("name") || is("privatename")) chain_contents = subscripts(new (is("privatename") ? AST_DotHash : AST_Dot)({
start,
expression: expr,
optional: !0,
property: as_name(),
end: prev()
}), allow_calls, !0);
else if (is("punc", "[")) {
next();
const property = expression(!0);
expect("]"), chain_contents = subscripts(new AST_Sub({
start,
expression: expr,
optional: !0,
property,
end: prev()
}), allow_calls, !0);
}
return (chain_contents || unexpected(), chain_contents instanceof AST_Chain) ? chain_contents : new AST_Chain({
start,
expression: chain_contents,
end: prev()
});
}
return is("template_head") ? (is_chain && // a?.b`c` is a syntax error
unexpected(), subscripts(new AST_PrefixedTemplateString({
start: start,
prefix: expr,
template_string: template_string(),
end: prev()
}), allow_calls)) : expr;
};
function call_args() {
for(var args = []; !is("punc", ")");)is("expand", "...") ? (next(), args.push(new AST_Expansion({
start: prev(),
expression: expression(!1),
end: prev()
}))) : args.push(expression(!1)), is("punc", ")") || expect(",");
return next(), args;
}
var maybe_unary = function(allow_calls, allow_arrows) {
var start = S.token;
if ("name" == start.type && "await" == start.value && can_await()) return next(), can_await() || croak("Unexpected await expression outside async function", S.prev.line, S.prev.col, S.prev.pos), new AST_Await({
start: prev(),
end: S.token,
expression: maybe_unary(!0)
});
if (is("operator") && UNARY_PREFIX.has(start.value)) {
next(), handle_regexp();
var ex = make_unary(AST_UnaryPrefix, start, maybe_unary(allow_calls));
return ex.start = start, ex.end = prev(), ex;
}
for(var val = expr_atom(allow_calls, allow_arrows); is("operator") && UNARY_POSTFIX.has(S.token.value) && !has_newline_before(S.token);)val instanceof AST_Arrow && unexpected(), (val = make_unary(AST_UnaryPostfix, S.token, val)).start = start, val.end = S.token, next();
return val;
};
function make_unary(ctor, token, expr) {
var op = token.value;
switch(op){
case "++":
case "--":
is_assignable(expr) || croak("Invalid use of " + op + " operator", token.line, token.col, token.pos);
break;
case "delete":
expr instanceof AST_SymbolRef && S.input.has_directive("use strict") && croak("Calling delete on expression not allowed in strict mode", expr.start.line, expr.start.col, expr.start.pos);
}
return new ctor({
operator: op,
expression: expr
});
}
var expr_op = function(left, min_prec, no_in) {
var op = is("operator") ? S.token.value : null;
"in" == op && no_in && (op = null), "**" == op && left instanceof AST_UnaryPrefix && !is_token(left.start, "punc", "(") && "--" !== left.operator && "++" !== left.operator && unexpected(left.start);
var prec = null != op ? PRECEDENCE[op] : null;
if (null != prec && (prec > min_prec || "**" === op && min_prec === prec)) {
next();
var right = expr_op(maybe_unary(!0), prec, no_in);
return expr_op(new AST_Binary({
start: left.start,
left: left,
operator: op,
right: right,
end: right.end
}), min_prec, no_in);
}
return left;
}, maybe_conditional = function(no_in) {
var start = S.token, expr = expr_op(maybe_unary(!0, !0), 0, no_in);
if (is("operator", "?")) {
next();
var yes = expression(!1);
return expect(":"), new AST_Conditional({
start: start,
condition: expr,
consequent: yes,
alternative: expression(!1, no_in),
end: prev()
});
}
return expr;
};
function is_assignable(expr) {
return expr instanceof AST_PropAccess || expr instanceof AST_SymbolRef;
}
function to_destructuring(node) {
if (node instanceof AST_Object) node = new AST_Destructuring({
start: node.start,
names: node.properties.map(to_destructuring),
is_array: !1,
end: node.end
});
else if (node instanceof AST_Array) {
for(var names = [], i = 0; i < node.elements.length; i++)node.elements[i] instanceof AST_Expansion && (i + 1 !== node.elements.length && token_error(node.elements[i].start, "Spread must the be last element in destructuring array"), node.elements[i].expression = to_destructuring(node.elements[i].expression)), names.push(to_destructuring(node.elements[i]));
node = new AST_Destructuring({
start: node.start,
names: names,
is_array: !0,
end: node.end
});
} else node instanceof AST_ObjectProperty ? node.value = to_destructuring(node.value) : node instanceof AST_Assign && (node = new AST_DefaultAssign({
start: node.start,
left: node.left,
operator: "=",
right: node.right,
end: node.end
}));
return node;
}
// In ES6, AssignmentExpression can also be an ArrowFunction
var maybe_assign = function(no_in) {
handle_regexp();
var start, star, has_expression, start1 = S.token;
if ("name" == start1.type && "yield" == start1.value) {
if (is_in_generator()) return next(), is_in_generator() || croak("Unexpected yield expression outside generator function", S.prev.line, S.prev.col, S.prev.pos), start = S.token, star = !1, has_expression = !0, can_insert_semicolon() || is("punc") && PUNC_AFTER_EXPRESSION.has(S.token.value) ? has_expression = !1 : is("operator", "*") && (star = !0, next()), new AST_Yield({
start: start,
is_star: star,
expression: has_expression ? expression() : null,
end: prev()
});
S.input.has_directive("use strict") && token_error(S.token, "Unexpected yield identifier inside strict mode");
}
var left = maybe_conditional(no_in), val = S.token.value;
if (is("operator") && ASSIGNMENT.has(val)) {
if (is_assignable(left) || (left = to_destructuring(left)) instanceof AST_Destructuring) return next(), new AST_Assign({
start: start1,
left: left,
operator: val,
right: maybe_assign(no_in),
logical: LOGICAL_ASSIGNMENT.has(val),
end: prev()
});
croak("Invalid assignment");
}
return left;
}, expression = function(commas, no_in) {
for(var start = S.token, exprs = []; exprs.push(maybe_assign(no_in)), commas && is("punc", ",");)next(), commas = !0;
return 1 == exprs.length ? exprs[0] : new AST_Sequence({
start: start,
expressions: exprs,
end: peek()
});
};
function in_loop(cont) {
++S.in_loop;
var ret = cont();
return --S.in_loop, ret;
}
return options.expression ? expression(!0) : function() {
var start = S.token, body = [];
for(S.input.push_directives_stack(), options.module && S.input.add_directive("use strict"); !is("eof");)body.push(statement());
S.input.pop_directives_stack();
var end = prev(), toplevel = options.toplevel;
return toplevel ? (toplevel.body = toplevel.body.concat(body), toplevel.end = end) : toplevel = new AST_Toplevel({
start: start,
body: body,
end: end
}), toplevel;
}();
}
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
***********************************************************************/ function DEFNODE(type, props, methods, base = AST_Node) {
var self_props = props = props ? props.split(/\s+/) : [];
base && base.PROPS && (props = props.concat(base.PROPS));
for(var code = "return function AST_" + type + "(props){ if (props) { ", i = props.length; --i >= 0;)code += "this." + props[i] + " = props." + props[i] + ";";
const proto = base && Object.create(base.prototype);
(proto && proto.initialize || methods && methods.initialize) && (code += "this.initialize();");
var ctor = Function(code += "}this.flags = 0;}")();
if (proto && (ctor.prototype = proto, ctor.BASE = base), base && base.SUBCLASSES.push(ctor), ctor.prototype.CTOR = ctor, ctor.prototype.constructor = ctor, ctor.PROPS = props || null, ctor.SELF_PROPS = self_props, ctor.SUBCLASSES = [], type && (ctor.prototype.TYPE = ctor.TYPE = type), methods) for(i in methods)HOP(methods, i) && ("$" === i[0] ? ctor[i.substr(1)] = methods[i] : ctor.prototype[i] = methods[i]);
return ctor.DEFMETHOD = function(name, method) {
this.prototype[name] = method;
}, ctor;
}
const has_tok_flag = (tok, flag)=>!!(tok.flags & flag), set_tok_flag = (tok, flag, truth)=>{
truth ? tok.flags |= flag : tok.flags &= ~flag;
};
class AST_Token {
constructor(type, value, line, col, pos, nlb, comments_before, comments_after, file){
this.flags = +!!nlb, this.type = type, this.value = value, this.line = line, this.col = col, this.pos = pos, this.comments_before = comments_before, this.comments_after = comments_after, this.file = file, Object.seal(this);
}
get nlb() {
return has_tok_flag(this, 0b0001);
}
set nlb(new_nlb) {
set_tok_flag(this, 0b0001, new_nlb);
}
get quote() {
return has_tok_flag(this, 0b0100) ? has_tok_flag(this, 0b0010) ? "'" : '"' : "";
}
set quote(quote_type) {
set_tok_flag(this, 0b0010, "'" === quote_type), set_tok_flag(this, 0b0100, !!quote_type);
}
}
var AST_Node = DEFNODE("Node", "start end", {
_clone: function(deep) {
if (deep) {
var self1 = this.clone();
return self1.transform(new TreeTransformer(function(node) {
if (node !== self1) return node.clone(!0);
}));
}
return new this.CTOR(this);
},
clone: function(deep) {
return this._clone(deep);
},
$documentation: "Base class of all AST nodes",
$propdoc: {
start: "[AST_Token] The first token of this node",
end: "[AST_Token] The last token of this node"
},
_walk: function(visitor) {
return visitor._visit(this);
},
walk: function(visitor) {
return this._walk(visitor); // not sure the indirection will be any help
},
_children_backwards: ()=>{}
}, null), AST_Statement = DEFNODE("Statement", null, {
$documentation: "Base class of all statements"
}), AST_Debugger = DEFNODE("Debugger", null, {
$documentation: "Represents a debugger statement"
}, AST_Statement), AST_Directive = DEFNODE("Directive", "value quote", {
$documentation: "Represents a directive, like \"use strict\";",
$propdoc: {
value: "[string] The value of this directive as a plain string (it's not an AST_String!)",
quote: "[string] the original quote character"
}
}, AST_Statement), AST_SimpleStatement = DEFNODE("SimpleStatement", "body", {
$documentation: "A statement consisting of an expression, i.e. a = 1 + 2",
$propdoc: {
body: "[AST_Node] an expression node (should not be instanceof AST_Statement)"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.body._walk(visitor);
});
},
_children_backwards (push) {
push(this.body);
}
}, AST_Statement);
function walk_body(node, visitor) {
const body = node.body;
for(var i = 0, len = body.length; i < len; i++)body[i]._walk(visitor);
}
function clone_block_scope(deep) {
var clone = this._clone(deep);
return this.block_scope && (clone.block_scope = this.block_scope.clone()), clone;
}
var AST_Block = DEFNODE("Block", "body block_scope", {
$documentation: "A body of statements (usually braced)",
$propdoc: {
body: "[AST_Statement*] an array of statements",
block_scope: "[AST_Scope] the block scope"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
walk_body(this, visitor);
});
},
_children_backwards (push) {
let i = this.body.length;
for(; i--;)push(this.body[i]);
},
clone: clone_block_scope
}, AST_Statement), AST_BlockStatement = DEFNODE("BlockStatement", null, {
$documentation: "A block statement"
}, AST_Block), AST_EmptyStatement = DEFNODE("EmptyStatement", null, {
$documentation: "The empty statement (empty block or simply a semicolon)"
}, AST_Statement), AST_StatementWithBody = DEFNODE("StatementWithBody", "body", {
$documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`",
$propdoc: {
body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement"
}
}, AST_Statement), AST_LabeledStatement = DEFNODE("LabeledStatement", "label", {
$documentation: "Statement with a label",
$propdoc: {
label: "[AST_Label] a label definition"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.label._walk(visitor), this.body._walk(visitor);
});
},
_children_backwards (push) {
push(this.body), push(this.label);
},
clone: function(deep) {
var node = this._clone(deep);
if (deep) {
var label = node.label, def = this.label;
node.walk(new TreeWalker(function(node) {
node instanceof AST_LoopControl && node.label && node.label.thedef === def && (node.label.thedef = label, label.references.push(node));
}));
}
return node;
}
}, AST_StatementWithBody), AST_IterationStatement = DEFNODE("IterationStatement", "block_scope", {
$documentation: "Internal class. All loops inherit from it.",
$propdoc: {
block_scope: "[AST_Scope] the block scope for this iteration statement."
},
clone: clone_block_scope
}, AST_StatementWithBody), AST_DWLoop = DEFNODE("DWLoop", "condition", {
$documentation: "Base class for do/while statements",
$propdoc: {
condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement"
}
}, AST_IterationStatement), AST_Do = DEFNODE("Do", null, {
$documentation: "A `do` statement",
_walk: function(visitor) {
return visitor._visit(this, function() {
this.body._walk(visitor), this.condition._walk(visitor);
});
},
_children_backwards (push) {
push(this.condition), push(this.body);
}
}, AST_DWLoop), AST_While = DEFNODE("While", null, {
$documentation: "A `while` statement",
_walk: function(visitor) {
return visitor._visit(this, function() {
this.condition._walk(visitor), this.body._walk(visitor);
});
},
_children_backwards (push) {
push(this.body), push(this.condition);
}
}, AST_DWLoop), AST_For = DEFNODE("For", "init condition step", {
$documentation: "A `for` statement",
$propdoc: {
init: "[AST_Node?] the `for` initialization code, or null if empty",
condition: "[AST_Node?] the `for` termination clause, or null if empty",
step: "[AST_Node?] the `for` update clause, or null if empty"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.init && this.init._walk(visitor), this.condition && this.condition._walk(visitor), this.step && this.step._walk(visitor), this.body._walk(visitor);
});
},
_children_backwards (push) {
push(this.body), this.step && push(this.step), this.condition && push(this.condition), this.init && push(this.init);
}
}, AST_IterationStatement), AST_ForIn = DEFNODE("ForIn", "init object", {
$documentation: "A `for ... in` statement",
$propdoc: {
init: "[AST_Node] the `for/in` initialization code",
object: "[AST_Node] the object that we're looping through"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.init._walk(visitor), this.object._walk(visitor), this.body._walk(visitor);
});
},
_children_backwards (push) {
push(this.body), this.object && push(this.object), this.init && push(this.init);
}
}, AST_IterationStatement), AST_ForOf = DEFNODE("ForOf", "await", {
$documentation: "A `for ... of` statement"
}, AST_ForIn), AST_With = DEFNODE("With", "expression", {
$documentation: "A `with` statement",
$propdoc: {
expression: "[AST_Node] the `with` expression"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.expression._walk(visitor), this.body._walk(visitor);
});
},
_children_backwards (push) {
push(this.body), push(this.expression);
}
}, AST_StatementWithBody), AST_Scope = DEFNODE("Scope", "variables functions uses_with uses_eval parent_scope enclosed cname", {
$documentation: "Base class for all statements introducing a lexical scope",
$propdoc: {
variables: "[Map/S] a map of name -> SymbolDef for all variables/functions defined in this scope",
uses_with: "[boolean/S] tells whether this scope uses the `with` statement",
uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`",
parent_scope: "[AST_Scope?/S] link to the parent scope",
enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",
cname: "[integer/S] current index for mangling variables (used internally by the mangler)"
},
get_defun_scope: function() {
for(var self1 = this; self1.is_block_scope();)self1 = self1.parent_scope;
return self1;
},
clone: function(deep, toplevel) {
var node = this._clone(deep);
return deep && this.variables && toplevel && !this._block_scope ? node.figure_out_scope({}, {
toplevel: toplevel,
parent_scope: this.parent_scope
}) : (this.variables && (node.variables = new Map(this.variables)), this.enclosed && (node.enclosed = this.enclosed.slice()), this._block_scope && (node._block_scope = this._block_scope)), node;
},
pinned: function() {
return this.uses_eval || this.uses_with;
}
}, AST_Block), AST_Toplevel = DEFNODE("Toplevel", "globals", {
$documentation: "The toplevel scope",
$propdoc: {
globals: "[Map/S] a map of name -> SymbolDef for all undeclared names"
},
wrap_commonjs: function(name) {
var body = this.body, wrapped_tl = "(function(exports){'$ORIG';})(typeof " + name + "=='undefined'?(" + name + "={}):" + name + ");";
return (wrapped_tl = parse(wrapped_tl)).transform(new TreeTransformer(function(node) {
if (node instanceof AST_Directive && "$ORIG" == node.value) return MAP.splice(body);
}));
},
wrap_enclose: function(args_values) {
"string" != typeof args_values && (args_values = "");
var index = args_values.indexOf(":");
index < 0 && (index = args_values.length);
var body = this.body;
return parse([
"(function(",
args_values.slice(0, index),
'){"$ORIG"})(',
args_values.slice(index + 1),
")"
].join("")).transform(new TreeTransformer(function(node) {
if (node instanceof AST_Directive && "$ORIG" == node.value) return MAP.splice(body);
}));
}
}, AST_Scope), AST_Expansion = DEFNODE("Expansion", "expression", {
$documentation: "An expandible argument, such as ...rest, a splat, such as [1,2,...all], or an expansion in a variable declaration, such as var [first, ...rest] = list",
$propdoc: {
expression: "[AST_Node] the thing to be expanded"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.expression.walk(visitor);
});
},
_children_backwards (push) {
push(this.expression);
}
}), AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments is_generator async", {
$documentation: "Base class for functions",
$propdoc: {
name: "[AST_SymbolDeclaration?] the name of this function",
argnames: "[AST_SymbolFunarg|AST_Destructuring|AST_Expansion|AST_DefaultAssign*] array of function arguments, destructurings, or expanding arguments",
uses_arguments: "[boolean/S] tells whether this function accesses the arguments array",
is_generator: "[boolean] is this a generator method",
async: "[boolean] is this method async"
},
args_as_names: function() {
for(var out = [], i = 0; i < this.argnames.length; i++)this.argnames[i] instanceof AST_Destructuring ? out.push(...this.argnames[i].all_symbols()) : out.push(this.argnames[i]);
return out;
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.name && this.name._walk(visitor);
for(var argnames = this.argnames, i = 0, len = argnames.length; i < len; i++)argnames[i]._walk(visitor);
walk_body(this, visitor);
});
},
_children_backwards (push) {
let i = this.body.length;
for(; i--;)push(this.body[i]);
for(i = this.argnames.length; i--;)push(this.argnames[i]);
this.name && push(this.name);
},
is_braceless () {
return this.body[0] instanceof AST_Return && this.body[0].value;
},
// Default args and expansion don't count, so .argnames.length doesn't cut it
length_property () {
let length = 0;
for (const arg of this.argnames)(arg instanceof AST_SymbolFunarg || arg instanceof AST_Destructuring) && length++;
return length;
}
}, AST_Scope), AST_Accessor = DEFNODE("Accessor", null, {
$documentation: "A setter/getter function. The `name` property is always null."
}, AST_Lambda), AST_Function = DEFNODE("Function", null, {
$documentation: "A function expression"
}, AST_Lambda), AST_Arrow = DEFNODE("Arrow", null, {
$documentation: "An ES6 Arrow function ((a) => b)"
}, AST_Lambda), AST_Defun = DEFNODE("Defun", null, {
$documentation: "A function definition"
}, AST_Lambda), AST_Destructuring = DEFNODE("Destructuring", "names is_array", {
$documentation: "A destructuring of several names. Used in destructuring assignment and with destructuring function argument names",
$propdoc: {
names: "[AST_Node*] Array of properties or elements",
is_array: "[Boolean] Whether the destructuring represents an object or array"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.names.forEach(function(name) {
name._walk(visitor);
});
});
},
_children_backwards (push) {
let i = this.names.length;
for(; i--;)push(this.names[i]);
},
all_symbols: function() {
var out = [];
return this.walk(new TreeWalker(function(node) {
node instanceof AST_Symbol && out.push(node);
})), out;
}
}), AST_PrefixedTemplateString = DEFNODE("PrefixedTemplateString", "template_string prefix", {
$documentation: "A templatestring with a prefix, such as String.raw`foobarbaz`",
$propdoc: {
template_string: "[AST_TemplateString] The template string",
prefix: "[AST_Node] The prefix, which will get called."
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.prefix._walk(visitor), this.template_string._walk(visitor);
});
},
_children_backwards (push) {
push(this.template_string), push(this.prefix);
}
}), AST_TemplateString = DEFNODE("TemplateString", "segments", {
$documentation: "A template string literal",
$propdoc: {
segments: "[AST_Node*] One or more segments, starting with AST_TemplateSegment. AST_Node may follow AST_TemplateSegment, but each AST_Node must be followed by AST_TemplateSegment."
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.segments.forEach(function(seg) {
seg._walk(visitor);
});
});
},
_children_backwards (push) {
let i = this.segments.length;
for(; i--;)push(this.segments[i]);
}
}), AST_TemplateSegment = DEFNODE("TemplateSegment", "value raw", {
$documentation: "A segment of a template string literal",
$propdoc: {
value: "Content of the segment",
raw: "Raw source of the segment"
}
}), AST_Jump = DEFNODE("Jump", null, {
$documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"
}, AST_Statement), AST_Exit = DEFNODE("Exit", "value", {
$documentation: "Base class for “exits” (`return` and `throw`)",
$propdoc: {
value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return"
},
_walk: function(visitor) {
return visitor._visit(this, this.value && function() {
this.value._walk(visitor);
});
},
_children_backwards (push) {
this.value && push(this.value);
}
}, AST_Jump), AST_Return = DEFNODE("Return", null, {
$documentation: "A `return` statement"
}, AST_Exit), AST_Throw = DEFNODE("Throw", null, {
$documentation: "A `throw` statement"
}, AST_Exit), AST_LoopControl = DEFNODE("LoopControl", "label", {
$documentation: "Base class for loop control statements (`break` and `continue`)",
$propdoc: {
label: "[AST_LabelRef?] the label, or null if none"
},
_walk: function(visitor) {
return visitor._visit(this, this.label && function() {
this.label._walk(visitor);
});
},
_children_backwards (push) {
this.label && push(this.label);
}
}, AST_Jump), AST_Break = DEFNODE("Break", null, {
$documentation: "A `break` statement"
}, AST_LoopControl), AST_Continue = DEFNODE("Continue", null, {
$documentation: "A `continue` statement"
}, AST_LoopControl), AST_Await = DEFNODE("Await", "expression", {
$documentation: "An `await` statement",
$propdoc: {
expression: "[AST_Node] the mandatory expression being awaited"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.expression._walk(visitor);
});
},
_children_backwards (push) {
push(this.expression);
}
}), AST_Yield = DEFNODE("Yield", "expression is_star", {
$documentation: "A `yield` statement",
$propdoc: {
expression: "[AST_Node?] the value returned or thrown by this statement; could be null (representing undefined) but only when is_star is set to false",
is_star: "[Boolean] Whether this is a yield or yield* statement"
},
_walk: function(visitor) {
return visitor._visit(this, this.expression && function() {
this.expression._walk(visitor);
});
},
_children_backwards (push) {
this.expression && push(this.expression);
}
}), AST_If = DEFNODE("If", "condition alternative", {
$documentation: "A `if` statement",
$propdoc: {
condition: "[AST_Node] the `if` condition",
alternative: "[AST_Statement?] the `else` part, or null if not present"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.condition._walk(visitor), this.body._walk(visitor), this.alternative && this.alternative._walk(visitor);
});
},
_children_backwards (push) {
this.alternative && push(this.alternative), push(this.body), push(this.condition);
}
}, AST_StatementWithBody), AST_Switch = DEFNODE("Switch", "expression", {
$documentation: "A `switch` statement",
$propdoc: {
expression: "[AST_Node] the `switch` “discriminant”"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.expression._walk(visitor), walk_body(this, visitor);
});
},
_children_backwards (push) {
let i = this.body.length;
for(; i--;)push(this.body[i]);
push(this.expression);
}
}, AST_Block), AST_SwitchBranch = DEFNODE("SwitchBranch", null, {
$documentation: "Base class for `switch` branches"
}, AST_Block), AST_Default = DEFNODE("Default", null, {
$documentation: "A `default` switch branch"
}, AST_SwitchBranch), AST_Case = DEFNODE("Case", "expression", {
$documentation: "A `case` switch branch",
$propdoc: {
expression: "[AST_Node] the `case` expression"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.expression._walk(visitor), walk_body(this, visitor);
});
},
_children_backwards (push) {
let i = this.body.length;
for(; i--;)push(this.body[i]);
push(this.expression);
}
}, AST_SwitchBranch), AST_Try = DEFNODE("Try", "bcatch bfinally", {
$documentation: "A `try` statement",
$propdoc: {
bcatch: "[AST_Catch?] the catch block, or null if not present",
bfinally: "[AST_Finally?] the finally block, or null if not present"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
walk_body(this, visitor), this.bcatch && this.bcatch._walk(visitor), this.bfinally && this.bfinally._walk(visitor);
});
},
_children_backwards (push) {
this.bfinally && push(this.bfinally), this.bcatch && push(this.bcatch);
let i = this.body.length;
for(; i--;)push(this.body[i]);
}
}, AST_Block), AST_Catch = DEFNODE("Catch", "argname", {
$documentation: "A `catch` node; only makes sense as part of a `try` statement",
$propdoc: {
argname: "[AST_SymbolCatch|AST_Destructuring|AST_Expansion|AST_DefaultAssign] symbol for the exception"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.argname && this.argname._walk(visitor), walk_body(this, visitor);
});
},
_children_backwards (push) {
let i = this.body.length;
for(; i--;)push(this.body[i]);
this.argname && push(this.argname);
}
}, AST_Block), AST_Finally = DEFNODE("Finally", null, {
$documentation: "A `finally` node; only makes sense as part of a `try` statement"
}, AST_Block), AST_Definitions = DEFNODE("Definitions", "definitions", {
$documentation: "Base class for `var` or `const` nodes (variable declarations/initializations)",
$propdoc: {
definitions: "[AST_VarDef*] array of variable definitions"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
for(var definitions = this.definitions, i = 0, len = definitions.length; i < len; i++)definitions[i]._walk(visitor);
});
},
_children_backwards (push) {
let i = this.definitions.length;
for(; i--;)push(this.definitions[i]);
}
}, AST_Statement), AST_Var = DEFNODE("Var", null, {
$documentation: "A `var` statement"
}, AST_Definitions), AST_Let = DEFNODE("Let", null, {
$documentation: "A `let` statement"
}, AST_Definitions), AST_Const = DEFNODE("Const", null, {
$documentation: "A `const` statement"
}, AST_Definitions), AST_VarDef = DEFNODE("VarDef", "name value", {
$documentation: "A variable declaration; only appears in a AST_Definitions node",
$propdoc: {
name: "[AST_Destructuring|AST_SymbolConst|AST_SymbolLet|AST_SymbolVar] name of the variable",
value: "[AST_Node?] initializer, or null of there's no initializer"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.name._walk(visitor), this.value && this.value._walk(visitor);
});
},
_children_backwards (push) {
this.value && push(this.value), push(this.name);
}
}), AST_NameMapping = DEFNODE("NameMapping", "foreign_name name", {
$documentation: "The part of the export/import statement that declare names from a module.",
$propdoc: {
foreign_name: "[AST_SymbolExportForeign|AST_SymbolImportForeign] The name being exported/imported (as specified in the module)",
name: "[AST_SymbolExport|AST_SymbolImport] The name as it is visible to this module."
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.foreign_name._walk(visitor), this.name._walk(visitor);
});
},
_children_backwards (push) {
push(this.name), push(this.foreign_name);
}
}), AST_Import = DEFNODE("Import", "imported_name imported_names module_name assert_clause", {
$documentation: "An `import` statement",
$propdoc: {
imported_name: "[AST_SymbolImport] The name of the variable holding the module's default export.",
imported_names: "[AST_NameMapping*] The names of non-default imported variables",
module_name: "[AST_String] String literal describing where this module came from",
assert_clause: "[AST_Object?] The import assertion"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.imported_name && this.imported_name._walk(visitor), this.imported_names && this.imported_names.forEach(function(name_import) {
name_import._walk(visitor);
}), this.module_name._walk(visitor);
});
},
_children_backwards (push) {
if (push(this.module_name), this.imported_names) {
let i = this.imported_names.length;
for(; i--;)push(this.imported_names[i]);
}
this.imported_name && push(this.imported_name);
}
}), AST_ImportMeta = DEFNODE("ImportMeta", null, {
$documentation: "A reference to import.meta"
}), AST_Export = DEFNODE("Export", "exported_definition exported_value is_default exported_names module_name assert_clause", {
$documentation: "An `export` statement",
$propdoc: {
exported_definition: "[AST_Defun|AST_Definitions|AST_DefClass?] An exported definition",
exported_value: "[AST_Node?] An exported value",
exported_names: "[AST_NameMapping*?] List of exported names",
module_name: "[AST_String?] Name of the file to load exports from",
is_default: "[Boolean] Whether this is the default exported value of this module",
assert_clause: "[AST_Object?] The import assertion"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.exported_definition && this.exported_definition._walk(visitor), this.exported_value && this.exported_value._walk(visitor), this.exported_names && this.exported_names.forEach(function(name_export) {
name_export._walk(visitor);
}), this.module_name && this.module_name._walk(visitor);
});
},
_children_backwards (push) {
if (this.module_name && push(this.module_name), this.exported_names) {
let i = this.exported_names.length;
for(; i--;)push(this.exported_names[i]);
}
this.exported_value && push(this.exported_value), this.exported_definition && push(this.exported_definition);
}
}, AST_Statement), AST_Call = DEFNODE("Call", "expression args optional _annotations", {
$documentation: "A function call expression",
$propdoc: {
expression: "[AST_Node] expression to invoke as function",
args: "[AST_Node*] array of arguments",
optional: "[boolean] whether this is an optional call (IE ?.() )",
_annotations: "[number] bitfield containing information about the call"
},
initialize () {
null == this._annotations && (this._annotations = 0);
},
_walk (visitor) {
return visitor._visit(this, function() {
for(var args = this.args, i = 0, len = args.length; i < len; i++)args[i]._walk(visitor);
this.expression._walk(visitor); // TODO why do we need to crawl this last?
});
},
_children_backwards (push) {
let i = this.args.length;
for(; i--;)push(this.args[i]);
push(this.expression);
}
}), AST_New = DEFNODE("New", null, {
$documentation: "An object instantiation. Derives from a function call since it has exactly the same properties"
}, AST_Call), AST_Sequence = DEFNODE("Sequence", "expressions", {
$documentation: "A sequence expression (comma-separated expressions)",
$propdoc: {
expressions: "[AST_Node*] array of expressions (at least two)"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.expressions.forEach(function(node) {
node._walk(visitor);
});
});
},
_children_backwards (push) {
let i = this.expressions.length;
for(; i--;)push(this.expressions[i]);
}
}), AST_PropAccess = DEFNODE("PropAccess", "expression property optional", {
$documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`",
$propdoc: {
expression: "[AST_Node] the “container” expression",
property: "[AST_Node|string] the property to access. For AST_Dot & AST_DotHash this is always a plain string, while for AST_Sub it's an arbitrary AST_Node",
optional: "[boolean] whether this is an optional property access (IE ?.)"
}
}), AST_Dot = DEFNODE("Dot", "quote", {
$documentation: "A dotted property access expression",
$propdoc: {
quote: "[string] the original quote character when transformed from AST_Sub"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.expression._walk(visitor);
});
},
_children_backwards (push) {
push(this.expression);
}
}, AST_PropAccess), AST_DotHash = DEFNODE("DotHash", "", {
$documentation: "A dotted property access to a private property",
_walk: function(visitor) {
return visitor._visit(this, function() {
this.expression._walk(visitor);
});
},
_children_backwards (push) {
push(this.expression);
}
}, AST_PropAccess), AST_Sub = DEFNODE("Sub", null, {
$documentation: "Index-style property access, i.e. `a[\"foo\"]`",
_walk: function(visitor) {
return visitor._visit(this, function() {
this.expression._walk(visitor), this.property._walk(visitor);
});
},
_children_backwards (push) {
push(this.property), push(this.expression);
}
}, AST_PropAccess), AST_Chain = DEFNODE("Chain", "expression", {
$documentation: "A chain expression like a?.b?.(c)?.[d]",
$propdoc: {
expression: "[AST_Call|AST_Dot|AST_DotHash|AST_Sub] chain element."
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.expression._walk(visitor);
});
},
_children_backwards (push) {
push(this.expression);
}
}), AST_Unary = DEFNODE("Unary", "operator expression", {
$documentation: "Base class for unary expressions",
$propdoc: {
operator: "[string] the operator",
expression: "[AST_Node] expression that this unary operator applies to"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.expression._walk(visitor);
});
},
_children_backwards (push) {
push(this.expression);
}
}), AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, {
$documentation: "Unary prefix expression, i.e. `typeof i` or `++i`"
}, AST_Unary), AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, {
$documentation: "Unary postfix expression, i.e. `i++`"
}, AST_Unary), AST_Binary = DEFNODE("Binary", "operator left right", {
$documentation: "Binary expression, i.e. `a + b`",
$propdoc: {
left: "[AST_Node] left-hand side expression",
operator: "[string] the operator",
right: "[AST_Node] right-hand side expression"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.left._walk(visitor), this.right._walk(visitor);
});
},
_children_backwards (push) {
push(this.right), push(this.left);
}
}), AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", {
$documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`",
$propdoc: {
condition: "[AST_Node]",
consequent: "[AST_Node]",
alternative: "[AST_Node]"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.condition._walk(visitor), this.consequent._walk(visitor), this.alternative._walk(visitor);
});
},
_children_backwards (push) {
push(this.alternative), push(this.consequent), push(this.condition);
}
}), AST_Assign = DEFNODE("Assign", "logical", {
$documentation: "An assignment expression — `a = b + 5`",
$propdoc: {
logical: "Whether it's a logical assignment"
}
}, AST_Binary), AST_DefaultAssign = DEFNODE("DefaultAssign", null, {
$documentation: "A default assignment expression like in `(a = 3) => a`"
}, AST_Binary), AST_Array = DEFNODE("Array", "elements", {
$documentation: "An array literal",
$propdoc: {
elements: "[AST_Node*] array of elements"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
for(var elements = this.elements, i = 0, len = elements.length; i < len; i++)elements[i]._walk(visitor);
});
},
_children_backwards (push) {
let i = this.elements.length;
for(; i--;)push(this.elements[i]);
}
}), AST_Object = DEFNODE("Object", "properties", {
$documentation: "An object literal",
$propdoc: {
properties: "[AST_ObjectProperty*] array of properties"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
for(var properties = this.properties, i = 0, len = properties.length; i < len; i++)properties[i]._walk(visitor);
});
},
_children_backwards (push) {
let i = this.properties.length;
for(; i--;)push(this.properties[i]);
}
}), AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", {
$documentation: "Base class for literal object properties",
$propdoc: {
key: "[string|AST_Node] property name. For ObjectKeyVal this is a string. For getters, setters and computed property this is an AST_Node.",
value: "[AST_Node] property value. For getters and setters this is an AST_Accessor."
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.key instanceof AST_Node && this.key._walk(visitor), this.value._walk(visitor);
});
},
_children_backwards (push) {
push(this.value), this.key instanceof AST_Node && push(this.key);
}
}), AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", "quote", {
$documentation: "A key: value object property",
$propdoc: {
quote: "[string] the original quote character"
},
computed_key () {
return this.key instanceof AST_Node;
}
}, AST_ObjectProperty), AST_PrivateSetter = DEFNODE("PrivateSetter", "static", {
$propdoc: {
static: "[boolean] whether this is a static private setter"
},
$documentation: "A private setter property",
computed_key: ()=>!1
}, AST_ObjectProperty), AST_PrivateGetter = DEFNODE("PrivateGetter", "static", {
$propdoc: {
static: "[boolean] whether this is a static private getter"
},
$documentation: "A private getter property",
computed_key: ()=>!1
}, AST_ObjectProperty), AST_ObjectSetter = DEFNODE("ObjectSetter", "quote static", {
$propdoc: {
quote: "[string|undefined] the original quote character, if any",
static: "[boolean] whether this is a static setter (classes only)"
},
$documentation: "An object setter property",
computed_key () {
return !(this.key instanceof AST_SymbolMethod);
}
}, AST_ObjectProperty), AST_ObjectGetter = DEFNODE("ObjectGetter", "quote static", {
$propdoc: {
quote: "[string|undefined] the original quote character, if any",
static: "[boolean] whether this is a static getter (classes only)"
},
$documentation: "An object getter property",
computed_key () {
return !(this.key instanceof AST_SymbolMethod);
}
}, AST_ObjectProperty), AST_ConciseMethod = DEFNODE("ConciseMethod", "quote static is_generator async", {
$propdoc: {
quote: "[string|undefined] the original quote character, if any",
static: "[boolean] is this method static (classes only)",
is_generator: "[boolean] is this a generator method",
async: "[boolean] is this method async"
},
$documentation: "An ES6 concise method inside an object or class",
computed_key () {
return !(this.key instanceof AST_SymbolMethod);
}
}, AST_ObjectProperty), AST_PrivateMethod = DEFNODE("PrivateMethod", "", {
$documentation: "A private class method inside a class"
}, AST_ConciseMethod), AST_Class = DEFNODE("Class", "name extends properties", {
$propdoc: {
name: "[AST_SymbolClass|AST_SymbolDefClass?] optional class name.",
extends: "[AST_Node]? optional parent class",
properties: "[AST_ObjectProperty*] array of properties"
},
$documentation: "An ES6 class",
_walk: function(visitor) {
return visitor._visit(this, function() {
this.name && this.name._walk(visitor), this.extends && this.extends._walk(visitor), this.properties.forEach((prop)=>prop._walk(visitor));
});
},
_children_backwards (push) {
let i = this.properties.length;
for(; i--;)push(this.properties[i]);
this.extends && push(this.extends), this.name && push(this.name);
}
}, AST_Scope /* TODO a class might have a scope but it's not a scope */ ), AST_ClassProperty = DEFNODE("ClassProperty", "static quote", {
$documentation: "A class property",
$propdoc: {
static: "[boolean] whether this is a static key",
quote: "[string] which quote is being used"
},
_walk: function(visitor) {
return visitor._visit(this, function() {
this.key instanceof AST_Node && this.key._walk(visitor), this.value instanceof AST_Node && this.value._walk(visitor);
});
},
_children_backwards (push) {
this.value instanceof AST_Node && push(this.value), this.key instanceof AST_Node && push(this.key);
},
computed_key () {
return !(this.key instanceof AST_SymbolClassProperty);
}
}, AST_ObjectProperty), AST_ClassPrivateProperty = DEFNODE("ClassPrivateProperty", "", {
$documentation: "A class property for a private property"
}, AST_ClassProperty), AST_DefClass = DEFNODE("DefClass", null, {
$documentation: "A class definition"
}, AST_Class), AST_ClassExpression = DEFNODE("ClassExpression", null, {
$documentation: "A class expression."
}, AST_Class), AST_Symbol = DEFNODE("Symbol", "scope name thedef", {
$propdoc: {
name: "[string] name of this symbol",
scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)",
thedef: "[SymbolDef/S] the definition of this symbol"
},
$documentation: "Base class for all symbols"
}), AST_NewTarget = DEFNODE("NewTarget", null, {
$documentation: "A reference to new.target"
}), AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", {
$documentation: "A declaration symbol (symbol in var/const, function name or argument, symbol in catch)"
}, AST_Symbol), AST_SymbolVar = DEFNODE("SymbolVar", null, {
$documentation: "Symbol defining a variable"
}, AST_SymbolDeclaration), AST_SymbolBlockDeclaration = DEFNODE("SymbolBlockDeclaration", null, {
$documentation: "Base class for block-scoped declaration symbols"
}, AST_SymbolDeclaration), AST_SymbolConst = DEFNODE("SymbolConst", null, {
$documentation: "A constant declaration"
}, AST_SymbolBlockDeclaration), AST_SymbolLet = DEFNODE("SymbolLet", null, {
$documentation: "A block-scoped `let` declaration"
}, AST_SymbolBlockDeclaration), AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, {
$documentation: "Symbol naming a function argument"
}, AST_SymbolVar), AST_SymbolDefun = DEFNODE("SymbolDefun", null, {
$documentation: "Symbol defining a function"
}, AST_SymbolDeclaration), AST_SymbolMethod = DEFNODE("SymbolMethod", null, {
$documentation: "Symbol in an object defining a method"
}, AST_Symbol), AST_SymbolClassProperty = DEFNODE("SymbolClassProperty", null, {
$documentation: "Symbol for a class property"
}, AST_Symbol), AST_SymbolLambda = DEFNODE("SymbolLambda", null, {
$documentation: "Symbol naming a function expression"
}, AST_SymbolDeclaration), AST_SymbolDefClass = DEFNODE("SymbolDefClass", null, {
$documentation: "Symbol naming a class's name in a class declaration. Lexically scoped to its containing scope, and accessible within the class."
}, AST_SymbolBlockDeclaration), AST_SymbolClass = DEFNODE("SymbolClass", null, {
$documentation: "Symbol naming a class's name. Lexically scoped to the class."
}, AST_SymbolDeclaration), AST_SymbolCatch = DEFNODE("SymbolCatch", null, {
$documentation: "Symbol naming the exception in catch"
}, AST_SymbolBlockDeclaration), AST_SymbolImport = DEFNODE("SymbolImport", null, {
$documentation: "Symbol referring to an imported name"
}, AST_SymbolBlockDeclaration), AST_SymbolImportForeign = DEFNODE("SymbolImportForeign", null, {
$documentation: "A symbol imported from a module, but it is defined in the other module, and its real name is irrelevant for this module's purposes"
}, AST_Symbol), AST_Label = DEFNODE("Label", "references", {
$documentation: "Symbol naming a label (declaration)",
$propdoc: {
references: "[AST_LoopControl*] a list of nodes referring to this label"
},
initialize: function() {
this.references = [], this.thedef = this;
}
}, AST_Symbol), AST_SymbolRef = DEFNODE("SymbolRef", null, {
$documentation: "Reference to some symbol (not definition/declaration)"
}, AST_Symbol), AST_SymbolExport = DEFNODE("SymbolExport", null, {
$documentation: "Symbol referring to a name to export"
}, AST_SymbolRef), AST_SymbolExportForeign = DEFNODE("SymbolExportForeign", null, {
$documentation: "A symbol exported from this module, but it is used in the other module, and its real name is irrelevant for this module's purposes"
}, AST_Symbol), AST_LabelRef = DEFNODE("LabelRef", null, {
$documentation: "Reference to a label symbol"
}, AST_Symbol), AST_This = DEFNODE("This", null, {
$documentation: "The `this` symbol"
}, AST_Symbol), AST_Super = DEFNODE("Super", null, {
$documentation: "The `super` symbol"
}, AST_This), AST_Constant = DEFNODE("Constant", null, {
$documentation: "Base class for all constants",
getValue: function() {
return this.value;
}
}), AST_String = DEFNODE("String", "value quote", {
$documentation: "A string literal",
$propdoc: {
value: "[string] the contents of this string",
quote: "[string] the original quote character"
}
}, AST_Constant), AST_Number = DEFNODE("Number", "value raw", {
$documentation: "A number literal",
$propdoc: {
value: "[number] the numeric value",
raw: "[string] numeric value as string"
}
}, AST_Constant), AST_BigInt = DEFNODE("BigInt", "value", {
$documentation: "A big int literal",
$propdoc: {
value: "[string] big int value"
}
}, AST_Constant), AST_RegExp = DEFNODE("RegExp", "value", {
$documentation: "A regexp literal",
$propdoc: {
value: "[RegExp] the actual regexp"
}
}, AST_Constant), AST_Atom = DEFNODE("Atom", null, {
$documentation: "Base class for atoms"
}, AST_Constant), AST_Null = DEFNODE("Null", null, {
$documentation: "The `null` atom",
value: null
}, AST_Atom), AST_NaN = DEFNODE("NaN", null, {
$documentation: "The impossible value",
value: 0 / 0
}, AST_Atom), AST_Undefined = DEFNODE("Undefined", null, {
$documentation: "The `undefined` value",
value: void 0
}, AST_Atom), AST_Hole = DEFNODE("Hole", null, {
$documentation: "A hole in an array",
value: void 0
}, AST_Atom), AST_Infinity = DEFNODE("Infinity", null, {
$documentation: "The `Infinity` value",
value: 1 / 0
}, AST_Atom), AST_Boolean = DEFNODE("Boolean", null, {
$documentation: "Base class for booleans"
}, AST_Atom), AST_False = DEFNODE("False", null, {
$documentation: "The `false` atom",
value: !1
}, AST_Boolean), AST_True = DEFNODE("True", null, {
$documentation: "The `true` atom",
value: !0
}, AST_Boolean);
/* -----[ Walk function ]---- */ /**
* Walk nodes in depth-first search fashion.
* Callback can return `walk_abort` symbol to stop iteration.
* It can also return `true` to stop iteration just for child nodes.
* Iteration can be stopped and continued by passing the `to_visit` argument,
* which is given to the callback in the second argument.
**/ function walk(node, cb, to_visit = [
node
]) {
const push = to_visit.push.bind(to_visit);
for(; to_visit.length;){
const node = to_visit.pop(), ret = cb(node, to_visit);
if (ret) {
if (ret === walk_abort) return !0;
continue;
}
node._children_backwards(push);
}
return !1;
}
function walk_parent(node, cb, initial_stack) {
let current;
const to_visit = [
node
], push = to_visit.push.bind(to_visit), stack = initial_stack ? initial_stack.slice() : [], parent_pop_indices = [], info = {
parent: (n = 0)=>-1 === n ? current : initial_stack && n >= stack.length ? (n -= stack.length, initial_stack[initial_stack.length - (n + 1)]) : stack[stack.length - (1 + n)]
};
for(; to_visit.length;){
for(current = to_visit.pop(); parent_pop_indices.length && to_visit.length == parent_pop_indices[parent_pop_indices.length - 1];)stack.pop(), parent_pop_indices.pop();
const ret = cb(current, info);
if (ret) {
if (ret === walk_abort) return !0;
continue;
}
const visit_length = to_visit.length;
current._children_backwards(push), to_visit.length > visit_length && (stack.push(current), parent_pop_indices.push(visit_length - 1));
}
return !1;
}
const walk_abort = Symbol("abort walk");
/* -----[ TreeWalker ]----- */ class TreeWalker {
constructor(callback){
this.visit = callback, this.stack = [], this.directives = Object.create(null);
}
_visit(node, descend) {
this.push(node);
var ret = this.visit(node, descend ? function() {
descend.call(node);
} : noop);
return !ret && descend && descend.call(node), this.pop(), ret;
}
parent(n) {
return this.stack[this.stack.length - 2 - (n || 0)];
}
push(node) {
node instanceof AST_Lambda ? this.directives = Object.create(this.directives) : node instanceof AST_Directive && !this.directives[node.value] ? this.directives[node.value] = node : node instanceof AST_Class && (this.directives = Object.create(this.directives), this.directives["use strict"] || (this.directives["use strict"] = node)), this.stack.push(node);
}
pop() {
var node = this.stack.pop();
(node instanceof AST_Lambda || node instanceof AST_Class) && (this.directives = Object.getPrototypeOf(this.directives));
}
self() {
return this.stack[this.stack.length - 1];
}
find_parent(type) {
for(var stack = this.stack, i = stack.length; --i >= 0;){
var x = stack[i];
if (x instanceof type) return x;
}
}
has_directive(type) {
var dir = this.directives[type];
if (dir) return dir;
var node = this.stack[this.stack.length - 1];
if (node instanceof AST_Scope && node.body) for(var i = 0; i < node.body.length; ++i){
var st = node.body[i];
if (!(st instanceof AST_Directive)) break;
if (st.value == type) return st;
}
}
loopcontrol_target(node) {
var stack = this.stack;
if (node.label) for(var i = stack.length; --i >= 0;){
var x = stack[i];
if (x instanceof AST_LabeledStatement && x.label.name == node.label.name) return x.body;
}
else for(var i = stack.length; --i >= 0;){
var x = stack[i];
if (x instanceof AST_IterationStatement || node instanceof AST_Break && x instanceof AST_Switch) return x;
}
}
}
// Tree transformer helpers.
class TreeTransformer extends TreeWalker {
constructor(before, after){
super(), this.before = before, this.after = after;
}
}
const _PURE = 0b00000001, _INLINE = 0b00000010, _NOINLINE = 0b00000100;
var ast = /*#__PURE__*/ Object.freeze({
__proto__: null,
AST_Accessor: AST_Accessor,
AST_Array: AST_Array,
AST_Arrow: AST_Arrow,
AST_Assign: AST_Assign,
AST_Atom: AST_Atom,
AST_Await: AST_Await,
AST_BigInt: AST_BigInt,
AST_Binary: AST_Binary,
AST_Block: AST_Block,
AST_BlockStatement: AST_BlockStatement,
AST_Boolean: AST_Boolean,
AST_Break: AST_Break,
AST_Call: AST_Call,
AST_Case: AST_Case,
AST_Catch: AST_Catch,
AST_Chain: AST_Chain,
AST_Class: AST_Class,
AST_ClassExpression: AST_ClassExpression,
AST_ClassPrivateProperty: AST_ClassPrivateProperty,
AST_ClassProperty: AST_ClassProperty,
AST_ConciseMethod: AST_ConciseMethod,
AST_Conditional: AST_Conditional,
AST_Const: AST_Const,
AST_Constant: AST_Constant,
AST_Continue: AST_Continue,
AST_Debugger: AST_Debugger,
AST_Default: AST_Default,
AST_DefaultAssign: AST_DefaultAssign,
AST_DefClass: AST_DefClass,
AST_Definitions: AST_Definitions,
AST_Defun: AST_Defun,
AST_Destructuring: AST_Destructuring,
AST_Directive: AST_Directive,
AST_Do: AST_Do,
AST_Dot: AST_Dot,
AST_DotHash: AST_DotHash,
AST_DWLoop: AST_DWLoop,
AST_EmptyStatement: AST_EmptyStatement,
AST_Exit: AST_Exit,
AST_Expansion: AST_Expansion,
AST_Export: AST_Export,
AST_False: AST_False,
AST_Finally: AST_Finally,
AST_For: AST_For,
AST_ForIn: AST_ForIn,
AST_ForOf: AST_ForOf,
AST_Function: AST_Function,
AST_Hole: AST_Hole,
AST_If: AST_If,
AST_Import: AST_Import,
AST_ImportMeta: AST_ImportMeta,
AST_Infinity: AST_Infinity,
AST_IterationStatement: AST_IterationStatement,
AST_Jump: AST_Jump,
AST_Label: AST_Label,
AST_LabeledStatement: AST_LabeledStatement,
AST_LabelRef: AST_LabelRef,
AST_Lambda: AST_Lambda,
AST_Let: AST_Let,
AST_LoopControl: AST_LoopControl,
AST_NameMapping: AST_NameMapping,
AST_NaN: AST_NaN,
AST_New: AST_New,
AST_NewTarget: AST_NewTarget,
AST_Node: AST_Node,
AST_Null: AST_Null,
AST_Number: AST_Number,
AST_Object: AST_Object,
AST_ObjectGetter: AST_ObjectGetter,
AST_ObjectKeyVal: AST_ObjectKeyVal,
AST_ObjectProperty: AST_ObjectProperty,
AST_ObjectSetter: AST_ObjectSetter,
AST_PrefixedTemplateString: AST_PrefixedTemplateString,
AST_PrivateGetter: AST_PrivateGetter,
AST_PrivateMethod: AST_PrivateMethod,
AST_PrivateSetter: AST_PrivateSetter,
AST_PropAccess: AST_PropAccess,
AST_RegExp: AST_RegExp,
AST_Return: AST_Return,
AST_Scope: AST_Scope,
AST_Sequence: AST_Sequence,
AST_SimpleStatement: AST_SimpleStatement,
AST_Statement: AST_Statement,
AST_StatementWithBody: AST_StatementWithBody,
AST_String: AST_String,
AST_Sub: AST_Sub,
AST_Super: AST_Super,
AST_Switch: AST_Switch,
AST_SwitchBranch: AST_SwitchBranch,
AST_Symbol: AST_Symbol,
AST_SymbolBlockDeclaration: AST_SymbolBlockDeclaration,
AST_SymbolCatch: AST_SymbolCatch,
AST_SymbolClass: AST_SymbolClass,
AST_SymbolClassProperty: AST_SymbolClassProperty,
AST_SymbolConst: AST_SymbolConst,
AST_SymbolDeclaration: AST_SymbolDeclaration,
AST_SymbolDefClass: AST_SymbolDefClass,
AST_SymbolDefun: AST_SymbolDefun,
AST_SymbolExport: AST_SymbolExport,
AST_SymbolExportForeign: AST_SymbolExportForeign,
AST_SymbolFunarg: AST_SymbolFunarg,
AST_SymbolImport: AST_SymbolImport,
AST_SymbolImportForeign: AST_SymbolImportForeign,
AST_SymbolLambda: AST_SymbolLambda,
AST_SymbolLet: AST_SymbolLet,
AST_SymbolMethod: AST_SymbolMethod,
AST_SymbolRef: AST_SymbolRef,
AST_SymbolVar: AST_SymbolVar,
AST_TemplateSegment: AST_TemplateSegment,
AST_TemplateString: AST_TemplateString,
AST_This: AST_This,
AST_Throw: AST_Throw,
AST_Token: AST_Token,
AST_Toplevel: AST_Toplevel,
AST_True: AST_True,
AST_Try: AST_Try,
AST_Unary: AST_Unary,
AST_UnaryPostfix: AST_UnaryPostfix,
AST_UnaryPrefix: AST_UnaryPrefix,
AST_Undefined: AST_Undefined,
AST_Var: AST_Var,
AST_VarDef: AST_VarDef,
AST_While: AST_While,
AST_With: AST_With,
AST_Yield: AST_Yield,
TreeTransformer: TreeTransformer,
TreeWalker: TreeWalker,
walk: walk,
walk_abort: walk_abort,
walk_body: walk_body,
walk_parent: walk_parent,
_INLINE: 0b00000010,
_NOINLINE: 0b00000100,
_PURE: 0b00000001
});
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
***********************************************************************/ function def_transform(node, descend) {
node.DEFMETHOD("transform", function(tw, in_list) {
let transformed;
if (tw.push(this), tw.before && (transformed = tw.before(this, descend, in_list)), void 0 === transformed && (transformed = this, descend(transformed, tw), tw.after)) {
const after_ret = tw.after(transformed, in_list);
void 0 !== after_ret && (transformed = after_ret);
}
return tw.pop(), transformed;
});
}
function do_list(list, tw) {
return MAP(list, function(node) {
return node.transform(tw, !0);
});
}
// return true if the node at the top of the stack (that means the
// innermost node in the current output) is lexically the first in
// a statement.
function first_in_statement(stack) {
let node = stack.parent(-1);
for(let i = 0, p; p = stack.parent(i); i++){
if (p instanceof AST_Statement && p.body === node) return !0;
if ((!(p instanceof AST_Sequence) || p.expressions[0] !== node) && ("Call" !== p.TYPE || p.expression !== node) && (!(p instanceof AST_PrefixedTemplateString) || p.prefix !== node) && (!(p instanceof AST_Dot) || p.expression !== node) && (!(p instanceof AST_Sub) || p.expression !== node) && (!(p instanceof AST_Conditional) || p.condition !== node) && (!(p instanceof AST_Binary) || p.left !== node) && (!(p instanceof AST_UnaryPostfix) || p.expression !== node)) return !1;
node = p;
}
}
def_transform(AST_Node, noop), def_transform(AST_LabeledStatement, function(self1, tw) {
self1.label = self1.label.transform(tw), self1.body = self1.body.transform(tw);
}), def_transform(AST_SimpleStatement, function(self1, tw) {
self1.body = self1.body.transform(tw);
}), def_transform(AST_Block, function(self1, tw) {
self1.body = do_list(self1.body, tw);
}), def_transform(AST_Do, function(self1, tw) {
self1.body = self1.body.transform(tw), self1.condition = self1.condition.transform(tw);
}), def_transform(AST_While, function(self1, tw) {
self1.condition = self1.condition.transform(tw), self1.body = self1.body.transform(tw);
}), def_transform(AST_For, function(self1, tw) {
self1.init && (self1.init = self1.init.transform(tw)), self1.condition && (self1.condition = self1.condition.transform(tw)), self1.step && (self1.step = self1.step.transform(tw)), self1.body = self1.body.transform(tw);
}), def_transform(AST_ForIn, function(self1, tw) {
self1.init = self1.init.transform(tw), self1.object = self1.object.transform(tw), self1.body = self1.body.transform(tw);
}), def_transform(AST_With, function(self1, tw) {
self1.expression = self1.expression.transform(tw), self1.body = self1.body.transform(tw);
}), def_transform(AST_Exit, function(self1, tw) {
self1.value && (self1.value = self1.value.transform(tw));
}), def_transform(AST_LoopControl, function(self1, tw) {
self1.label && (self1.label = self1.label.transform(tw));
}), def_transform(AST_If, function(self1, tw) {
self1.condition = self1.condition.transform(tw), self1.body = self1.body.transform(tw), self1.alternative && (self1.alternative = self1.alternative.transform(tw));
}), def_transform(AST_Switch, function(self1, tw) {
self1.expression = self1.expression.transform(tw), self1.body = do_list(self1.body, tw);
}), def_transform(AST_Case, function(self1, tw) {
self1.expression = self1.expression.transform(tw), self1.body = do_list(self1.body, tw);
}), def_transform(AST_Try, function(self1, tw) {
self1.body = do_list(self1.body, tw), self1.bcatch && (self1.bcatch = self1.bcatch.transform(tw)), self1.bfinally && (self1.bfinally = self1.bfinally.transform(tw));
}), def_transform(AST_Catch, function(self1, tw) {
self1.argname && (self1.argname = self1.argname.transform(tw)), self1.body = do_list(self1.body, tw);
}), def_transform(AST_Definitions, function(self1, tw) {
self1.definitions = do_list(self1.definitions, tw);
}), def_transform(AST_VarDef, function(self1, tw) {
self1.name = self1.name.transform(tw), self1.value && (self1.value = self1.value.transform(tw));
}), def_transform(AST_Destructuring, function(self1, tw) {
self1.names = do_list(self1.names, tw);
}), def_transform(AST_Lambda, function(self1, tw) {
self1.name && (self1.name = self1.name.transform(tw)), self1.argnames = do_list(self1.argnames, tw), self1.body instanceof AST_Node ? self1.body = self1.body.transform(tw) : self1.body = do_list(self1.body, tw);
}), def_transform(AST_Call, function(self1, tw) {
self1.expression = self1.expression.transform(tw), self1.args = do_list(self1.args, tw);
}), def_transform(AST_Sequence, function(self1, tw) {
const result = do_list(self1.expressions, tw);
self1.expressions = result.length ? result : [
new AST_Number({
value: 0
})
];
}), def_transform(AST_PropAccess, function(self1, tw) {
self1.expression = self1.expression.transform(tw);
}), def_transform(AST_Sub, function(self1, tw) {
self1.expression = self1.expression.transform(tw), self1.property = self1.property.transform(tw);
}), def_transform(AST_Chain, function(self1, tw) {
self1.expression = self1.expression.transform(tw);
}), def_transform(AST_Yield, function(self1, tw) {
self1.expression && (self1.expression = self1.expression.transform(tw));
}), def_transform(AST_Await, function(self1, tw) {
self1.expression = self1.expression.transform(tw);
}), def_transform(AST_Unary, function(self1, tw) {
self1.expression = self1.expression.transform(tw);
}), def_transform(AST_Binary, function(self1, tw) {
self1.left = self1.left.transform(tw), self1.right = self1.right.transform(tw);
}), def_transform(AST_Conditional, function(self1, tw) {
self1.condition = self1.condition.transform(tw), self1.consequent = self1.consequent.transform(tw), self1.alternative = self1.alternative.transform(tw);
}), def_transform(AST_Array, function(self1, tw) {
self1.elements = do_list(self1.elements, tw);
}), def_transform(AST_Object, function(self1, tw) {
self1.properties = do_list(self1.properties, tw);
}), def_transform(AST_ObjectProperty, function(self1, tw) {
self1.key instanceof AST_Node && (self1.key = self1.key.transform(tw)), self1.value && (self1.value = self1.value.transform(tw));
}), def_transform(AST_Class, function(self1, tw) {
self1.name && (self1.name = self1.name.transform(tw)), self1.extends && (self1.extends = self1.extends.transform(tw)), self1.properties = do_list(self1.properties, tw);
}), def_transform(AST_Expansion, function(self1, tw) {
self1.expression = self1.expression.transform(tw);
}), def_transform(AST_NameMapping, function(self1, tw) {
self1.foreign_name = self1.foreign_name.transform(tw), self1.name = self1.name.transform(tw);
}), def_transform(AST_Import, function(self1, tw) {
self1.imported_name && (self1.imported_name = self1.imported_name.transform(tw)), self1.imported_names && do_list(self1.imported_names, tw), self1.module_name = self1.module_name.transform(tw);
}), def_transform(AST_Export, function(self1, tw) {
self1.exported_definition && (self1.exported_definition = self1.exported_definition.transform(tw)), self1.exported_value && (self1.exported_value = self1.exported_value.transform(tw)), self1.exported_names && do_list(self1.exported_names, tw), self1.module_name && (self1.module_name = self1.module_name.transform(tw));
}), def_transform(AST_TemplateString, function(self1, tw) {
self1.segments = do_list(self1.segments, tw);
}), def_transform(AST_PrefixedTemplateString, function(self1, tw) {
self1.prefix = self1.prefix.transform(tw), self1.template_string = self1.template_string.transform(tw);
}), /***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
***********************************************************************/ function() {
var normalize_directives = function(body) {
for(var in_directive = !0, i = 0; i < body.length; i++)in_directive && body[i] instanceof AST_Statement && body[i].body instanceof AST_String ? body[i] = new AST_Directive({
start: body[i].start,
end: body[i].end,
value: body[i].body.value
}) : in_directive && !(body[i] instanceof AST_Statement && body[i].body instanceof AST_String) && (in_directive = !1);
return body;
};
const assert_clause_from_moz = (assertions)=>assertions && assertions.length > 0 ? new AST_Object({
start: my_start_token(assertions),
end: my_end_token(assertions),
properties: assertions.map((assertion_kv)=>new AST_ObjectKeyVal({
start: my_start_token(assertion_kv),
end: my_end_token(assertion_kv),
key: assertion_kv.key.name || assertion_kv.key.value,
value: from_moz(assertion_kv.value)
}))
}) : null;
var MOZ_TO_ME = {
Program: function(M) {
return new AST_Toplevel({
start: my_start_token(M),
end: my_end_token(M),
body: normalize_directives(M.body.map(from_moz))
});
},
ArrayPattern: function(M) {
return new AST_Destructuring({
start: my_start_token(M),
end: my_end_token(M),
names: M.elements.map(function(elm) {
return null === elm ? new AST_Hole() : from_moz(elm);
}),
is_array: !0
});
},
ObjectPattern: function(M) {
return new AST_Destructuring({
start: my_start_token(M),
end: my_end_token(M),
names: M.properties.map(from_moz),
is_array: !1
});
},
AssignmentPattern: function(M) {
return new AST_DefaultAssign({
start: my_start_token(M),
end: my_end_token(M),
left: from_moz(M.left),
operator: "=",
right: from_moz(M.right)
});
},
SpreadElement: function(M) {
return new AST_Expansion({
start: my_start_token(M),
end: my_end_token(M),
expression: from_moz(M.argument)
});
},
RestElement: function(M) {
return new AST_Expansion({
start: my_start_token(M),
end: my_end_token(M),
expression: from_moz(M.argument)
});
},
TemplateElement: function(M) {
return new AST_TemplateSegment({
start: my_start_token(M),
end: my_end_token(M),
value: M.value.cooked,
raw: M.value.raw
});
},
TemplateLiteral: function(M) {
for(var segments = [], i = 0; i < M.quasis.length; i++)segments.push(from_moz(M.quasis[i])), M.expressions[i] && segments.push(from_moz(M.expressions[i]));
return new AST_TemplateString({
start: my_start_token(M),
end: my_end_token(M),
segments: segments
});
},
TaggedTemplateExpression: function(M) {
return new AST_PrefixedTemplateString({
start: my_start_token(M),
end: my_end_token(M),
template_string: from_moz(M.quasi),
prefix: from_moz(M.tag)
});
},
FunctionDeclaration: function(M) {
return new AST_Defun({
start: my_start_token(M),
end: my_end_token(M),
name: from_moz(M.id),
argnames: M.params.map(from_moz),
is_generator: M.generator,
async: M.async,
body: normalize_directives(from_moz(M.body).body)
});
},
FunctionExpression: function(M) {
return new AST_Function({
start: my_start_token(M),
end: my_end_token(M),
name: from_moz(M.id),
argnames: M.params.map(from_moz),
is_generator: M.generator,
async: M.async,
body: normalize_directives(from_moz(M.body).body)
});
},
ArrowFunctionExpression: function(M) {
const body = "BlockStatement" === M.body.type ? from_moz(M.body).body : [
make_node(AST_Return, {}, {
value: from_moz(M.body)
})
];
return new AST_Arrow({
start: my_start_token(M),
end: my_end_token(M),
argnames: M.params.map(from_moz),
body,
async: M.async
});
},
ExpressionStatement: function(M) {
return new AST_SimpleStatement({
start: my_start_token(M),
end: my_end_token(M),
body: from_moz(M.expression)
});
},
TryStatement: function(M) {
var handlers = M.handlers || [
M.handler
];
if (handlers.length > 1 || M.guardedHandlers && M.guardedHandlers.length) throw Error("Multiple catch clauses are not supported.");
return new AST_Try({
start: my_start_token(M),
end: my_end_token(M),
body: from_moz(M.block).body,
bcatch: from_moz(handlers[0]),
bfinally: M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null
});
},
Property: function(M) {
var key = M.key, args = {
start: my_start_token(key || M.value),
end: my_end_token(M.value),
key: "Identifier" == key.type ? key.name : key.value,
value: from_moz(M.value)
};
return (M.computed && (args.key = from_moz(M.key)), M.method) ? (args.is_generator = M.value.generator, args.async = M.value.async, M.computed ? args.key = from_moz(M.key) : args.key = new AST_SymbolMethod({
name: args.key
}), new AST_ConciseMethod(args)) : "init" == M.kind ? ("Identifier" != key.type && "Literal" != key.type && (args.key = from_moz(key)), new AST_ObjectKeyVal(args)) : (("string" == typeof args.key || "number" == typeof args.key) && (args.key = new AST_SymbolMethod({
name: args.key
})), args.value = new AST_Accessor(args.value), "get" == M.kind) ? new AST_ObjectGetter(args) : "set" == M.kind ? new AST_ObjectSetter(args) : "method" == M.kind ? (args.async = M.value.async, args.is_generator = M.value.generator, args.quote = M.computed ? "\"" : null, new AST_ConciseMethod(args)) : void 0;
},
MethodDefinition: function(M) {
var args = {
start: my_start_token(M),
end: my_end_token(M),
key: M.computed ? from_moz(M.key) : new AST_SymbolMethod({
name: M.key.name || M.key.value
}),
value: from_moz(M.value),
static: M.static
};
return "get" == M.kind ? new AST_ObjectGetter(args) : "set" == M.kind ? new AST_ObjectSetter(args) : (args.is_generator = M.value.generator, args.async = M.value.async, new AST_ConciseMethod(args));
},
FieldDefinition: function(M) {
let key;
if (M.computed) key = from_moz(M.key);
else {
if ("Identifier" !== M.key.type) throw Error("Non-Identifier key in FieldDefinition");
key = from_moz(M.key);
}
return new AST_ClassProperty({
start: my_start_token(M),
end: my_end_token(M),
key,
value: from_moz(M.value),
static: M.static
});
},
PropertyDefinition: function(M) {
let key;
if (M.computed) key = from_moz(M.key);
else {
if ("Identifier" !== M.key.type) throw Error("Non-Identifier key in PropertyDefinition");
key = from_moz(M.key);
}
return new AST_ClassProperty({
start: my_start_token(M),
end: my_end_token(M),
key,
value: from_moz(M.value),
static: M.static
});
},
ArrayExpression: function(M) {
return new AST_Array({
start: my_start_token(M),
end: my_end_token(M),
elements: M.elements.map(function(elem) {
return null === elem ? new AST_Hole() : from_moz(elem);
})
});
},
ObjectExpression: function(M) {
return new AST_Object({
start: my_start_token(M),
end: my_end_token(M),
properties: M.properties.map(function(prop) {
return "SpreadElement" === prop.type || (prop.type = "Property"), from_moz(prop);
})
});
},
SequenceExpression: function(M) {
return new AST_Sequence({
start: my_start_token(M),
end: my_end_token(M),
expressions: M.expressions.map(from_moz)
});
},
MemberExpression: function(M) {
return new (M.computed ? AST_Sub : AST_Dot)({
start: my_start_token(M),
end: my_end_token(M),
property: M.computed ? from_moz(M.property) : M.property.name,
expression: from_moz(M.object),
optional: M.optional || !1
});
},
ChainExpression: function(M) {
return new AST_Chain({
start: my_start_token(M),
end: my_end_token(M),
expression: from_moz(M.expression)
});
},
SwitchCase: function(M) {
return new (M.test ? AST_Case : AST_Default)({
start: my_start_token(M),
end: my_end_token(M),
expression: from_moz(M.test),
body: M.consequent.map(from_moz)
});
},
VariableDeclaration: function(M) {
return new ("const" === M.kind ? AST_Const : "let" === M.kind ? AST_Let : AST_Var)({
start: my_start_token(M),
end: my_end_token(M),
definitions: M.declarations.map(from_moz)
});
},
ImportDeclaration: function(M) {
var imported_name = null, imported_names = null;
return M.specifiers.forEach(function(specifier) {
"ImportSpecifier" === specifier.type ? (imported_names || (imported_names = []), imported_names.push(new AST_NameMapping({
start: my_start_token(specifier),
end: my_end_token(specifier),
foreign_name: from_moz(specifier.imported),
name: from_moz(specifier.local)
}))) : "ImportDefaultSpecifier" === specifier.type ? imported_name = from_moz(specifier.local) : "ImportNamespaceSpecifier" === specifier.type && (imported_names || (imported_names = []), imported_names.push(new AST_NameMapping({
start: my_start_token(specifier),
end: my_end_token(specifier),
foreign_name: new AST_SymbolImportForeign({
name: "*"
}),
name: from_moz(specifier.local)
})));
}), new AST_Import({
start: my_start_token(M),
end: my_end_token(M),
imported_name: imported_name,
imported_names: imported_names,
module_name: from_moz(M.source),
assert_clause: assert_clause_from_moz(M.assertions)
});
},
ExportAllDeclaration: function(M) {
return new AST_Export({
start: my_start_token(M),
end: my_end_token(M),
exported_names: [
new AST_NameMapping({
name: new AST_SymbolExportForeign({
name: "*"
}),
foreign_name: new AST_SymbolExportForeign({
name: "*"
})
})
],
module_name: from_moz(M.source),
assert_clause: assert_clause_from_moz(M.assertions)
});
},
ExportNamedDeclaration: function(M) {
return new AST_Export({
start: my_start_token(M),
end: my_end_token(M),
exported_definition: from_moz(M.declaration),
exported_names: M.specifiers && M.specifiers.length ? M.specifiers.map(function(specifier) {
return new AST_NameMapping({
foreign_name: from_moz(specifier.exported),
name: from_moz(specifier.local)
});
}) : null,
module_name: from_moz(M.source),
assert_clause: assert_clause_from_moz(M.assertions)
});
},
ExportDefaultDeclaration: function(M) {
return new AST_Export({
start: my_start_token(M),
end: my_end_token(M),
exported_value: from_moz(M.declaration),
is_default: !0
});
},
Literal: function(M) {
var val = M.value, args = {
start: my_start_token(M),
end: my_end_token(M)
}, rx = M.regex;
if (rx && rx.pattern) return(// RegExpLiteral as per ESTree AST spec
args.value = {
source: rx.pattern,
flags: rx.flags
}, new AST_RegExp(args));
if (rx) {
// support legacy RegExp
const rx_source = M.raw || val, match = rx_source.match(/^\/(.*)\/(\w*)$/);
if (!match) throw Error("Invalid regex source " + rx_source);
const [_, source, flags] = match;
return args.value = {
source,
flags
}, new AST_RegExp(args);
}
if (null === val) return new AST_Null(args);
switch(typeof val){
case "string":
return args.value = val, new AST_String(args);
case "number":
return args.value = val, args.raw = M.raw || val.toString(), new AST_Number(args);
case "boolean":
return new (val ? AST_True : AST_False)(args);
}
},
MetaProperty: function(M) {
return "new" === M.meta.name && "target" === M.property.name ? new AST_NewTarget({
start: my_start_token(M),
end: my_end_token(M)
}) : "import" === M.meta.name && "meta" === M.property.name ? new AST_ImportMeta({
start: my_start_token(M),
end: my_end_token(M)
}) : void 0;
},
Identifier: function(M) {
var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2];
return new ("LabeledStatement" == p.type ? AST_Label : "VariableDeclarator" == p.type && p.id === M ? "const" == p.kind ? AST_SymbolConst : "let" == p.kind ? AST_SymbolLet : AST_SymbolVar : /Import.*Specifier/.test(p.type) ? p.local === M ? AST_SymbolImport : AST_SymbolImportForeign : "ExportSpecifier" == p.type ? p.local === M ? AST_SymbolExport : AST_SymbolExportForeign : "FunctionExpression" == p.type ? p.id === M ? AST_SymbolLambda : AST_SymbolFunarg : "FunctionDeclaration" == p.type ? p.id === M ? AST_SymbolDefun : AST_SymbolFunarg : "ArrowFunctionExpression" == p.type ? p.params.includes(M) ? AST_SymbolFunarg : AST_SymbolRef : "ClassExpression" == p.type ? p.id === M ? AST_SymbolClass : AST_SymbolRef : "Property" == p.type ? p.key === M && p.computed || p.value === M ? AST_SymbolRef : AST_SymbolMethod : "PropertyDefinition" == p.type || "FieldDefinition" === p.type ? p.key === M && p.computed || p.value === M ? AST_SymbolRef : AST_SymbolClassProperty : "ClassDeclaration" == p.type ? p.id === M ? AST_SymbolDefClass : AST_SymbolRef : "MethodDefinition" == p.type ? p.computed ? AST_SymbolRef : AST_SymbolMethod : "CatchClause" == p.type ? AST_SymbolCatch : "BreakStatement" == p.type || "ContinueStatement" == p.type ? AST_LabelRef : AST_SymbolRef)({
start: my_start_token(M),
end: my_end_token(M),
name: M.name
});
},
BigIntLiteral: (M)=>new AST_BigInt({
start: my_start_token(M),
end: my_end_token(M),
value: M.value
})
};
MOZ_TO_ME.UpdateExpression = MOZ_TO_ME.UnaryExpression = function(M) {
return new (("prefix" in M ? M.prefix : "UnaryExpression" == M.type) ? AST_UnaryPrefix : AST_UnaryPostfix)({
start: my_start_token(M),
end: my_end_token(M),
operator: M.operator,
expression: from_moz(M.argument)
});
}, MOZ_TO_ME.ClassDeclaration = MOZ_TO_ME.ClassExpression = function(M) {
return new ("ClassDeclaration" === M.type ? AST_DefClass : AST_ClassExpression)({
start: my_start_token(M),
end: my_end_token(M),
name: from_moz(M.id),
extends: from_moz(M.superClass),
properties: M.body.body.map(from_moz)
});
}, map("EmptyStatement", AST_EmptyStatement), map("BlockStatement", AST_BlockStatement, "body@body"), map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative"), map("LabeledStatement", AST_LabeledStatement, "label>label, body>body"), map("BreakStatement", AST_Break, "label>label"), map("ContinueStatement", AST_Continue, "label>label"), map("WithStatement", AST_With, "object>expression, body>body"), map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body"), map("ReturnStatement", AST_Return, "argument>value"), map("ThrowStatement", AST_Throw, "argument>value"), map("WhileStatement", AST_While, "test>condition, body>body"), map("DoWhileStatement", AST_Do, "test>condition, body>body"), map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body"), map("ForInStatement", AST_ForIn, "left>init, right>object, body>body"), map("ForOfStatement", AST_ForOf, "left>init, right>object, body>body, await=await"), map("AwaitExpression", AST_Await, "argument>expression"), map("YieldExpression", AST_Yield, "argument>expression, delegate=is_star"), map("DebuggerStatement", AST_Debugger), map("VariableDeclarator", AST_VarDef, "id>name, init>value"), map("CatchClause", AST_Catch, "param>argname, body%body"), map("ThisExpression", AST_This), map("Super", AST_Super), map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right"), map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right"), map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right"), map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative"), map("NewExpression", AST_New, "callee>expression, arguments@args"), map("CallExpression", AST_Call, "callee>expression, optional=optional, arguments@args"), def_to_moz(AST_Toplevel, function(M) {
return to_moz_scope("Program", M);
}), def_to_moz(AST_Expansion, function(M) {
return {
type: to_moz_in_destructuring() ? "RestElement" : "SpreadElement",
argument: to_moz(M.expression)
};
}), def_to_moz(AST_PrefixedTemplateString, function(M) {
return {
type: "TaggedTemplateExpression",
tag: to_moz(M.prefix),
quasi: to_moz(M.template_string)
};
}), def_to_moz(AST_TemplateString, function(M) {
for(var quasis = [], expressions = [], i = 0; i < M.segments.length; i++)i % 2 != 0 ? expressions.push(to_moz(M.segments[i])) : quasis.push({
type: "TemplateElement",
value: {
raw: M.segments[i].raw,
cooked: M.segments[i].value
},
tail: i === M.segments.length - 1
});
return {
type: "TemplateLiteral",
quasis: quasis,
expressions: expressions
};
}), def_to_moz(AST_Defun, function(M) {
return {
type: "FunctionDeclaration",
id: to_moz(M.name),
params: M.argnames.map(to_moz),
generator: M.is_generator,
async: M.async,
body: to_moz_scope("BlockStatement", M)
};
}), def_to_moz(AST_Function, function(M, parent) {
var is_generator = void 0 !== parent.is_generator ? parent.is_generator : M.is_generator;
return {
type: "FunctionExpression",
id: to_moz(M.name),
params: M.argnames.map(to_moz),
generator: is_generator,
async: M.async,
body: to_moz_scope("BlockStatement", M)
};
}), def_to_moz(AST_Arrow, function(M) {
var body = {
type: "BlockStatement",
body: M.body.map(to_moz)
};
return {
type: "ArrowFunctionExpression",
params: M.argnames.map(to_moz),
async: M.async,
body: body
};
}), def_to_moz(AST_Destructuring, function(M) {
return M.is_array ? {
type: "ArrayPattern",
elements: M.names.map(to_moz)
} : {
type: "ObjectPattern",
properties: M.names.map(to_moz)
};
}), def_to_moz(AST_Directive, function(M) {
return {
type: "ExpressionStatement",
expression: {
type: "Literal",
value: M.value,
raw: M.print_to_string()
},
directive: M.value
};
}), def_to_moz(AST_SimpleStatement, function(M) {
return {
type: "ExpressionStatement",
expression: to_moz(M.body)
};
}), def_to_moz(AST_SwitchBranch, function(M) {
return {
type: "SwitchCase",
test: to_moz(M.expression),
consequent: M.body.map(to_moz)
};
}), def_to_moz(AST_Try, function(M) {
return {
type: "TryStatement",
block: to_moz_block(M),
handler: to_moz(M.bcatch),
guardedHandlers: [],
finalizer: to_moz(M.bfinally)
};
}), def_to_moz(AST_Catch, function(M) {
return {
type: "CatchClause",
param: to_moz(M.argname),
guard: null,
body: to_moz_block(M)
};
}), def_to_moz(AST_Definitions, function(M) {
return {
type: "VariableDeclaration",
kind: M instanceof AST_Const ? "const" : M instanceof AST_Let ? "let" : "var",
declarations: M.definitions.map(to_moz)
};
});
const assert_clause_to_moz = (assert_clause)=>{
const assertions = [];
if (assert_clause) for (const { key, value } of assert_clause.properties){
const key_moz = is_basic_identifier_string(key) ? {
type: "Identifier",
name: key
} : {
type: "Literal",
value: key,
raw: JSON.stringify(key)
};
assertions.push({
type: "ImportAttribute",
key: key_moz,
value: to_moz(value)
});
}
return assertions;
};
/* -----[ tools ]----- */ function my_start_token(moznode) {
var loc = moznode.loc, start = loc && loc.start, range = moznode.range;
return new AST_Token("", "", start && start.line || 0, start && start.column || 0, range ? range[0] : moznode.start, !1, [], [], loc && loc.source);
}
function my_end_token(moznode) {
var loc = moznode.loc, end = loc && loc.end, range = moznode.range;
return new AST_Token("", "", end && end.line || 0, end && end.column || 0, range ? range[0] : moznode.end, !1, [], [], loc && loc.source);
}
function map(moztype, mytype, propmap) {
var moz_to_me = "function From_Moz_" + moztype + "(M){\n";
moz_to_me += "return new U2." + mytype.name + "({\nstart: my_start_token(M),\nend: my_end_token(M)";
var me_to_moz = "function To_Moz_" + moztype + "(M){\n";
me_to_moz += "return {\ntype: " + JSON.stringify(moztype), propmap && propmap.split(/\s*,\s*/).forEach(function(prop) {
var m = /([a-z0-9$_]+)([=@>%])([a-z0-9$_]+)/i.exec(prop);
if (!m) throw Error("Can't understand property map: " + prop);
var moz = m[1], how = m[2], my = m[3];
switch(moz_to_me += ",\n" + my + ": ", me_to_moz += ",\n" + moz + ": ", how){
case "@":
moz_to_me += "M." + moz + ".map(from_moz)", me_to_moz += "M." + my + ".map(to_moz)";
break;
case ">":
moz_to_me += "from_moz(M." + moz + ")", me_to_moz += "to_moz(M." + my + ")";
break;
case "=":
moz_to_me += "M." + moz, me_to_moz += "M." + my;
break;
case "%":
moz_to_me += "from_moz(M." + moz + ").body", me_to_moz += "to_moz_block(M)";
break;
default:
throw Error("Can't understand operator in propmap: " + prop);
}
}), moz_to_me += "\n})\n}", me_to_moz += "\n}\n}", moz_to_me = Function("U2", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")(ast, my_start_token, my_end_token, from_moz), me_to_moz = Function("to_moz", "to_moz_block", "to_moz_scope", "return(" + me_to_moz + ")")(to_moz, to_moz_block, to_moz_scope), MOZ_TO_ME[moztype] = moz_to_me, def_to_moz(mytype, me_to_moz);
}
def_to_moz(AST_Export, function(M) {
return M.exported_names ? "*" === M.exported_names[0].name.name ? {
type: "ExportAllDeclaration",
source: to_moz(M.module_name),
assertions: assert_clause_to_moz(M.assert_clause)
} : {
type: "ExportNamedDeclaration",
specifiers: M.exported_names.map(function(name_mapping) {
return {
type: "ExportSpecifier",
exported: to_moz(name_mapping.foreign_name),
local: to_moz(name_mapping.name)
};
}),
declaration: to_moz(M.exported_definition),
source: to_moz(M.module_name),
assertions: assert_clause_to_moz(M.assert_clause)
} : {
type: M.is_default ? "ExportDefaultDeclaration" : "ExportNamedDeclaration",
declaration: to_moz(M.exported_value || M.exported_definition)
};
}), def_to_moz(AST_Import, function(M) {
var specifiers = [];
return M.imported_name && specifiers.push({
type: "ImportDefaultSpecifier",
local: to_moz(M.imported_name)
}), M.imported_names && "*" === M.imported_names[0].foreign_name.name ? specifiers.push({
type: "ImportNamespaceSpecifier",
local: to_moz(M.imported_names[0].name)
}) : M.imported_names && M.imported_names.forEach(function(name_mapping) {
specifiers.push({
type: "ImportSpecifier",
local: to_moz(name_mapping.name),
imported: to_moz(name_mapping.foreign_name)
});
}), {
type: "ImportDeclaration",
specifiers: specifiers,
source: to_moz(M.module_name),
assertions: assert_clause_to_moz(M.assert_clause)
};
}), def_to_moz(AST_ImportMeta, function() {
return {
type: "MetaProperty",
meta: {
type: "Identifier",
name: "import"
},
property: {
type: "Identifier",
name: "meta"
}
};
}), def_to_moz(AST_Sequence, function(M) {
return {
type: "SequenceExpression",
expressions: M.expressions.map(to_moz)
};
}), def_to_moz(AST_DotHash, function(M) {
return {
type: "MemberExpression",
object: to_moz(M.expression),
computed: !1,
property: {
type: "PrivateIdentifier",
name: M.property
},
optional: M.optional
};
}), def_to_moz(AST_PropAccess, function(M) {
var isComputed = M instanceof AST_Sub;
return {
type: "MemberExpression",
object: to_moz(M.expression),
computed: isComputed,
property: isComputed ? to_moz(M.property) : {
type: "Identifier",
name: M.property
},
optional: M.optional
};
}), def_to_moz(AST_Chain, function(M) {
return {
type: "ChainExpression",
expression: to_moz(M.expression)
};
}), def_to_moz(AST_Unary, function(M) {
return {
type: "++" == M.operator || "--" == M.operator ? "UpdateExpression" : "UnaryExpression",
operator: M.operator,
prefix: M instanceof AST_UnaryPrefix,
argument: to_moz(M.expression)
};
}), def_to_moz(AST_Binary, function(M) {
return "=" == M.operator && to_moz_in_destructuring() ? {
type: "AssignmentPattern",
left: to_moz(M.left),
right: to_moz(M.right)
} : {
type: "&&" == M.operator || "||" == M.operator || "??" === M.operator ? "LogicalExpression" : "BinaryExpression",
left: to_moz(M.left),
operator: M.operator,
right: to_moz(M.right)
};
}), def_to_moz(AST_Array, function(M) {
return {
type: "ArrayExpression",
elements: M.elements.map(to_moz)
};
}), def_to_moz(AST_Object, function(M) {
return {
type: "ObjectExpression",
properties: M.properties.map(to_moz)
};
}), def_to_moz(AST_ObjectProperty, function(M, parent) {
var kind, key = M.key instanceof AST_Node ? to_moz(M.key) : {
type: "Identifier",
value: M.key
};
"number" == typeof M.key && (key = {
type: "Literal",
value: Number(M.key)
}), "string" == typeof M.key && (key = {
type: "Identifier",
name: M.key
});
var string_or_num = "string" == typeof M.key || "number" == typeof M.key, computed = !string_or_num && (!(M.key instanceof AST_Symbol) || M.key instanceof AST_SymbolRef);
return (M instanceof AST_ObjectKeyVal ? (kind = "init", computed = !string_or_num) : M instanceof AST_ObjectGetter ? kind = "get" : M instanceof AST_ObjectSetter && (kind = "set"), M instanceof AST_PrivateGetter || M instanceof AST_PrivateSetter) ? {
type: "MethodDefinition",
computed: !1,
kind: M instanceof AST_PrivateGetter ? "get" : "set",
static: M.static,
key: {
type: "PrivateIdentifier",
name: M.key.name
},
value: to_moz(M.value)
} : M instanceof AST_ClassPrivateProperty ? {
type: "PropertyDefinition",
key: {
type: "PrivateIdentifier",
name: M.key.name
},
value: to_moz(M.value),
computed: !1,
static: M.static
} : M instanceof AST_ClassProperty ? {
type: "PropertyDefinition",
key,
value: to_moz(M.value),
computed,
static: M.static
} : parent instanceof AST_Class ? {
type: "MethodDefinition",
computed: computed,
kind: kind,
static: M.static,
key: to_moz(M.key),
value: to_moz(M.value)
} : {
type: "Property",
computed: computed,
kind: kind,
key: key,
value: to_moz(M.value)
};
}), def_to_moz(AST_ConciseMethod, function(M, parent) {
if (parent instanceof AST_Object) return {
type: "Property",
computed: !(M.key instanceof AST_Symbol) || M.key instanceof AST_SymbolRef,
kind: "init",
method: !0,
shorthand: !1,
key: to_moz(M.key),
value: to_moz(M.value)
};
const key = M instanceof AST_PrivateMethod ? {
type: "PrivateIdentifier",
name: M.key.name
} : to_moz(M.key);
return {
type: "MethodDefinition",
kind: "constructor" === M.key ? "constructor" : "method",
key,
value: to_moz(M.value),
computed: !(M.key instanceof AST_Symbol) || M.key instanceof AST_SymbolRef,
static: M.static
};
}), def_to_moz(AST_Class, function(M) {
return {
type: M instanceof AST_ClassExpression ? "ClassExpression" : "ClassDeclaration",
superClass: to_moz(M.extends),
id: M.name ? to_moz(M.name) : null,
body: {
type: "ClassBody",
body: M.properties.map(to_moz)
}
};
}), def_to_moz(AST_NewTarget, function() {
return {
type: "MetaProperty",
meta: {
type: "Identifier",
name: "new"
},
property: {
type: "Identifier",
name: "target"
}
};
}), def_to_moz(AST_Symbol, function(M, parent) {
if (M instanceof AST_SymbolMethod && parent.quote) return {
type: "Literal",
value: M.name
};
var def = M.definition();
return {
type: "Identifier",
name: def ? def.mangled_name || def.name : M.name
};
}), def_to_moz(AST_RegExp, function(M) {
const pattern = M.value.source, flags = M.value.flags;
return {
type: "Literal",
value: null,
raw: M.print_to_string(),
regex: {
pattern,
flags
}
};
}), def_to_moz(AST_Constant, function(M) {
return {
type: "Literal",
value: M.value,
raw: M.raw || M.print_to_string()
};
}), def_to_moz(AST_Atom, function(M) {
return {
type: "Identifier",
name: String(M.value)
};
}), def_to_moz(AST_BigInt, (M)=>({
type: "BigIntLiteral",
value: M.value
})), AST_Boolean.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast), AST_Null.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast), AST_Hole.DEFMETHOD("to_mozilla_ast", function() {
return null;
}), AST_Block.DEFMETHOD("to_mozilla_ast", AST_BlockStatement.prototype.to_mozilla_ast), AST_Lambda.DEFMETHOD("to_mozilla_ast", AST_Function.prototype.to_mozilla_ast);
var FROM_MOZ_STACK = null;
function from_moz(node) {
FROM_MOZ_STACK.push(node);
var ret = null != node ? MOZ_TO_ME[node.type](node) : null;
return FROM_MOZ_STACK.pop(), ret;
}
function def_to_moz(mytype, handler) {
mytype.DEFMETHOD("to_mozilla_ast", function(parent) {
var moznode, start, end;
return moznode = handler(this, parent), start = this.start, end = this.end, start && end && (null != start.pos && null != end.endpos && (moznode.range = [
start.pos,
end.endpos
]), start.line && (moznode.loc = {
start: {
line: start.line,
column: start.col
},
end: end.endline ? {
line: end.endline,
column: end.endcol
} : null
}, start.file && (moznode.loc.source = start.file))), moznode;
});
}
AST_Node.from_mozilla_ast = function(node) {
var save_stack = FROM_MOZ_STACK;
FROM_MOZ_STACK = [];
var ast = from_moz(node);
return FROM_MOZ_STACK = save_stack, ast;
};
var TO_MOZ_STACK = null;
function to_moz(node) {
null === TO_MOZ_STACK && (TO_MOZ_STACK = []), TO_MOZ_STACK.push(node);
var ast = null != node ? node.to_mozilla_ast(TO_MOZ_STACK[TO_MOZ_STACK.length - 2]) : null;
return TO_MOZ_STACK.pop(), 0 === TO_MOZ_STACK.length && (TO_MOZ_STACK = null), ast;
}
function to_moz_in_destructuring() {
for(var i = TO_MOZ_STACK.length; i--;)if (TO_MOZ_STACK[i] instanceof AST_Destructuring) return !0;
return !1;
}
function to_moz_block(node) {
return {
type: "BlockStatement",
body: node.body.map(to_moz)
};
}
function to_moz_scope(type, node) {
var body = node.body.map(to_moz);
return node.body[0] instanceof AST_SimpleStatement && node.body[0].body instanceof AST_String && body.unshift(to_moz(new AST_EmptyStatement(node.body[0]))), {
type: type,
body: body
};
}
}();
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
***********************************************************************/ const EXPECT_DIRECTIVE = /^$|[;{][\s\n]*$/, r_annotation = /[@#]__(PURE|INLINE|NOINLINE)__/g;
function is_some_comments(comment) {
// multiline comment
return ("comment2" === comment.type || "comment1" === comment.type) && /@preserve|@copyright|@lic|@cc_on|^\**!/i.test(comment.value);
}
class Rope {
constructor(){
this.committed = "", this.current = "";
}
append(str) {
this.current += str;
}
insertAt(char, index) {
const { committed, current } = this;
index < committed.length ? this.committed = committed.slice(0, index) + char + committed.slice(index) : index === committed.length ? this.committed += char : (index -= committed.length, this.committed += current.slice(0, index) + char, this.current = current.slice(index));
}
charAt(index) {
const { committed } = this;
return index < committed.length ? committed[index] : this.current[index - committed.length];
}
curLength() {
return this.current.length;
}
length() {
return this.committed.length + this.current.length;
}
toString() {
return this.committed + this.current;
}
}
function OutputStream(options) {
var readonly = !options;
void 0 === (options = defaults(options, {
ascii_only: !1,
beautify: !1,
braces: !1,
comments: "some",
ecma: 5,
ie8: !1,
indent_level: 4,
indent_start: 0,
inline_script: !0,
keep_numbers: !1,
keep_quoted_props: !1,
max_line_len: !1,
preamble: null,
preserve_annotations: !1,
quote_keys: !1,
quote_style: 0,
safari10: !1,
semicolons: !0,
shebang: !0,
shorthand: void 0,
source_map: null,
webkit: !1,
width: 80,
wrap_iife: !1,
wrap_func_args: !0
}, !0)).shorthand && (options.shorthand = options.ecma > 5);
// Convert comment option to RegExp if neccessary and set up comments filter
var comment_filter = return_false; // Default case, throw all comments away
if (options.comments) {
let comments = options.comments;
if ("string" == typeof options.comments && /^\/.*\/[a-zA-Z]*$/.test(options.comments)) {
var regex_pos = options.comments.lastIndexOf("/");
comments = new RegExp(options.comments.substr(1, regex_pos - 1), options.comments.substr(regex_pos + 1));
}
comment_filter = comments instanceof RegExp ? function(comment) {
return "comment5" != comment.type && comments.test(comment.value);
} : "function" == typeof comments ? function(comment) {
return "comment5" != comment.type && comments(this, comment);
} : "some" === comments ? is_some_comments : return_true;
}
var indentation = 0, current_col = 0, current_line = 1, current_pos = 0, OUTPUT = new Rope();
let printed_comments = new Set();
var to_utf8 = options.ascii_only ? function(str, identifier = !1, regexp = !1) {
return !(options.ecma >= 2015) || options.safari10 || regexp || (str = str.replace(/[\ud800-\udbff][\udc00-\udfff]/g, function(ch) {
return "\\u{" + (is_surrogate_pair_head(ch.charCodeAt(0)) ? 0x10000 + (ch.charCodeAt(0) - 0xd800 << 10) + ch.charCodeAt(1) - 0xdc00 : ch.charCodeAt(0)).toString(16) + "}";
})), str.replace(/[\u0000-\u001f\u007f-\uffff]/g, function(ch) {
var code = ch.charCodeAt(0).toString(16);
if (code.length <= 2 && !identifier) {
for(; code.length < 2;)code = "0" + code;
return "\\x" + code;
}
for(; code.length < 4;)code = "0" + code;
return "\\u" + code;
});
} : function(str) {
return str.replace(/[\ud800-\udbff][\udc00-\udfff]|([\ud800-\udbff]|[\udc00-\udfff])/g, function(match, lone) {
return lone ? "\\u" + lone.charCodeAt(0).toString(16) : match;
});
};
function encode_string(str, quote) {
var ret = function(str, quote) {
var dq = 0, sq = 0;
function quote_single() {
return "'" + str.replace(/\x27/g, "\\'") + "'";
}
function quote_double() {
return '"' + str.replace(/\x22/g, '\\"') + '"';
}
if (str = to_utf8(str = str.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g, function(s, i) {
switch(s){
case '"':
return ++dq, '"';
case "'":
return ++sq, "'";
case "\\":
return "\\\\";
case "\n":
return "\\n";
case "\r":
return "\\r";
case "\t":
return "\\t";
case "\b":
return "\\b";
case "\f":
return "\\f";
case "\x0B":
return options.ie8 ? "\\x0B" : "\\v";
case "\u2028":
return "\\u2028";
case "\u2029":
return "\\u2029";
case "\ufeff":
return "\\ufeff";
case "\0":
return /[0-9]/.test(get_full_char(str, i + 1)) ? "\\x00" : "\\0";
}
return s;
})), "`" === quote) return "`" + str.replace(/`/g, "\\`") + "`";
switch(options.quote_style){
case 1:
return quote_single();
case 2:
return quote_double();
case 3:
return "'" == quote ? quote_single() : quote_double();
default:
return dq > sq ? quote_single() : quote_double();
}
}(str, quote);
return options.inline_script && (ret = (ret = (ret = ret.replace(/<\x2f(script)([>\/\t\n\f\r ])/gi, "<\\/$1$2")).replace(/\x3c!--/g, "\\x3c!--")).replace(/--\x3e/g, "--\\x3e")), ret;
}
/* -----[ beautification/minification ]----- */ var mapping_token, mapping_name, has_parens = !1, might_need_space = !1, might_need_semicolon = !1, might_add_newline = 0, need_newline_indented = !1, need_space = !1, newline_insert = -1, last = "", mappings = options.source_map && [], do_add_mapping = mappings ? function() {
mappings.forEach(function(mapping) {
try {
let { name, token } = mapping;
"name" == token.type || "privatename" === token.type ? name = token.value : name instanceof AST_Symbol && (name = "string" === token.type ? token.value : name.name), options.source_map.add(mapping.token.file, mapping.line, mapping.col, mapping.token.line, mapping.token.col, is_basic_identifier_string(name) ? name : void 0);
} catch (ex) {
// Ignore bad mapping
}
}), mappings = [];
} : noop, ensure_line_len = options.max_line_len ? function() {
if (current_col > options.max_line_len && might_add_newline) {
OUTPUT.insertAt("\n", might_add_newline);
const curLength = OUTPUT.curLength();
if (mappings) {
var delta = curLength - current_col;
mappings.forEach(function(mapping) {
mapping.line++, mapping.col += delta;
});
}
current_line++, current_pos++, current_col = curLength;
}
might_add_newline && (might_add_newline = 0, do_add_mapping());
} : noop, requireSemicolonChars = makePredicate("( [ + * / - , . `");
function print(str) {
var ch = get_full_char(str = String(str), 0);
need_newline_indented && ch && (need_newline_indented = !1, "\n" !== ch && (print("\n"), indent())), need_space && ch && (need_space = !1, /[\s;})]/.test(ch) || space()), newline_insert = -1;
var prev = last.charAt(last.length - 1);
!might_need_semicolon || (might_need_semicolon = !1, (":" !== prev || "}" !== ch) && (ch && ";}".includes(ch) || ";" === prev) || (options.semicolons || requireSemicolonChars.has(ch) ? (OUTPUT.append(";"), current_col++, current_pos++) : (ensure_line_len(), current_col > 0 && (OUTPUT.append("\n"), current_pos++, current_line++, current_col = 0), /^\s+$/.test(str) && // reset the semicolon flag, since we didn't print one
// now and might still have to later
(might_need_semicolon = !0)), options.beautify || (might_need_space = !1))), might_need_space && ((is_identifier_char(prev) && (is_identifier_char(ch) || "\\" == ch) || "/" == ch && ch == prev || ("+" == ch || "-" == ch) && ch == last) && (OUTPUT.append(" "), current_col++, current_pos++), might_need_space = !1), mapping_token && (mappings.push({
token: mapping_token,
name: mapping_name,
line: current_line,
col: current_col
}), mapping_token = !1, might_add_newline || do_add_mapping()), OUTPUT.append(str), has_parens = "(" == str[str.length - 1], current_pos += str.length;
var a = str.split(/\r?\n/), n = a.length - 1;
current_line += n, current_col += a[0].length, n > 0 && (ensure_line_len(), current_col = a[n].length), last = str;
}
var space = options.beautify ? function() {
print(" ");
} : function() {
might_need_space = !0;
}, indent = options.beautify ? function(half) {
options.beautify && print(" ".repeat(options.indent_start + indentation - 0.5 * !!half * options.indent_level));
} : noop, with_indent = options.beautify ? function(col, cont) {
!0 === col && (col = next_indent());
var save_indentation = indentation;
indentation = col;
var ret = cont();
return indentation = save_indentation, ret;
} : function(col, cont) {
return cont();
}, newline = options.beautify ? function() {
if (newline_insert < 0) return print("\n");
"\n" != OUTPUT.charAt(newline_insert) && (OUTPUT.insertAt("\n", newline_insert), current_pos++, current_line++), newline_insert++;
} : options.max_line_len ? function() {
ensure_line_len(), might_add_newline = OUTPUT.length();
} : noop, semicolon = options.beautify ? function() {
print(";");
} : function() {
might_need_semicolon = !0;
};
function force_semicolon() {
might_need_semicolon = !1, print(";");
}
function next_indent() {
return indentation + options.indent_level;
}
function get() {
return might_add_newline && ensure_line_len(), OUTPUT.toString();
}
function has_nlb() {
const output = OUTPUT.toString();
let n = output.length - 1;
for(; n >= 0;){
const code = output.charCodeAt(n);
if (10 === code) break;
if (32 !== code) return !1;
n--;
}
return !0;
}
function filter_comment(comment) {
return (options.preserve_annotations || (comment = comment.replace(r_annotation, " ")), /^\s*$/.test(comment)) ? "" : comment.replace(/(<\s*\/\s*)(script)/i, "<\\/$2");
}
var stack = [];
return {
get: get,
toString: get,
indent: indent,
in_directive: !1,
use_asm: null,
active_scope: null,
indentation: function() {
return indentation;
},
current_width: function() {
return current_col - indentation;
},
should_break: function() {
return options.width && this.current_width() >= options.width;
},
has_parens: function() {
return has_parens;
},
newline: newline,
print: print,
star: function() {
print("*");
},
space: space,
comma: function() {
print(","), space();
},
colon: function() {
print(":"), space();
},
last: function() {
return last;
},
semicolon: semicolon,
force_semicolon: force_semicolon,
to_utf8: to_utf8,
print_name: function(name) {
print(to_utf8(name.toString(), !0));
},
print_string: function(str, quote, escape_directive) {
var encoded = encode_string(str, quote);
!0 !== escape_directive || encoded.includes("\\") || (EXPECT_DIRECTIVE.test(OUTPUT.toString()) || force_semicolon(), force_semicolon()), print(encoded);
},
print_template_string_chars: function(str) {
var encoded = encode_string(str, "`").replace(/\${/g, "\\${");
return print(encoded.substr(1, encoded.length - 2));
},
encode_string: encode_string,
next_indent: next_indent,
with_indent: with_indent,
with_block: function(cont) {
var ret;
return print("{"), newline(), with_indent(next_indent(), function() {
ret = cont();
}), indent(), print("}"), ret;
},
with_parens: function(cont) {
print("(");
//XXX: still nice to have that for argument lists
//var ret = with_indent(current_col, cont);
var ret = cont();
return print(")"), ret;
},
with_square: function(cont) {
print("[");
//var ret = with_indent(current_col, cont);
var ret = cont();
return print("]"), ret;
},
add_mapping: mappings ? function(token, name) {
mapping_token = token, mapping_name = name;
} : noop,
option: function(opt) {
return options[opt];
},
printed_comments: printed_comments,
prepend_comments: readonly ? noop : function(node) {
var start = node.start;
if (!start) return;
var printed_comments = this.printed_comments;
// There cannot be a newline between return and its value.
const return_with_value = node instanceof AST_Exit && node.value;
if (start.comments_before && printed_comments.has(start.comments_before)) {
if (!return_with_value) return;
start.comments_before = [];
}
var comments = start.comments_before;
if (comments || (comments = start.comments_before = []), printed_comments.add(comments), return_with_value) {
var tw = new TreeWalker(function(node) {
var parent = tw.parent();
if (!(parent instanceof AST_Exit) && (!(parent instanceof AST_Binary) || parent.left !== node) && ("Call" != parent.TYPE || parent.expression !== node) && (!(parent instanceof AST_Conditional) || parent.condition !== node) && (!(parent instanceof AST_Dot) || parent.expression !== node) && (!(parent instanceof AST_Sequence) || parent.expressions[0] !== node) && (!(parent instanceof AST_Sub) || parent.expression !== node) && !(parent instanceof AST_UnaryPostfix)) return !0;
if (node.start) {
var text = node.start.comments_before;
text && !printed_comments.has(text) && (printed_comments.add(text), comments = comments.concat(text));
}
});
tw.push(node), node.value.walk(tw);
}
if (0 == current_pos) {
comments.length > 0 && options.shebang && "comment5" === comments[0].type && !printed_comments.has(comments[0]) && (print("#!" + comments.shift().value + "\n"), indent());
var preamble = options.preamble;
preamble && print(preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g, "\n"));
}
if (0 != (comments = comments.filter(comment_filter, node).filter((c)=>!printed_comments.has(c))).length) {
var last_nlb = has_nlb();
comments.forEach(function(c, i) {
if (printed_comments.add(c), !last_nlb && (c.nlb ? (print("\n"), indent(), last_nlb = !0) : i > 0 && space()), /comment[134]/.test(c.type)) {
var value = filter_comment(c.value);
value && (print("//" + value + "\n"), indent()), last_nlb = !0;
} else if ("comment2" == c.type) {
var value = filter_comment(c.value);
value && print("/*" + value + "*/"), last_nlb = !1;
}
}), last_nlb || (start.nlb ? (print("\n"), indent()) : space());
}
},
append_comments: readonly || comment_filter === return_false ? noop : function(node, tail) {
var token = node.end;
if (token) {
var printed_comments = this.printed_comments, comments = token[tail ? "comments_before" : "comments_after"];
if (!(!comments || printed_comments.has(comments)) && (node instanceof AST_Statement || comments.every((c)=>!/comment[134]/.test(c.type)))) {
printed_comments.add(comments);
var insert = OUTPUT.length();
comments.filter(comment_filter, node).forEach(function(c, i) {
if (!printed_comments.has(c)) {
if (printed_comments.add(c), need_space = !1, need_newline_indented ? (print("\n"), indent(), need_newline_indented = !1) : c.nlb && (i > 0 || !has_nlb()) ? (print("\n"), indent()) : (i > 0 || !tail) && space(), /comment[134]/.test(c.type)) {
const value = filter_comment(c.value);
value && print("//" + value), need_newline_indented = !0;
} else if ("comment2" == c.type) {
const value = filter_comment(c.value);
value && print("/*" + value + "*/"), need_space = !0;
}
}
}), OUTPUT.length() > insert && (newline_insert = insert);
}
}
},
line: function() {
return current_line;
},
col: function() {
return current_col;
},
pos: function() {
return current_pos;
},
push_node: function(node) {
stack.push(node);
},
pop_node: function() {
return stack.pop();
},
parent: function(n) {
return stack[stack.length - 2 - (n || 0)];
}
};
}
!/* -----[ code generators ]----- */ function() {
/* -----[ utils ]----- */ function DEFPRINT(nodetype, generator) {
nodetype.DEFMETHOD("_codegen", generator);
}
/* -----[ PARENTHESES ]----- */ function PARENS(nodetype, func) {
Array.isArray(nodetype) ? nodetype.forEach(function(nodetype) {
PARENS(nodetype, func);
}) : nodetype.DEFMETHOD("needs_parens", func);
}
/* -----[ statements ]----- */ function display_body(body, is_toplevel, output, allow_directives) {
var last = body.length - 1;
output.in_directive = allow_directives, body.forEach(function(stmt, i) {
!0 !== output.in_directive || stmt instanceof AST_Directive || stmt instanceof AST_EmptyStatement || stmt instanceof AST_SimpleStatement && stmt.body instanceof AST_String || (output.in_directive = !1), stmt instanceof AST_EmptyStatement || (output.indent(), stmt.print(output), !(i == last && is_toplevel) && (output.newline(), is_toplevel && output.newline())), !0 === output.in_directive && stmt instanceof AST_SimpleStatement && stmt.body instanceof AST_String && (output.in_directive = !1);
}), output.in_directive = !1;
}
function print_braced_empty(self1, output) {
output.print("{"), output.with_indent(output.next_indent(), function() {
output.append_comments(self1, !0);
}), output.print("}");
}
function print_braced(self1, output, allow_directives) {
self1.body.length > 0 ? output.with_block(function() {
display_body(self1.body, !1, output, allow_directives);
}) : print_braced_empty(self1, output);
}
function parenthesize_for_noin(node, output, noin) {
var parens = !1;
noin && (parens = walk(node, (node)=>// Don't go into scopes -- except arrow functions:
// https://github.com/terser/terser/issues/1019#issuecomment-877642607
node instanceof AST_Scope && !(node instanceof AST_Arrow) || (node instanceof AST_Binary && "in" == node.operator ? walk_abort : void 0))), node.print(output, parens);
}
function print_property_name(key, quote, output) {
return output.option("quote_keys") ? output.print_string(key) : "" + +key == key && key >= 0 ? output.option("keep_numbers") ? output.print(key) : output.print(make_num(key)) : (ALL_RESERVED_WORDS.has(key) ? output.option("ie8") : 2015 > output.option("ecma") || output.option("safari10") ? !is_basic_identifier_string(key) : !is_identifier_string(key, !0)) || quote && output.option("keep_quoted_props") ? output.print_string(key, quote) : output.print_name(key);
}
AST_Node.DEFMETHOD("print", function(output, force_parens) {
var self1 = this, generator = self1._codegen;
function doit() {
output.prepend_comments(self1), self1.add_source_map(output), generator(self1, output), output.append_comments(self1);
}
self1 instanceof AST_Scope ? output.active_scope = self1 : !output.use_asm && self1 instanceof AST_Directive && "use asm" == self1.value && (output.use_asm = output.active_scope), output.push_node(self1), force_parens || self1.needs_parens(output) ? output.with_parens(doit) : doit(), output.pop_node(), self1 === output.use_asm && (output.use_asm = null);
}), AST_Node.DEFMETHOD("_print", AST_Node.prototype.print), AST_Node.DEFMETHOD("print_to_string", function(options) {
var output = OutputStream(options);
return this.print(output), output.get();
}), PARENS(AST_Node, return_false), // a function expression needs parens around it when it's provably
// the first token to appear in a statement.
PARENS(AST_Function, function(output) {
if (!output.has_parens() && first_in_statement(output)) return !0;
if (output.option("webkit")) {
var p = output.parent();
if (p instanceof AST_PropAccess && p.expression === this) return !0;
}
if (output.option("wrap_iife")) {
var p = output.parent();
if (p instanceof AST_Call && p.expression === this) return !0;
}
if (output.option("wrap_func_args")) {
var p = output.parent();
if (p instanceof AST_Call && p.args.includes(this)) return !0;
}
return !1;
}), PARENS(AST_Arrow, function(output) {
var p = output.parent();
return !!(output.option("wrap_func_args") && p instanceof AST_Call && p.args.includes(this)) || p instanceof AST_PropAccess && p.expression === this;
}), // same goes for an object literal (as in AST_Function), because
// otherwise {...} would be interpreted as a block of code.
PARENS(AST_Object, function(output) {
return !output.has_parens() && first_in_statement(output);
}), PARENS(AST_ClassExpression, first_in_statement), PARENS(AST_Unary, function(output) {
var p = output.parent();
return p instanceof AST_PropAccess && p.expression === this || p instanceof AST_Call && p.expression === this || p instanceof AST_Binary && "**" === p.operator && this instanceof AST_UnaryPrefix && p.left === this && "++" !== this.operator && "--" !== this.operator;
}), PARENS(AST_Await, function(output) {
var p = output.parent();
return p instanceof AST_PropAccess && p.expression === this || p instanceof AST_Call && p.expression === this || p instanceof AST_Binary && "**" === p.operator && p.left === this || output.option("safari10") && p instanceof AST_UnaryPrefix;
}), PARENS(AST_Sequence, function(output) {
var p = output.parent();
return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4)
|| p instanceof AST_Unary // !(foo, bar, baz)
|| p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8
|| p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4
|| p instanceof AST_PropAccess // (1, {foo:2}).foo or (1, {foo:2})["foo"] ==> 2
|| p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ]
|| p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2
|| p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30)
* ==> 20 (side effect, set a := 10 and b := 20) */ || p instanceof AST_Arrow // x => (x, x)
|| p instanceof AST_DefaultAssign // x => (x = (0, function(){}))
|| p instanceof AST_Expansion // [...(a, b)]
|| p instanceof AST_ForOf && this === p.object // for (e of (foo, bar)) {}
|| p instanceof AST_Yield // yield (foo, bar)
|| p instanceof AST_Export // export default (foo, bar)
;
}), PARENS(AST_Binary, function(output) {
var p = output.parent();
// (foo && bar)()
if (p instanceof AST_Call && p.expression === this || p instanceof AST_Unary || p instanceof AST_PropAccess && p.expression === this) return !0;
// this deals with precedence: 3 * (2 + 1)
if (p instanceof AST_Binary) {
const po = p.operator, so = this.operator;
if ("??" === so && ("||" === po || "&&" === po) || "??" === po && ("||" === so || "&&" === so)) return !0;
const pp = PRECEDENCE[po], sp = PRECEDENCE[so];
if (pp > sp || pp == sp && (this === p.right || "**" == po)) return !0;
}
}), PARENS(AST_Yield, function(output) {
var p = output.parent();
// (yield 1) + (yield 2)
// a = yield 3
if (p instanceof AST_Binary && "=" !== p.operator || p instanceof AST_Call && p.expression === this || p instanceof AST_Conditional && p.condition === this || p instanceof AST_Unary || p instanceof AST_PropAccess && p.expression === this) return !0;
}), PARENS(AST_PropAccess, function(output) {
var p = output.parent();
if (p instanceof AST_New && p.expression === this) // i.e. new (foo.bar().baz)
//
// if there's one call into this subtree, then we need
// parens around it too, otherwise the call will be
// interpreted as passing the arguments to the upper New
// expression.
return walk(this, (node)=>node instanceof AST_Scope || (node instanceof AST_Call ? walk_abort : void 0));
}), PARENS(AST_Call, function(output) {
var p1, p = output.parent();
return p instanceof AST_New && p.expression === this || p instanceof AST_Export && !!p.is_default && this.expression instanceof AST_Function || this.expression instanceof AST_Function && p instanceof AST_PropAccess && p.expression === this && (p1 = output.parent(1)) instanceof AST_Assign && p1.left === p;
}), PARENS(AST_New, function(output) {
var p = output.parent();
if (0 === this.args.length && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]()
|| p instanceof AST_Call && p.expression === this)) return !0;
}), PARENS(AST_Number, function(output) {
var p = output.parent();
if (p instanceof AST_PropAccess && p.expression === this) {
var value = this.getValue();
if (value < 0 || /^0/.test(make_num(value))) return !0;
}
}), PARENS(AST_BigInt, function(output) {
var p = output.parent();
if (p instanceof AST_PropAccess && p.expression === this && this.getValue().startsWith("-")) return !0;
}), PARENS([
AST_Assign,
AST_Conditional
], function(output) {
var p = output.parent();
// !(a = false) → true
if (p instanceof AST_Unary || p instanceof AST_Binary && !(p instanceof AST_Assign) || p instanceof AST_Call && p.expression === this || p instanceof AST_Conditional && p.condition === this || p instanceof AST_PropAccess && p.expression === this || this instanceof AST_Assign && this.left instanceof AST_Destructuring && !1 === this.left.is_array) return !0;
}), /* -----[ PRINTERS ]----- */ DEFPRINT(AST_Directive, function(self1, output) {
output.print_string(self1.value, self1.quote), output.semicolon();
}), DEFPRINT(AST_Expansion, function(self1, output) {
output.print("..."), self1.expression.print(output);
}), DEFPRINT(AST_Destructuring, function(self1, output) {
output.print(self1.is_array ? "[" : "{");
var len = self1.names.length;
self1.names.forEach(function(name, i) {
i > 0 && output.comma(), name.print(output), i == len - 1 && name instanceof AST_Hole && output.comma();
}), output.print(self1.is_array ? "]" : "}");
}), DEFPRINT(AST_Debugger, function(self1, output) {
output.print("debugger"), output.semicolon();
}), AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output) {
force_statement(this.body, output);
}), DEFPRINT(AST_Statement, function(self1, output) {
self1.body.print(output), output.semicolon();
}), DEFPRINT(AST_Toplevel, function(self1, output) {
display_body(self1.body, !0, output, !0), output.print("");
}), DEFPRINT(AST_LabeledStatement, function(self1, output) {
self1.label.print(output), output.colon(), self1.body.print(output);
}), DEFPRINT(AST_SimpleStatement, function(self1, output) {
self1.body.print(output), output.semicolon();
}), DEFPRINT(AST_BlockStatement, function(self1, output) {
print_braced(self1, output);
}), DEFPRINT(AST_EmptyStatement, function(self1, output) {
output.semicolon();
}), DEFPRINT(AST_Do, function(self1, output) {
output.print("do"), output.space(), make_block(self1.body, output), output.space(), output.print("while"), output.space(), output.with_parens(function() {
self1.condition.print(output);
}), output.semicolon();
}), DEFPRINT(AST_While, function(self1, output) {
output.print("while"), output.space(), output.with_parens(function() {
self1.condition.print(output);
}), output.space(), self1._do_print_body(output);
}), DEFPRINT(AST_For, function(self1, output) {
output.print("for"), output.space(), output.with_parens(function() {
self1.init ? (self1.init instanceof AST_Definitions ? self1.init.print(output) : parenthesize_for_noin(self1.init, output, !0), output.print(";"), output.space()) : output.print(";"), self1.condition ? (self1.condition.print(output), output.print(";"), output.space()) : output.print(";"), self1.step && self1.step.print(output);
}), output.space(), self1._do_print_body(output);
}), DEFPRINT(AST_ForIn, function(self1, output) {
output.print("for"), self1.await && (output.space(), output.print("await")), output.space(), output.with_parens(function() {
self1.init.print(output), output.space(), output.print(self1 instanceof AST_ForOf ? "of" : "in"), output.space(), self1.object.print(output);
}), output.space(), self1._do_print_body(output);
}), DEFPRINT(AST_With, function(self1, output) {
output.print("with"), output.space(), output.with_parens(function() {
self1.expression.print(output);
}), output.space(), self1._do_print_body(output);
}), /* -----[ functions ]----- */ AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword) {
var self1 = this;
!nokeyword && (self1.async && (output.print("async"), output.space()), output.print("function"), self1.is_generator && output.star(), self1.name && output.space()), self1.name instanceof AST_Symbol ? self1.name.print(output) : nokeyword && self1.name instanceof AST_Node && output.with_square(function() {
self1.name.print(output); // Computed method name
}), output.with_parens(function() {
self1.argnames.forEach(function(arg, i) {
i && output.comma(), arg.print(output);
});
}), output.space(), print_braced(self1, output, !0);
}), DEFPRINT(AST_Lambda, function(self1, output) {
self1._do_print(output);
}), DEFPRINT(AST_PrefixedTemplateString, function(self1, output) {
var tag = self1.prefix, parenthesize_tag = tag instanceof AST_Lambda || tag instanceof AST_Binary || tag instanceof AST_Conditional || tag instanceof AST_Sequence || tag instanceof AST_Unary || tag instanceof AST_Dot && tag.expression instanceof AST_Object;
parenthesize_tag && output.print("("), self1.prefix.print(output), parenthesize_tag && output.print(")"), self1.template_string.print(output);
}), DEFPRINT(AST_TemplateString, function(self1, output) {
var is_tagged = output.parent() instanceof AST_PrefixedTemplateString;
output.print("`");
for(var i = 0; i < self1.segments.length; i++)self1.segments[i] instanceof AST_TemplateSegment ? is_tagged ? output.print(self1.segments[i].raw) : output.print_template_string_chars(self1.segments[i].value) : (output.print("${"), self1.segments[i].print(output), output.print("}"));
output.print("`");
}), DEFPRINT(AST_TemplateSegment, function(self1, output) {
output.print_template_string_chars(self1.value);
}), AST_Arrow.DEFMETHOD("_do_print", function(output) {
var self1 = this, parent = output.parent(), needs_parens = parent instanceof AST_Binary && !(parent instanceof AST_Assign) || parent instanceof AST_Unary || parent instanceof AST_Call && self1 === parent.expression;
needs_parens && output.print("("), self1.async && (output.print("async"), output.space()), 1 === self1.argnames.length && self1.argnames[0] instanceof AST_Symbol ? self1.argnames[0].print(output) : output.with_parens(function() {
self1.argnames.forEach(function(arg, i) {
i && output.comma(), arg.print(output);
});
}), output.space(), output.print("=>"), output.space();
const first_statement = self1.body[0];
if (1 === self1.body.length && first_statement instanceof AST_Return) {
const returned = first_statement.value;
returned ? // Returns whether the leftmost item in the expression is an object
function left_is_object(node) {
return node instanceof AST_Object || (node instanceof AST_Sequence ? left_is_object(node.expressions[0]) : "Call" === node.TYPE ? left_is_object(node.expression) : node instanceof AST_PrefixedTemplateString ? left_is_object(node.prefix) : node instanceof AST_Dot || node instanceof AST_Sub ? left_is_object(node.expression) : node instanceof AST_Conditional ? left_is_object(node.condition) : node instanceof AST_Binary ? left_is_object(node.left) : node instanceof AST_UnaryPostfix && left_is_object(node.expression));
}(returned) ? (output.print("("), returned.print(output), output.print(")")) : returned.print(output) : output.print("{}");
} else print_braced(self1, output);
needs_parens && output.print(")");
}), /* -----[ exits ]----- */ AST_Exit.DEFMETHOD("_do_print", function(output, kind) {
if (output.print(kind), this.value) {
output.space();
const comments = this.value.start.comments_before;
comments && comments.length && !output.printed_comments.has(comments) ? (output.print("("), this.value.print(output), output.print(")")) : this.value.print(output);
}
output.semicolon();
}), DEFPRINT(AST_Return, function(self1, output) {
self1._do_print(output, "return");
}), DEFPRINT(AST_Throw, function(self1, output) {
self1._do_print(output, "throw");
}), /* -----[ yield ]----- */ DEFPRINT(AST_Yield, function(self1, output) {
var star = self1.is_star ? "*" : "";
output.print("yield" + star), self1.expression && (output.space(), self1.expression.print(output));
}), DEFPRINT(AST_Await, function(self1, output) {
output.print("await"), output.space();
var e = self1.expression, parens = !(e instanceof AST_Call || e instanceof AST_SymbolRef || e instanceof AST_PropAccess || e instanceof AST_Unary || e instanceof AST_Constant || e instanceof AST_Await || e instanceof AST_Object);
parens && output.print("("), self1.expression.print(output), parens && output.print(")");
}), /* -----[ loop control ]----- */ AST_LoopControl.DEFMETHOD("_do_print", function(output, kind) {
output.print(kind), this.label && (output.space(), this.label.print(output)), output.semicolon();
}), DEFPRINT(AST_Break, function(self1, output) {
self1._do_print(output, "break");
}), DEFPRINT(AST_Continue, function(self1, output) {
self1._do_print(output, "continue");
}), DEFPRINT(AST_If, function(self1, output) {
output.print("if"), output.space(), output.with_parens(function() {
self1.condition.print(output);
}), output.space(), self1.alternative ? (/* -----[ if ]----- */ function(self1, output) {
var b = self1.body;
if (output.option("braces") || output.option("ie8") && b instanceof AST_Do) return make_block(b, output);
// The squeezer replaces "block"-s that contain only a single
// statement with the statement itself; technically, the AST
// is correct, but this can create problems when we output an
// IF having an ELSE clause where the THEN clause ends in an
// IF *without* an ELSE block (then the outer ELSE would refer
// to the inner IF). This function checks for this case and
// adds the block braces if needed.
if (!b) return output.force_semicolon();
for(;;)if (b instanceof AST_If) {
if (!b.alternative) {
make_block(self1.body, output);
return;
}
b = b.alternative;
} else if (b instanceof AST_StatementWithBody) b = b.body;
else break;
force_statement(self1.body, output);
}(self1, output), output.space(), output.print("else"), output.space(), self1.alternative instanceof AST_If ? self1.alternative.print(output) : force_statement(self1.alternative, output)) : self1._do_print_body(output);
}), /* -----[ switch ]----- */ DEFPRINT(AST_Switch, function(self1, output) {
output.print("switch"), output.space(), output.with_parens(function() {
self1.expression.print(output);
}), output.space();
var last = self1.body.length - 1;
last < 0 ? print_braced_empty(self1, output) : output.with_block(function() {
self1.body.forEach(function(branch, i) {
output.indent(!0), branch.print(output), i < last && branch.body.length > 0 && output.newline();
});
});
}), AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output) {
output.newline(), this.body.forEach(function(stmt) {
output.indent(), stmt.print(output), output.newline();
});
}), DEFPRINT(AST_Default, function(self1, output) {
output.print("default:"), self1._do_print_body(output);
}), DEFPRINT(AST_Case, function(self1, output) {
output.print("case"), output.space(), self1.expression.print(output), output.print(":"), self1._do_print_body(output);
}), /* -----[ exceptions ]----- */ DEFPRINT(AST_Try, function(self1, output) {
output.print("try"), output.space(), print_braced(self1, output), self1.bcatch && (output.space(), self1.bcatch.print(output)), self1.bfinally && (output.space(), self1.bfinally.print(output));
}), DEFPRINT(AST_Catch, function(self1, output) {
output.print("catch"), self1.argname && (output.space(), output.with_parens(function() {
self1.argname.print(output);
})), output.space(), print_braced(self1, output);
}), DEFPRINT(AST_Finally, function(self1, output) {
output.print("finally"), output.space(), print_braced(self1, output);
}), /* -----[ var/const ]----- */ AST_Definitions.DEFMETHOD("_do_print", function(output, kind) {
output.print(kind), output.space(), this.definitions.forEach(function(def, i) {
i && output.comma(), def.print(output);
});
var p = output.parent();
(!(p instanceof AST_For || p instanceof AST_ForIn) || p && p.init !== this) && output.semicolon();
}), DEFPRINT(AST_Let, function(self1, output) {
self1._do_print(output, "let");
}), DEFPRINT(AST_Var, function(self1, output) {
self1._do_print(output, "var");
}), DEFPRINT(AST_Const, function(self1, output) {
self1._do_print(output, "const");
}), DEFPRINT(AST_Import, function(self1, output) {
output.print("import"), output.space(), self1.imported_name && self1.imported_name.print(output), self1.imported_name && self1.imported_names && (output.print(","), output.space()), self1.imported_names && (1 === self1.imported_names.length && "*" === self1.imported_names[0].foreign_name.name ? self1.imported_names[0].print(output) : (output.print("{"), self1.imported_names.forEach(function(name_import, i) {
output.space(), name_import.print(output), i < self1.imported_names.length - 1 && output.print(",");
}), output.space(), output.print("}"))), (self1.imported_name || self1.imported_names) && (output.space(), output.print("from"), output.space()), self1.module_name.print(output), self1.assert_clause && (output.print("assert"), self1.assert_clause.print(output)), output.semicolon();
}), DEFPRINT(AST_ImportMeta, function(self1, output) {
output.print("import.meta");
}), DEFPRINT(AST_NameMapping, function(self1, output) {
var is_import = output.parent() instanceof AST_Import, definition = self1.name.definition();
(definition && definition.mangled_name || self1.name.name) !== self1.foreign_name.name ? (is_import ? output.print(self1.foreign_name.name) : self1.name.print(output), output.space(), output.print("as"), output.space(), is_import ? self1.name.print(output) : output.print(self1.foreign_name.name)) : self1.name.print(output);
}), DEFPRINT(AST_Export, function(self1, output) {
if (output.print("export"), output.space(), self1.is_default && (output.print("default"), output.space()), self1.exported_names) 1 === self1.exported_names.length && "*" === self1.exported_names[0].name.name ? self1.exported_names[0].print(output) : (output.print("{"), self1.exported_names.forEach(function(name_export, i) {
output.space(), name_export.print(output), i < self1.exported_names.length - 1 && output.print(",");
}), output.space(), output.print("}"));
else if (self1.exported_value) self1.exported_value.print(output);
else if (self1.exported_definition && (self1.exported_definition.print(output), self1.exported_definition instanceof AST_Definitions)) return;
self1.module_name && (output.space(), output.print("from"), output.space(), self1.module_name.print(output)), self1.assert_clause && (output.print("assert"), self1.assert_clause.print(output)), (self1.exported_value && !(self1.exported_value instanceof AST_Defun || self1.exported_value instanceof AST_Function || self1.exported_value instanceof AST_Class) || self1.module_name || self1.exported_names) && output.semicolon();
}), DEFPRINT(AST_VarDef, function(self1, output) {
if (self1.name.print(output), self1.value) {
output.space(), output.print("="), output.space();
var p = output.parent(1), noin = p instanceof AST_For || p instanceof AST_ForIn;
parenthesize_for_noin(self1.value, output, noin);
}
}), /* -----[ other expressions ]----- */ DEFPRINT(AST_Call, function(self1, output) {
self1.expression.print(output), self1 instanceof AST_New && 0 === self1.args.length || ((self1.expression instanceof AST_Call || self1.expression instanceof AST_Lambda) && output.add_mapping(self1.start), self1.optional && output.print("?."), output.with_parens(function() {
self1.args.forEach(function(expr, i) {
i && output.comma(), expr.print(output);
});
}));
}), DEFPRINT(AST_New, function(self1, output) {
output.print("new"), output.space(), AST_Call.prototype._codegen(self1, output);
}), AST_Sequence.DEFMETHOD("_do_print", function(output) {
this.expressions.forEach(function(node, index) {
index > 0 && (output.comma(), output.should_break() && (output.newline(), output.indent())), node.print(output);
});
}), DEFPRINT(AST_Sequence, function(self1, output) {
self1._do_print(output);
// var p = output.parent();
// if (p instanceof AST_Statement) {
// output.with_indent(output.next_indent(), function(){
// self._do_print(output);
// });
// } else {
// self._do_print(output);
// }
}), DEFPRINT(AST_Dot, function(self1, output) {
var expr = self1.expression;
expr.print(output);
var prop = self1.property, print_computed = ALL_RESERVED_WORDS.has(prop) ? output.option("ie8") : !is_identifier_string(prop, output.option("ecma") >= 2015 || output.option("safari10"));
self1.optional && output.print("?."), print_computed ? (output.print("["), output.add_mapping(self1.end), output.print_string(prop), output.print("]")) : (expr instanceof AST_Number && expr.getValue() >= 0 && !/[xa-f.)]/i.test(output.last()) && output.print("."), self1.optional || output.print("."), // the name after dot would be mapped about here.
output.add_mapping(self1.end), output.print_name(prop));
}), DEFPRINT(AST_DotHash, function(self1, output) {
self1.expression.print(output);
var prop = self1.property;
self1.optional && output.print("?"), output.print(".#"), output.add_mapping(self1.end), output.print_name(prop);
}), DEFPRINT(AST_Sub, function(self1, output) {
self1.expression.print(output), self1.optional && output.print("?."), output.print("["), self1.property.print(output), output.print("]");
}), DEFPRINT(AST_Chain, function(self1, output) {
self1.expression.print(output);
}), DEFPRINT(AST_UnaryPrefix, function(self1, output) {
var op = self1.operator;
output.print(op), (/^[a-z]/i.test(op) || /[+-]$/.test(op) && self1.expression instanceof AST_UnaryPrefix && /^[+-]/.test(self1.expression.operator)) && output.space(), self1.expression.print(output);
}), DEFPRINT(AST_UnaryPostfix, function(self1, output) {
self1.expression.print(output), output.print(self1.operator);
}), DEFPRINT(AST_Binary, function(self1, output) {
var op = self1.operator;
self1.left.print(output), ">" /* ">>" ">>>" ">" ">=" */ == op[0] && self1.left instanceof AST_UnaryPostfix && "--" == self1.left.operator ? // space is mandatory to avoid outputting -->
output.print(" ") : // the space is optional depending on "beautify"
output.space(), output.print(op), ("<" == op || "<<" == op) && self1.right instanceof AST_UnaryPrefix && "!" == self1.right.operator && self1.right.expression instanceof AST_UnaryPrefix && "--" == self1.right.expression.operator ? // space is mandatory to avoid outputting <!--
output.print(" ") : // the space is optional depending on "beautify"
output.space(), self1.right.print(output);
}), DEFPRINT(AST_Conditional, function(self1, output) {
self1.condition.print(output), output.space(), output.print("?"), output.space(), self1.consequent.print(output), output.space(), output.colon(), self1.alternative.print(output);
}), /* -----[ literals ]----- */ DEFPRINT(AST_Array, function(self1, output) {
output.with_square(function() {
var a = self1.elements, len = a.length;
len > 0 && output.space(), a.forEach(function(exp, i) {
i && output.comma(), exp.print(output), i === len - 1 && exp instanceof AST_Hole && output.comma();
}), len > 0 && output.space();
});
}), DEFPRINT(AST_Object, function(self1, output) {
self1.properties.length > 0 ? output.with_block(function() {
self1.properties.forEach(function(prop, i) {
i && (output.print(","), output.newline()), output.indent(), prop.print(output);
}), output.newline();
}) : print_braced_empty(self1, output);
}), DEFPRINT(AST_Class, function(self1, output) {
if (output.print("class"), output.space(), self1.name && (self1.name.print(output), output.space()), self1.extends) {
var parens = !(self1.extends instanceof AST_SymbolRef) && !(self1.extends instanceof AST_PropAccess) && !(self1.extends instanceof AST_ClassExpression) && !(self1.extends instanceof AST_Function);
output.print("extends"), parens ? output.print("(") : output.space(), self1.extends.print(output), parens ? output.print(")") : output.space();
}
self1.properties.length > 0 ? output.with_block(function() {
self1.properties.forEach(function(prop, i) {
i && output.newline(), output.indent(), prop.print(output);
}), output.newline();
}) : output.print("{}");
}), DEFPRINT(AST_NewTarget, function(self1, output) {
output.print("new.target");
}), DEFPRINT(AST_ObjectKeyVal, function(self1, output) {
function get_name(self1) {
var def = self1.definition();
return def ? def.mangled_name || def.name : self1.name;
}
var allowShortHand = output.option("shorthand");
allowShortHand && self1.value instanceof AST_Symbol && is_identifier_string(self1.key, output.option("ecma") >= 2015 || output.option("safari10")) && get_name(self1.value) === self1.key && !ALL_RESERVED_WORDS.has(self1.key) ? print_property_name(self1.key, self1.quote, output) : allowShortHand && self1.value instanceof AST_DefaultAssign && self1.value.left instanceof AST_Symbol && is_identifier_string(self1.key, output.option("ecma") >= 2015 || output.option("safari10")) && get_name(self1.value.left) === self1.key ? (print_property_name(self1.key, self1.quote, output), output.space(), output.print("="), output.space(), self1.value.right.print(output)) : (self1.key instanceof AST_Node ? output.with_square(function() {
self1.key.print(output);
}) : print_property_name(self1.key, self1.quote, output), output.colon(), self1.value.print(output));
}), DEFPRINT(AST_ClassPrivateProperty, (self1, output)=>{
self1.static && (output.print("static"), output.space()), output.print("#"), print_property_name(self1.key.name, self1.quote, output), self1.value && (output.print("="), self1.value.print(output)), output.semicolon();
}), DEFPRINT(AST_ClassProperty, (self1, output)=>{
self1.static && (output.print("static"), output.space()), self1.key instanceof AST_SymbolClassProperty ? print_property_name(self1.key.name, self1.quote, output) : (output.print("["), self1.key.print(output), output.print("]")), self1.value && (output.print("="), self1.value.print(output)), output.semicolon();
}), AST_ObjectProperty.DEFMETHOD("_print_getter_setter", function(type, is_private, output) {
var self1 = this;
self1.static && (output.print("static"), output.space()), type && (output.print(type), output.space()), self1.key instanceof AST_SymbolMethod ? (is_private && output.print("#"), print_property_name(self1.key.name, self1.quote, output)) : output.with_square(function() {
self1.key.print(output);
}), self1.value._do_print(output, !0);
}), DEFPRINT(AST_ObjectSetter, function(self1, output) {
self1._print_getter_setter("set", !1, output);
}), DEFPRINT(AST_ObjectGetter, function(self1, output) {
self1._print_getter_setter("get", !1, output);
}), DEFPRINT(AST_PrivateSetter, function(self1, output) {
self1._print_getter_setter("set", !0, output);
}), DEFPRINT(AST_PrivateGetter, function(self1, output) {
self1._print_getter_setter("get", !0, output);
}), DEFPRINT(AST_PrivateMethod, function(self1, output) {
var type;
self1.is_generator && self1.async ? type = "async*" : self1.is_generator ? type = "*" : self1.async && (type = "async"), self1._print_getter_setter(type, !0, output);
}), DEFPRINT(AST_ConciseMethod, function(self1, output) {
var type;
self1.is_generator && self1.async ? type = "async*" : self1.is_generator ? type = "*" : self1.async && (type = "async"), self1._print_getter_setter(type, !1, output);
}), AST_Symbol.DEFMETHOD("_do_print", function(output) {
var def = this.definition();
output.print_name(def ? def.mangled_name || def.name : this.name);
}), DEFPRINT(AST_Symbol, function(self1, output) {
self1._do_print(output);
}), DEFPRINT(AST_Hole, noop), DEFPRINT(AST_This, function(self1, output) {
output.print("this");
}), DEFPRINT(AST_Super, function(self1, output) {
output.print("super");
}), DEFPRINT(AST_Constant, function(self1, output) {
output.print(self1.getValue());
}), DEFPRINT(AST_String, function(self1, output) {
output.print_string(self1.getValue(), self1.quote, output.in_directive);
}), DEFPRINT(AST_Number, function(self1, output) {
(output.option("keep_numbers") || output.use_asm) && self1.raw ? output.print(self1.raw) : output.print(make_num(self1.getValue()));
}), DEFPRINT(AST_BigInt, function(self1, output) {
output.print(self1.getValue() + "n");
});
const r_slash_script = /(<\s*\/\s*script)/i, slash_script_replace = (_, $1)=>$1.replace("/", "\\/");
function force_statement(stat, output) {
output.option("braces") ? make_block(stat, output) : !stat || stat instanceof AST_EmptyStatement ? output.force_semicolon() : stat.print(output);
}
function make_num(num) {
var match, len, digits, str = num.toString(10).replace(/^0\./, ".").replace("e+", "e"), candidates = [
str
];
return Math.floor(num) === num && (num < 0 ? candidates.push("-0x" + (-num).toString(16).toLowerCase()) : candidates.push("0x" + num.toString(16).toLowerCase())), (match = /^\.0+/.exec(str)) ? (len = match[0].length, digits = str.slice(len), candidates.push(digits + "e-" + (digits.length + len - 1))) : (match = /0+$/.exec(str)) ? (len = match[0].length, candidates.push(str.slice(0, -len) + "e" + len)) : (match = /^(\d)\.(\d+)e(-?\d+)$/.exec(str)) && candidates.push(match[1] + match[2] + "e" + (match[3] - match[2].length)), function(a) {
for(var best = a[0], len = best.length, i = 1; i < a.length; ++i)a[i].length < len && (len = (best = a[i]).length);
return best;
}(candidates);
}
function make_block(stmt, output) {
!stmt || stmt instanceof AST_EmptyStatement ? output.print("{}") : stmt instanceof AST_BlockStatement ? stmt.print(output) : output.with_block(function() {
output.indent(), stmt.print(output), output.newline();
});
}
/* -----[ source map generators ]----- */ function DEFMAP(nodetype, generator) {
nodetype.forEach(function(nodetype) {
nodetype.DEFMETHOD("add_source_map", generator);
});
}
DEFPRINT(AST_RegExp, function(self1, output) {
let { source, flags } = self1.getValue();
source = regexp_source_fix(source), flags = flags ? function(flags) {
const existing_flags = new Set(flags.split(""));
let out = "";
for (const flag of "gimuy")existing_flags.has(flag) && (out += flag, existing_flags.delete(flag));
return existing_flags.size && // Flags Terser doesn't know about
existing_flags.forEach((flag)=>{
out += flag;
}), out;
}(flags) : "", source = source.replace(r_slash_script, slash_script_replace), output.print(output.to_utf8(`/${source}/${flags}`, !1, !0));
const parent = output.parent();
parent instanceof AST_Binary && /^\w/.test(parent.operator) && parent.left === self1 && output.print(" ");
}), DEFMAP([
// We could easily add info for ALL nodes, but it seems to me that
// would be quite wasteful, hence this noop in the base class.
AST_Node,
// since the label symbol will mark it
AST_LabeledStatement,
AST_Toplevel
], noop), // XXX: I'm not exactly sure if we need it for all of these nodes,
// or if we should add even more.
DEFMAP([
AST_Array,
AST_BlockStatement,
AST_Catch,
AST_Class,
AST_Constant,
AST_Debugger,
AST_Definitions,
AST_Directive,
AST_Finally,
AST_Jump,
AST_Lambda,
AST_New,
AST_Object,
AST_StatementWithBody,
AST_Symbol,
AST_Switch,
AST_SwitchBranch,
AST_TemplateString,
AST_TemplateSegment,
AST_Try
], function(output) {
output.add_mapping(this.start);
}), DEFMAP([
AST_ObjectGetter,
AST_ObjectSetter,
AST_PrivateGetter,
AST_PrivateSetter
], function(output) {
output.add_mapping(this.key.end, this.key.name);
}), DEFMAP([
AST_ObjectProperty
], function(output) {
output.add_mapping(this.start, this.key);
});
}();
const shallow_cmp = (node1, node2)=>null === node1 && null === node2 || node1.TYPE === node2.TYPE && node1.shallow_cmp(node2), equivalent_to = (tree1, tree2)=>{
if (!shallow_cmp(tree1, tree2)) return !1;
const walk_1_state = [
tree1
], walk_2_state = [
tree2
], walk_1_push = walk_1_state.push.bind(walk_1_state), walk_2_push = walk_2_state.push.bind(walk_2_state);
for(; walk_1_state.length && walk_2_state.length;){
const node_1 = walk_1_state.pop(), node_2 = walk_2_state.pop();
if (!shallow_cmp(node_1, node_2) || (node_1._children_backwards(walk_1_push), node_2._children_backwards(walk_2_push), walk_1_state.length !== walk_2_state.length)) return !1;
}
return 0 == walk_1_state.length && 0 == walk_2_state.length;
}, mkshallow = (props)=>Function("other", "return " + Object.keys(props).map((key)=>{
if ("eq" === props[key]) return `this.${key} === other.${key}`;
if ("exist" === props[key]) return `(this.${key} == null ? other.${key} == null : this.${key} === other.${key})`;
throw Error(`mkshallow: Unexpected instruction: ${props[key]}`);
}).join(" && ")), pass_through = ()=>!0;
AST_Node.prototype.shallow_cmp = function() {
throw Error("did not find a shallow_cmp function for " + this.constructor.name);
}, AST_Debugger.prototype.shallow_cmp = pass_through, AST_Directive.prototype.shallow_cmp = mkshallow({
value: "eq"
}), AST_SimpleStatement.prototype.shallow_cmp = pass_through, AST_Block.prototype.shallow_cmp = pass_through, AST_EmptyStatement.prototype.shallow_cmp = pass_through, AST_LabeledStatement.prototype.shallow_cmp = mkshallow({
"label.name": "eq"
}), AST_Do.prototype.shallow_cmp = pass_through, AST_While.prototype.shallow_cmp = pass_through, AST_For.prototype.shallow_cmp = mkshallow({
init: "exist",
condition: "exist",
step: "exist"
}), AST_ForIn.prototype.shallow_cmp = pass_through, AST_ForOf.prototype.shallow_cmp = pass_through, AST_With.prototype.shallow_cmp = pass_through, AST_Toplevel.prototype.shallow_cmp = pass_through, AST_Expansion.prototype.shallow_cmp = pass_through, AST_Lambda.prototype.shallow_cmp = mkshallow({
is_generator: "eq",
async: "eq"
}), AST_Destructuring.prototype.shallow_cmp = mkshallow({
is_array: "eq"
}), AST_PrefixedTemplateString.prototype.shallow_cmp = pass_through, AST_TemplateString.prototype.shallow_cmp = pass_through, AST_TemplateSegment.prototype.shallow_cmp = mkshallow({
value: "eq"
}), AST_Jump.prototype.shallow_cmp = pass_through, AST_LoopControl.prototype.shallow_cmp = pass_through, AST_Await.prototype.shallow_cmp = pass_through, AST_Yield.prototype.shallow_cmp = mkshallow({
is_star: "eq"
}), AST_If.prototype.shallow_cmp = mkshallow({
alternative: "exist"
}), AST_Switch.prototype.shallow_cmp = pass_through, AST_SwitchBranch.prototype.shallow_cmp = pass_through, AST_Try.prototype.shallow_cmp = mkshallow({
bcatch: "exist",
bfinally: "exist"
}), AST_Catch.prototype.shallow_cmp = mkshallow({
argname: "exist"
}), AST_Finally.prototype.shallow_cmp = pass_through, AST_Definitions.prototype.shallow_cmp = pass_through, AST_VarDef.prototype.shallow_cmp = mkshallow({
value: "exist"
}), AST_NameMapping.prototype.shallow_cmp = pass_through, AST_Import.prototype.shallow_cmp = mkshallow({
imported_name: "exist",
imported_names: "exist"
}), AST_ImportMeta.prototype.shallow_cmp = pass_through, AST_Export.prototype.shallow_cmp = mkshallow({
exported_definition: "exist",
exported_value: "exist",
exported_names: "exist",
module_name: "eq",
is_default: "eq"
}), AST_Call.prototype.shallow_cmp = pass_through, AST_Sequence.prototype.shallow_cmp = pass_through, AST_PropAccess.prototype.shallow_cmp = pass_through, AST_Chain.prototype.shallow_cmp = pass_through, AST_Dot.prototype.shallow_cmp = mkshallow({
property: "eq"
}), AST_DotHash.prototype.shallow_cmp = mkshallow({
property: "eq"
}), AST_Unary.prototype.shallow_cmp = mkshallow({
operator: "eq"
}), AST_Binary.prototype.shallow_cmp = mkshallow({
operator: "eq"
}), AST_Conditional.prototype.shallow_cmp = pass_through, AST_Array.prototype.shallow_cmp = pass_through, AST_Object.prototype.shallow_cmp = pass_through, AST_ObjectProperty.prototype.shallow_cmp = pass_through, AST_ObjectKeyVal.prototype.shallow_cmp = mkshallow({
key: "eq"
}), AST_ObjectSetter.prototype.shallow_cmp = mkshallow({
static: "eq"
}), AST_ObjectGetter.prototype.shallow_cmp = mkshallow({
static: "eq"
}), AST_ConciseMethod.prototype.shallow_cmp = mkshallow({
static: "eq",
is_generator: "eq",
async: "eq"
}), AST_Class.prototype.shallow_cmp = mkshallow({
name: "exist",
extends: "exist"
}), AST_ClassProperty.prototype.shallow_cmp = mkshallow({
static: "eq"
}), AST_Symbol.prototype.shallow_cmp = mkshallow({
name: "eq"
}), AST_NewTarget.prototype.shallow_cmp = pass_through, AST_This.prototype.shallow_cmp = pass_through, AST_Super.prototype.shallow_cmp = pass_through, AST_String.prototype.shallow_cmp = mkshallow({
value: "eq"
}), AST_Number.prototype.shallow_cmp = mkshallow({
value: "eq"
}), AST_BigInt.prototype.shallow_cmp = mkshallow({
value: "eq"
}), AST_RegExp.prototype.shallow_cmp = function(other) {
return this.value.flags === other.value.flags && this.value.source === other.value.source;
}, AST_Atom.prototype.shallow_cmp = pass_through;
let function_defs = null, unmangleable_names = null;
class SymbolDef {
constructor(scope, orig, init){
this.name = orig.name, this.orig = [
orig
], this.init = init, this.eliminated = 0, this.assignments = 0, this.scope = scope, this.replaced = 0, this.global = !1, this.export = 0, this.mangled_name = null, this.undeclared = !1, this.id = SymbolDef.next_id++, this.chained = !1, this.direct_access = !1, this.escaped = 0, this.recursive_refs = 0, this.references = [], this.should_replace = void 0, this.single_use = !1, this.fixed = !1, Object.seal(this);
}
fixed_value() {
return !this.fixed || this.fixed instanceof AST_Node ? this.fixed : this.fixed();
}
unmangleable(options) {
return options || (options = {}), !!(function_defs && function_defs.has(this.id) && keep_name(options.keep_fnames, this.orig[0].name)) || this.global && !options.toplevel || 1 & this.export || this.undeclared || !options.eval && this.scope.pinned() || (this.orig[0] instanceof AST_SymbolLambda || this.orig[0] instanceof AST_SymbolDefun) && keep_name(options.keep_fnames, this.orig[0].name) || this.orig[0] instanceof AST_SymbolMethod || (this.orig[0] instanceof AST_SymbolClass || this.orig[0] instanceof AST_SymbolDefClass) && keep_name(options.keep_classnames, this.orig[0].name);
}
mangle(options) {
const cache = options.cache && options.cache.props;
if (this.global && cache && cache.has(this.name)) this.mangled_name = cache.get(this.name);
else if (!this.mangled_name && !this.unmangleable(options)) {
var s = this.scope, sym = this.orig[0];
options.ie8 && sym instanceof AST_SymbolLambda && (s = s.parent_scope);
const redefinition = redefined_catch_def(this);
this.mangled_name = redefinition ? redefinition.mangled_name || redefinition.name : s.next_mangled(options, this), this.global && cache && cache.set(this.name, this.mangled_name);
}
}
}
function redefined_catch_def(def) {
if (def.orig[0] instanceof AST_SymbolCatch && def.scope.is_block_scope()) return def.scope.get_defun_scope().variables.get(def.name);
}
function next_mangled(scope, options) {
var ext = scope.enclosed, nth_identifier = options.nth_identifier;
out: for(;;){
var m = nth_identifier.get(++scope.cname);
if (!(ALL_RESERVED_WORDS.has(m) || options.reserved.has(m)) && !(unmangleable_names && unmangleable_names.has(m))) {
// we must ensure that the mangled name does not shadow a name
// from some parent scope that is referenced in this or in
// inner scopes.
for(let i = ext.length; --i >= 0;){
const def = ext[i];
if (m == (def.mangled_name || def.unmangleable(options) && def.name)) continue out;
}
return m;
} // skip over "do"
}
}
SymbolDef.next_id = 1, AST_Scope.DEFMETHOD("figure_out_scope", function(options, { parent_scope = null, toplevel = this } = {}) {
if (options = defaults(options, {
cache: null,
ie8: !1,
safari10: !1
}), !(toplevel instanceof AST_Toplevel)) throw Error("Invalid toplevel scope");
// pass 1: setup scope chaining and handle definitions
var scope = this.parent_scope = parent_scope, labels = new Map(), defun = null, in_destructuring = null, for_scopes = [], tw = new TreeWalker((node, descend)=>{
if (node.is_block_scope()) {
const save_scope = scope;
node.block_scope = scope = new AST_Scope(node), scope._block_scope = !0;
// AST_Try in the AST sadly *is* (not has) a body itself,
// and its catch and finally branches are children of the AST_Try itself
const parent_scope = node instanceof AST_Catch ? save_scope.parent_scope : save_scope;
if (scope.init_scope_vars(parent_scope), scope.uses_with = save_scope.uses_with, scope.uses_eval = save_scope.uses_eval, options.safari10 && (node instanceof AST_For || node instanceof AST_ForIn) && for_scopes.push(scope), node instanceof AST_Switch) {
// XXX: HACK! Ensure the switch expression gets the correct scope (the parent scope) and the body gets the contained scope
// AST_Switch has a scope within the body, but it itself "is a block scope"
// This means the switched expression has to belong to the outer scope
// while the body inside belongs to the switch itself.
// This is pretty nasty and warrants an AST change similar to AST_Try (read above)
const the_block_scope = scope;
scope = save_scope, node.expression.walk(tw), scope = the_block_scope;
for(let i = 0; i < node.body.length; i++)node.body[i].walk(tw);
} else descend();
return scope = save_scope, !0;
}
if (node instanceof AST_Destructuring) {
const save_destructuring = in_destructuring;
return in_destructuring = node, descend(), in_destructuring = save_destructuring, !0;
}
if (node instanceof AST_Scope) {
node.init_scope_vars(scope);
var def, save_scope = scope, save_defun = defun, save_labels = labels;
return defun = scope = node, labels = new Map(), descend(), scope = save_scope, defun = save_defun, labels = save_labels, !0; // don't descend again in TreeWalker
}
if (node instanceof AST_LabeledStatement) {
var l = node.label;
if (labels.has(l.name)) throw Error(string_template("Label {name} defined twice", l));
return labels.set(l.name, l), descend(), labels.delete(l.name), !0; // no descend again
}
if (node instanceof AST_With) {
for(var s = scope; s; s = s.parent_scope)s.uses_with = !0;
return;
}
if (node instanceof AST_Symbol && (node.scope = scope), node instanceof AST_Label && (node.thedef = node, node.references = []), node instanceof AST_SymbolLambda) defun.def_function(node, "arguments" == node.name ? void 0 : defun);
else if (node instanceof AST_SymbolDefun) {
// Careful here, the scope where this should be defined is
// the parent scope. The reason is that we enter a new
// scope when we encounter the AST_Defun node (which is
// instanceof AST_Scope) but we get to the symbol a bit
// later.
const closest_scope = defun.parent_scope;
// In strict mode, function definitions are block-scoped
node.scope = tw.directives["use strict"] ? closest_scope : closest_scope.get_defun_scope(), mark_export(node.scope.def_function(node, defun), 1);
} else if (node instanceof AST_SymbolClass) mark_export(defun.def_variable(node, defun), 1);
else if (node instanceof AST_SymbolImport) scope.def_variable(node);
else if (node instanceof AST_SymbolDefClass) // This deals with the name of the class being available
// inside the class.
mark_export((node.scope = defun.parent_scope).def_function(node, defun), 1);
else if (node instanceof AST_SymbolVar || node instanceof AST_SymbolLet || node instanceof AST_SymbolConst || node instanceof AST_SymbolCatch) {
if ((def = node instanceof AST_SymbolBlockDeclaration ? scope.def_variable(node, null) : defun.def_variable(node, "SymbolVar" == node.TYPE ? null : void 0)).orig.every((sym)=>sym === node || (node instanceof AST_SymbolBlockDeclaration ? sym instanceof AST_SymbolLambda : !(sym instanceof AST_SymbolLet || sym instanceof AST_SymbolConst))) || js_error(`"${node.name}" is redeclared`, node.start.file, node.start.line, node.start.col, node.start.pos), node instanceof AST_SymbolFunarg || mark_export(def, 2), defun !== scope) {
node.mark_enclosed();
var def = scope.find_variable(node);
node.thedef !== def && (node.thedef = def, node.reference());
}
} else if (node instanceof AST_LabelRef) {
var sym = labels.get(node.name);
if (!sym) throw Error(string_template("Undefined label {name} [{line},{col}]", {
name: node.name,
line: node.start.line,
col: node.start.col
}));
node.thedef = sym;
}
!(scope instanceof AST_Toplevel) && (node instanceof AST_Export || node instanceof AST_Import) && js_error(`"${node.TYPE}" statement may only appear at the top level`, node.start.file, node.start.line, node.start.col, node.start.pos);
});
function mark_export(def, level) {
if (in_destructuring) {
var i = 0;
do level++;
while (tw.parent(i++) !== in_destructuring)
}
var node = tw.parent(level);
if (def.export = +(node instanceof AST_Export)) {
var exported = node.exported_definition;
(exported instanceof AST_Defun || exported instanceof AST_DefClass) && node.is_default && (def.export = 2);
}
}
this.walk(tw), this instanceof AST_Toplevel && (this.globals = new Map());
var tw = new TreeWalker((node)=>{
if (node instanceof AST_LoopControl && node.label) return node.label.thedef.references.push(node), !0;
if (node instanceof AST_SymbolRef) {
var def, sym, name = node.name;
if ("eval" == name && tw.parent() instanceof AST_Call) for(var s = node.scope; s && !s.uses_eval; s = s.parent_scope)s.uses_eval = !0;
return tw.parent() instanceof AST_NameMapping && tw.parent(1).module_name || !(sym = node.scope.find_variable(name)) ? (sym = toplevel.def_global(node), node instanceof AST_SymbolExport && (sym.export = 1)) : sym.scope instanceof AST_Lambda && "arguments" == name && (sym.scope.uses_arguments = !0), node.thedef = sym, node.reference(), !node.scope.is_block_scope() || sym.orig[0] instanceof AST_SymbolBlockDeclaration || (node.scope = node.scope.get_defun_scope()), !0;
}
if (node instanceof AST_SymbolCatch && (def = redefined_catch_def(node.definition()))) for(var s = node.scope; s && (push_uniq(s.enclosed, def), s !== def.scope);)s = s.parent_scope;
});
// pass 4: add symbol definitions to loop scopes
// Safari/Webkit bug workaround - loop init let variable shadowing argument.
// https://github.com/mishoo/UglifyJS2/issues/1753
// https://bugs.webkit.org/show_bug.cgi?id=171041
if (this.walk(tw), (options.ie8 || options.safari10) && walk(this, (node)=>{
if (node instanceof AST_SymbolCatch) {
var name = node.name, refs = node.thedef.references, scope = node.scope.get_defun_scope(), def = scope.find_variable(name) || toplevel.globals.get(name) || scope.def_variable(node);
return refs.forEach(function(ref) {
ref.thedef = def, ref.reference();
}), node.thedef = def, node.reference(), !0;
}
}), options.safari10) for (const scope of for_scopes)scope.parent_scope.variables.forEach(function(def) {
push_uniq(scope.enclosed, def);
});
}), AST_Toplevel.DEFMETHOD("def_global", function(node) {
var globals = this.globals, name = node.name;
if (globals.has(name)) return globals.get(name);
var g = new SymbolDef(this, node);
return g.undeclared = !0, g.global = !0, globals.set(name, g), g;
}), AST_Scope.DEFMETHOD("init_scope_vars", function(parent_scope) {
this.variables = new Map(), this.uses_with = !1, this.uses_eval = !1, this.parent_scope = parent_scope, this.enclosed = [], this.cname = -1;
}), AST_Scope.DEFMETHOD("conflicting_def", function(name) {
return this.enclosed.find((def)=>def.name === name) || this.variables.has(name) || this.parent_scope && this.parent_scope.conflicting_def(name);
}), AST_Scope.DEFMETHOD("conflicting_def_shallow", function(name) {
return this.enclosed.find((def)=>def.name === name) || this.variables.has(name);
}), AST_Scope.DEFMETHOD("add_child_scope", function(scope) {
// `scope` is going to be moved into `this` right now.
// Update the required scopes' information
if (scope.parent_scope === this) return;
scope.parent_scope = this;
// TODO uses_with, uses_eval, etc
const scope_ancestry = (()=>{
const ancestry = [];
let cur = this;
do ancestry.push(cur);
while (cur = cur.parent_scope)
return ancestry.reverse(), ancestry;
})(), new_scope_enclosed_set = new Set(scope.enclosed), to_enclose = [];
for (const scope_topdown of scope_ancestry)for (const def of (to_enclose.forEach((e)=>push_uniq(scope_topdown.enclosed, e)), scope_topdown.variables.values()))new_scope_enclosed_set.has(def) && (push_uniq(to_enclose, def), push_uniq(scope_topdown.enclosed, def));
}), // Creates a symbol during compression
AST_Scope.DEFMETHOD("create_symbol", function(SymClass, { source, tentative_name, scope, conflict_scopes = [
scope
], init = null } = {}) {
let symbol_name;
if (conflict_scopes = function(scopes) {
const found_scopes = new Set();
for (const scope of new Set(scopes))!function bubble_up(scope) {
null == scope || found_scopes.has(scope) || (found_scopes.add(scope), bubble_up(scope.parent_scope));
}(scope);
return [
...found_scopes
];
}(conflict_scopes), tentative_name) {
// Implement hygiene (no new names are conflicting with existing names)
tentative_name = symbol_name = tentative_name.replace(/(?:^[^a-z_$]|[^a-z0-9_$])/ig, "_");
let i = 0;
for(; conflict_scopes.find((s)=>s.conflicting_def_shallow(symbol_name));)symbol_name = tentative_name + "$" + i++;
}
if (!symbol_name) throw Error("No symbol name could be generated in create_symbol()");
const symbol = make_node(SymClass, source, {
name: symbol_name,
scope
});
return this.def_variable(symbol, init || null), symbol.mark_enclosed(), symbol;
}), AST_Node.DEFMETHOD("is_block_scope", return_false), AST_Class.DEFMETHOD("is_block_scope", return_false), AST_Lambda.DEFMETHOD("is_block_scope", return_false), AST_Toplevel.DEFMETHOD("is_block_scope", return_false), AST_SwitchBranch.DEFMETHOD("is_block_scope", return_false), AST_Block.DEFMETHOD("is_block_scope", return_true), AST_Scope.DEFMETHOD("is_block_scope", function() {
return this._block_scope || !1;
}), AST_IterationStatement.DEFMETHOD("is_block_scope", return_true), AST_Lambda.DEFMETHOD("init_scope_vars", function() {
AST_Scope.prototype.init_scope_vars.apply(this, arguments), this.uses_arguments = !1, this.def_variable(new AST_SymbolFunarg({
name: "arguments",
start: this.start,
end: this.end
}));
}), AST_Arrow.DEFMETHOD("init_scope_vars", function() {
AST_Scope.prototype.init_scope_vars.apply(this, arguments), this.uses_arguments = !1;
}), AST_Symbol.DEFMETHOD("mark_enclosed", function() {
for(var def = this.definition(), s = this.scope; s && (push_uniq(s.enclosed, def), s !== def.scope);)s = s.parent_scope;
}), AST_Symbol.DEFMETHOD("reference", function() {
this.definition().references.push(this), this.mark_enclosed();
}), AST_Scope.DEFMETHOD("find_variable", function(name) {
return name instanceof AST_Symbol && (name = name.name), this.variables.get(name) || this.parent_scope && this.parent_scope.find_variable(name);
}), AST_Scope.DEFMETHOD("def_function", function(symbol, init) {
var def = this.def_variable(symbol, init);
return (!def.init || def.init instanceof AST_Defun) && (def.init = init), def;
}), AST_Scope.DEFMETHOD("def_variable", function(symbol, init) {
var def = this.variables.get(symbol.name);
return def ? (def.orig.push(symbol), def.init && (def.scope !== symbol.scope || def.init instanceof AST_Function) && (def.init = init)) : (def = new SymbolDef(this, symbol, init), this.variables.set(symbol.name, def), def.global = !this.parent_scope), symbol.thedef = def;
}), AST_Scope.DEFMETHOD("next_mangled", function(options) {
return next_mangled(this, options);
}), AST_Toplevel.DEFMETHOD("next_mangled", function(options) {
let name;
const mangled_names = this.mangled_names;
do name = next_mangled(this, options);
while (mangled_names.has(name))
return name;
}), AST_Function.DEFMETHOD("next_mangled", function(options, def) {
for(// #179, #326
// in Safari strict mode, something like (function x(x){...}) is a syntax error;
// a function expression's argument cannot shadow the function expression's name
var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition(), tricky_name = tricky_def ? tricky_def.mangled_name || tricky_def.name : null;;){
var name = next_mangled(this, options);
if (!tricky_name || tricky_name != name) return name;
}
}), AST_Symbol.DEFMETHOD("unmangleable", function(options) {
var def = this.definition();
return !def || def.unmangleable(options);
}), // labels are always mangleable
AST_Label.DEFMETHOD("unmangleable", return_false), AST_Symbol.DEFMETHOD("unreferenced", function() {
return !this.definition().references.length && !this.scope.pinned();
}), AST_Symbol.DEFMETHOD("definition", function() {
return this.thedef;
}), AST_Symbol.DEFMETHOD("global", function() {
return this.thedef.global;
}), AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options) {
return (options = defaults(options, {
eval: !1,
nth_identifier: base54,
ie8: !1,
keep_classnames: !1,
keep_fnames: !1,
module: !1,
reserved: [],
toplevel: !1
})).module && (options.toplevel = !0), Array.isArray(options.reserved) || options.reserved instanceof Set || (options.reserved = []), options.reserved = new Set(options.reserved), // Never mangle arguments
options.reserved.add("arguments"), options;
}), AST_Toplevel.DEFMETHOD("mangle_names", function(options) {
var nth_identifier = (options = this._default_mangler_options(options)).nth_identifier, lname = -1, to_mangle = [];
options.keep_fnames && (function_defs = new Set());
const mangled_names = this.mangled_names = new Set();
unmangleable_names = new Set(), options.cache && (this.globals.forEach(collect), options.cache.props && options.cache.props.forEach(function(mangled_name) {
mangled_names.add(mangled_name);
}));
var tw = new TreeWalker(function(node, descend) {
if (node instanceof AST_LabeledStatement) {
// lname is incremented when we get to the AST_Label
var save_nesting = lname;
return descend(), lname = save_nesting, !0; // don't descend again in TreeWalker
}
if (node instanceof AST_Scope) {
node.variables.forEach(collect);
return;
}
if (node.is_block_scope()) {
node.block_scope.variables.forEach(collect);
return;
}
if (function_defs && node instanceof AST_VarDef && node.value instanceof AST_Lambda && !node.value.name && keep_name(options.keep_fnames, node.name.name)) {
function_defs.add(node.name.definition().id);
return;
}
if (node instanceof AST_Label) {
let name;
do name = nth_identifier.get(++lname);
while (ALL_RESERVED_WORDS.has(name))
return node.mangled_name = name, !0;
}
if (!(options.ie8 || options.safari10) && node instanceof AST_SymbolCatch) {
to_mangle.push(node.definition());
return;
}
});
function collect(symbol) {
1 & symbol.export ? unmangleable_names.add(symbol.name) : options.reserved.has(symbol.name) || to_mangle.push(symbol);
}
this.walk(tw), (options.keep_fnames || options.keep_classnames) && // Collect a set of short names which are unmangleable,
// for use in avoiding collisions in next_mangled.
to_mangle.forEach((def)=>{
def.name.length < 6 && def.unmangleable(options) && unmangleable_names.add(def.name);
}), to_mangle.forEach((def)=>{
def.mangle(options);
}), function_defs = null, unmangleable_names = null;
}), AST_Toplevel.DEFMETHOD("find_colliding_names", function(options) {
const cache = options.cache && options.cache.props, avoid = new Set();
return options.reserved.forEach(to_avoid), this.globals.forEach(add_def), this.walk(new TreeWalker(function(node) {
node instanceof AST_Scope && node.variables.forEach(add_def), node instanceof AST_SymbolCatch && add_def(node.definition());
})), avoid;
function to_avoid(name) {
avoid.add(name);
}
function add_def(def) {
var name = def.name;
if (def.global && cache && cache.has(name)) name = cache.get(name);
else if (!def.unmangleable(options)) return;
to_avoid(name);
}
}), AST_Toplevel.DEFMETHOD("expand_names", function(options) {
var nth_identifier = (options = this._default_mangler_options(options)).nth_identifier;
nth_identifier.reset && nth_identifier.sort && (nth_identifier.reset(), nth_identifier.sort());
var avoid = this.find_colliding_names(options), cname = 0;
function rename(def) {
if (def.global && options.cache || def.unmangleable(options) || options.reserved.has(def.name)) return;
const redefinition = redefined_catch_def(def), name = def.name = redefinition ? redefinition.name : function() {
var name;
do name = nth_identifier.get(cname++);
while (avoid.has(name) || ALL_RESERVED_WORDS.has(name))
return name;
}();
def.orig.forEach(function(sym) {
sym.name = name;
}), def.references.forEach(function(sym) {
sym.name = name;
});
}
this.globals.forEach(rename), this.walk(new TreeWalker(function(node) {
node instanceof AST_Scope && node.variables.forEach(rename), node instanceof AST_SymbolCatch && rename(node.definition());
}));
}), AST_Node.DEFMETHOD("tail_node", return_this), AST_Sequence.DEFMETHOD("tail_node", function() {
return this.expressions[this.expressions.length - 1];
}), AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options) {
var nth_identifier = (options = this._default_mangler_options(options)).nth_identifier;
if (nth_identifier.reset && nth_identifier.consider && nth_identifier.sort) {
nth_identifier.reset();
try {
AST_Node.prototype.print = function(stream, force_parens) {
this._print(stream, force_parens), this instanceof AST_Symbol && !this.unmangleable(options) ? nth_identifier.consider(this.name, -1) : options.properties && (this instanceof AST_DotHash ? nth_identifier.consider("#" + this.property, -1) : this instanceof AST_Dot ? nth_identifier.consider(this.property, -1) : this instanceof AST_Sub && function skip_string(node) {
node instanceof AST_String ? nth_identifier.consider(node.value, -1) : node instanceof AST_Conditional ? (skip_string(node.consequent), skip_string(node.alternative)) : node instanceof AST_Sequence && skip_string(node.tail_node());
}(this.property));
}, nth_identifier.consider(this.print_to_string(), 1);
} finally{
AST_Node.prototype.print = AST_Node.prototype._print;
}
nth_identifier.sort();
}
});
const base54 = (()=>{
let chars, frequency;
const leading = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_".split(""), digits = "0123456789".split("");
function reset() {
frequency = new Map(), leading.forEach(function(ch) {
frequency.set(ch, 0);
}), digits.forEach(function(ch) {
frequency.set(ch, 0);
});
}
function compare(a, b) {
return frequency.get(b) - frequency.get(a);
}
function sort() {
chars = mergeSort(leading, compare).concat(mergeSort(digits, compare));
}
return(// Ensure this is in a usable initial state.
reset(), sort(), {
get: function(num) {
var ret = "", base = 54;
num++;
do ret += chars[--num % base], num = Math.floor(num / base), base = 64;
while (num > 0)
return ret;
},
consider: function(str, delta) {
for(var i = str.length; --i >= 0;)frequency.set(str[i], frequency.get(str[i]) + delta);
},
reset,
sort
});
})();
AST_Node.prototype.size = function(compressor, stack) {
mangle_options = compressor && compressor.mangle_options;
let size = 0;
return walk_parent(this, (node, info)=>{
// Braceless arrow functions have fake "return" statements
if (size += node._size(info), node instanceof AST_Arrow && node.is_braceless()) return size += node.body[0].value._size(info), !0;
}, stack || compressor && compressor.stack), // just to save a bit of memory
mangle_options = void 0, size;
}, AST_Node.prototype._size = ()=>0, AST_Debugger.prototype._size = ()=>8, AST_Directive.prototype._size = function() {
// TODO string encoding stuff
return 2 + this.value.length;
};
const list_overhead = (array)=>array.length && array.length - 1;
AST_Block.prototype._size = function() {
return 2 + list_overhead(this.body);
}, AST_Toplevel.prototype._size = function() {
return list_overhead(this.body);
}, AST_EmptyStatement.prototype._size = ()=>1, AST_LabeledStatement.prototype._size = ()=>2, AST_Do.prototype._size = ()=>9, AST_While.prototype._size = ()=>7, AST_For.prototype._size = ()=>8, AST_ForIn.prototype._size = ()=>8, // AST_ForOf inherits ^
AST_With.prototype._size = ()=>6, AST_Expansion.prototype._size = ()=>3;
const lambda_modifiers = (func)=>+!!func.is_generator + 6 * !!func.async;
AST_Accessor.prototype._size = function() {
return lambda_modifiers(this) + 4 + list_overhead(this.argnames) + list_overhead(this.body);
}, AST_Function.prototype._size = function(info) {
return 2 * !!first_in_statement(info) + lambda_modifiers(this) + 12 + list_overhead(this.argnames) + list_overhead(this.body);
}, AST_Defun.prototype._size = function() {
return lambda_modifiers(this) + 13 + list_overhead(this.argnames) + list_overhead(this.body);
}, AST_Arrow.prototype._size = function() {
let args_and_arrow = 2 + list_overhead(this.argnames);
1 === this.argnames.length && this.argnames[0] instanceof AST_Symbol || (args_and_arrow += 2);
const body_overhead = this.is_braceless() ? 0 : list_overhead(this.body) + 2;
return lambda_modifiers(this) + args_and_arrow + body_overhead;
}, AST_Destructuring.prototype._size = ()=>2, AST_TemplateString.prototype._size = function() {
return 2 + 3 * Math.floor(this.segments.length / 2); /* "${}" */
}, AST_TemplateSegment.prototype._size = function() {
return this.value.length;
}, AST_Return.prototype._size = function() {
return this.value ? 7 : 6;
}, AST_Throw.prototype._size = ()=>6, AST_Break.prototype._size = function() {
return this.label ? 6 : 5;
}, AST_Continue.prototype._size = function() {
return this.label ? 9 : 8;
}, AST_If.prototype._size = ()=>4, AST_Switch.prototype._size = function() {
return 8 + list_overhead(this.body);
}, AST_Case.prototype._size = function() {
return 5 + list_overhead(this.body);
}, AST_Default.prototype._size = function() {
return 8 + list_overhead(this.body);
}, AST_Try.prototype._size = function() {
return 3 + list_overhead(this.body);
}, AST_Catch.prototype._size = function() {
let size = 7 + list_overhead(this.body);
return this.argname && (size += 2), size;
}, AST_Finally.prototype._size = function() {
return 7 + list_overhead(this.body);
};
/*#__INLINE__*/ const def_size = (size, def)=>size + list_overhead(def.definitions);
AST_Var.prototype._size = function() {
return def_size(4, this);
}, AST_Let.prototype._size = function() {
return def_size(4, this);
}, AST_Const.prototype._size = function() {
return def_size(6, this);
}, AST_VarDef.prototype._size = function() {
return +!!this.value;
}, AST_NameMapping.prototype._size = function() {
// foreign name isn't mangled
return 4 * !!this.name;
}, AST_Import.prototype._size = function() {
// import
let size = 6;
return this.imported_name && (size += 1), (this.imported_name || this.imported_names) && (size += 5), this.imported_names && (size += 2 + list_overhead(this.imported_names)), size;
}, AST_ImportMeta.prototype._size = ()=>11, AST_Export.prototype._size = function() {
let size = 7 + 8 * !!this.is_default;
return this.exported_value && (size += this.exported_value._size()), this.exported_names && // Braces and commas
(size += 2 + list_overhead(this.exported_names)), this.module_name && // "from "
(size += 5), size;
}, AST_Call.prototype._size = function() {
return this.optional ? 4 + list_overhead(this.args) : 2 + list_overhead(this.args);
}, AST_New.prototype._size = function() {
return 6 + list_overhead(this.args);
}, AST_Sequence.prototype._size = function() {
return list_overhead(this.expressions);
}, AST_Dot.prototype._size = function() {
return this.optional ? this.property.length + 2 : this.property.length + 1;
}, AST_DotHash.prototype._size = function() {
return this.optional ? this.property.length + 3 : this.property.length + 2;
}, AST_Sub.prototype._size = function() {
return this.optional ? 4 : 2;
}, AST_Unary.prototype._size = function() {
return "typeof" === this.operator ? 7 : "void" === this.operator ? 5 : this.operator.length;
}, AST_Binary.prototype._size = function(info) {
if ("in" === this.operator) return 4;
let size = this.operator.length;
return ("+" === this.operator || "-" === this.operator) && this.right instanceof AST_Unary && this.right.operator === this.operator && // 1+ +a > needs space between the +
(size += 1), this.needs_parens(info) && (size += 2), size;
}, AST_Conditional.prototype._size = ()=>3, AST_Array.prototype._size = function() {
return 2 + list_overhead(this.elements);
}, AST_Object.prototype._size = function(info) {
let base = 2;
return first_in_statement(info) && (base += 2), base + list_overhead(this.properties);
};
/*#__INLINE__*/ const key_size = (key)=>"string" == typeof key ? key.length : 0;
AST_ObjectKeyVal.prototype._size = function() {
return key_size(this.key) + 1;
};
/*#__INLINE__*/ const static_size = (is_static)=>7 * !!is_static;
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
***********************************************************************/ function merge_sequence(array, node) {
return node instanceof AST_Sequence ? array.push(...node.expressions) : array.push(node), array;
}
function make_sequence(orig, expressions) {
if (1 == expressions.length) return expressions[0];
if (0 == expressions.length) throw Error("trying to create a sequence with length zero!");
return make_node(AST_Sequence, orig, {
expressions: expressions.reduce(merge_sequence, [])
});
}
function make_node_from_constant(val, orig) {
switch(typeof val){
case "string":
return make_node(AST_String, orig, {
value: val
});
case "number":
if (isNaN(val)) return make_node(AST_NaN, orig);
if (isFinite(val)) return 1 / val < 0 ? make_node(AST_UnaryPrefix, orig, {
operator: "-",
expression: make_node(AST_Number, orig, {
value: -val
})
}) : make_node(AST_Number, orig, {
value: val
});
return val < 0 ? make_node(AST_UnaryPrefix, orig, {
operator: "-",
expression: make_node(AST_Infinity, orig)
}) : make_node(AST_Infinity, orig);
case "boolean":
return make_node(val ? AST_True : AST_False, orig);
case "undefined":
return make_node(AST_Undefined, orig);
default:
if (null === val) return make_node(AST_Null, orig, {
value: null
});
if (val instanceof RegExp) return make_node(AST_RegExp, orig, {
value: {
source: regexp_source_fix(val.source),
flags: val.flags
}
});
throw Error(string_template("Can't handle constant of type: {type}", {
type: typeof val
}));
}
}
function best_of_expression(ast1, ast2) {
return ast1.size() > ast2.size() ? ast2 : ast1;
}
/** Find which node is smaller, and return that */ function best_of(compressor, ast1, ast2) {
return first_in_statement(compressor) ? best_of_expression(make_node(AST_SimpleStatement, ast1, {
body: ast1
}), make_node(AST_SimpleStatement, ast2, {
body: ast2
})).body : best_of_expression(ast1, ast2);
}
/** Simplify an object property's key, if possible */ function get_simple_key(key) {
return key instanceof AST_Constant ? key.getValue() : key instanceof AST_UnaryPrefix && "void" == key.operator && key.expression instanceof AST_Constant ? void 0 : key;
}
function read_property(obj, key) {
if (!((key = get_simple_key(key)) instanceof AST_Node)) {
if (obj instanceof AST_Array) {
var value, elements = obj.elements;
if ("length" == key) return make_node_from_constant(elements.length, obj);
"number" == typeof key && key in elements && (value = elements[key]);
} else if (obj instanceof AST_Object) {
key = "" + key;
for(var props = obj.properties, i = props.length; --i >= 0;){
if (!(props[i] instanceof AST_ObjectKeyVal)) return;
value || props[i].key !== key || (value = props[i].value);
}
}
return value instanceof AST_SymbolRef && value.fixed_value() || value;
}
}
function has_break_or_continue(loop, parent) {
var found = !1, tw = new TreeWalker(function(node) {
return !!found || node instanceof AST_Scope || (node instanceof AST_LoopControl && tw.loopcontrol_target(node) === loop ? found = !0 : void 0);
});
return parent instanceof AST_LabeledStatement && tw.push(parent), tw.push(loop), loop.body.walk(tw), found;
}
// we shouldn't compress (1,func)(something) to
// func(something) because that changes the meaning of
// the func (becomes lexical instead of global).
function maintain_this_binding(parent, orig, val) {
if ((!(parent instanceof AST_UnaryPrefix) || "delete" != parent.operator) && (!(parent instanceof AST_Call) || parent.expression !== orig || !(val instanceof AST_PropAccess) && (!(val instanceof AST_SymbolRef) || "eval" != val.name))) return val;
{
const zero = make_node(AST_Number, orig, {
value: 0
});
return make_sequence(orig, [
zero,
val
]);
}
}
function is_func_expr(node) {
return node instanceof AST_Arrow || node instanceof AST_Function;
}
function is_iife_call(node) {
return(// Used to determine whether the node can benefit from negation.
// Not the case with arrow functions (you need an extra set of parens).
"Call" == node.TYPE && (node.expression instanceof AST_Function || is_iife_call(node.expression)));
}
AST_ObjectGetter.prototype._size = function() {
return 5 + static_size(this.static) + key_size(this.key);
}, AST_ObjectSetter.prototype._size = function() {
return 5 + static_size(this.static) + key_size(this.key);
}, AST_ConciseMethod.prototype._size = function() {
return static_size(this.static) + key_size(this.key) + lambda_modifiers(this);
}, AST_PrivateMethod.prototype._size = function() {
return AST_ConciseMethod.prototype._size.call(this) + 1;
}, AST_PrivateGetter.prototype._size = AST_PrivateSetter.prototype._size = function() {
return AST_ConciseMethod.prototype._size.call(this) + 4;
}, AST_Class.prototype._size = function() {
return (this.name ? 8 : 7) + 8 * !!this.extends;
}, AST_ClassProperty.prototype._size = function() {
return static_size(this.static) + ("string" == typeof this.key ? this.key.length + 2 : 0) + +!!this.value;
}, AST_ClassPrivateProperty.prototype._size = function() {
return AST_ClassProperty.prototype._size.call(this) + 1;
}, AST_Symbol.prototype._size = function() {
return !mangle_options || this.definition().unmangleable(mangle_options) ? this.name.length : 1;
}, // TODO take propmangle into account
AST_SymbolClassProperty.prototype._size = function() {
return this.name.length;
}, AST_SymbolRef.prototype._size = AST_SymbolDeclaration.prototype._size = function() {
const { name, thedef } = this;
return thedef && thedef.global ? name.length : "arguments" === name ? 9 : AST_Symbol.prototype._size.call(this);
}, AST_NewTarget.prototype._size = ()=>10, AST_SymbolImportForeign.prototype._size = function() {
return this.name.length;
}, AST_SymbolExportForeign.prototype._size = function() {
return this.name.length;
}, AST_This.prototype._size = ()=>4, AST_Super.prototype._size = ()=>5, AST_String.prototype._size = function() {
return this.value.length + 2;
}, AST_Number.prototype._size = function() {
const { value } = this;
return 0 === value ? 1 : value > 0 && Math.floor(value) === value ? Math.floor(Math.log10(value) + 1) : value.toString().length;
}, AST_BigInt.prototype._size = function() {
return this.value.length;
}, AST_RegExp.prototype._size = function() {
return this.value.toString().length;
}, AST_Null.prototype._size = ()=>4, AST_NaN.prototype._size = ()=>3, AST_Undefined.prototype._size = ()=>6, AST_Hole.prototype._size = ()=>0, AST_Infinity.prototype._size = ()=>8, AST_True.prototype._size = ()=>4, AST_False.prototype._size = ()=>5, AST_Await.prototype._size = ()=>6, AST_Yield.prototype._size = ()=>6;
const identifier_atom = makePredicate("Infinity NaN undefined");
function is_identifier_atom(node) {
return node instanceof AST_Infinity || node instanceof AST_NaN || node instanceof AST_Undefined;
}
/** Check if this is a SymbolRef node which has one def of a certain AST type */ function is_ref_of(ref, type) {
if (!(ref instanceof AST_SymbolRef)) return !1;
for(var orig = ref.definition().orig, i = orig.length; --i >= 0;)if (orig[i] instanceof type) return !0;
}
// Can we turn { block contents... } into just the block contents ?
// Not if one of these is inside.
function can_be_evicted_from_block(node) {
return !(node instanceof AST_DefClass || node instanceof AST_Defun || node instanceof AST_Let || node instanceof AST_Const || node instanceof AST_Export || node instanceof AST_Import);
}
function as_statement_array(thing) {
if (null === thing) return [];
if (thing instanceof AST_BlockStatement) return thing.body;
if (thing instanceof AST_EmptyStatement) return [];
if (thing instanceof AST_Statement) return [
thing
];
throw Error("Can't convert thing to statement array");
}
/** Check if a ref refers to the name of a function/class it's defined within */ function is_recursive_ref(compressor, def) {
for(var node, i = 0; node = compressor.parent(i); i++)if (node instanceof AST_Lambda || node instanceof AST_Class) {
var name = node.name;
if (name && name.definition() === def) return !0;
}
return !1;
}
const has_flag = (node, flag)=>node.flags & flag, set_flag = (node, flag)=>{
node.flags |= flag;
}, clear_flag = (node, flag)=>{
node.flags &= ~flag;
};
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
***********************************************************************/ // Lists of native methods, useful for `unsafe` option which assumes they exist.
// Note: Lots of methods and functions are missing here, in case they aren't pure
// or not available in all JS environments.
function make_nested_lookup(obj) {
const out = new Map();
for (var key of Object.keys(obj))out.set(key, makePredicate(obj[key]));
return (global_name, fname)=>{
const inner_map = out.get(global_name);
return null != inner_map && inner_map.has(fname);
};
}
// Objects which are safe to access without throwing or causing a side effect.
// Usually we'd check the `unsafe` option first but these are way too common for that
const pure_prop_access_globals = new Set([
"Number",
"String",
"Array",
"Object",
"Function",
"Promise"
]), object_methods = [
"constructor",
"toString",
"valueOf"
], is_pure_native_method = make_nested_lookup({
Array: [
"indexOf",
"join",
"lastIndexOf",
"slice",
...object_methods
],
Boolean: object_methods,
Function: object_methods,
Number: [
"toExponential",
"toFixed",
"toPrecision",
...object_methods
],
Object: object_methods,
RegExp: [
"test",
...object_methods
],
String: [
"charAt",
"charCodeAt",
"concat",
"indexOf",
"italics",
"lastIndexOf",
"match",
"replace",
"search",
"slice",
"split",
"substr",
"substring",
"toLowerCase",
"toUpperCase",
"trim",
...object_methods
]
}), is_pure_native_fn = make_nested_lookup({
Array: [
"isArray"
],
Math: [
"abs",
"acos",
"asin",
"atan",
"ceil",
"cos",
"exp",
"floor",
"log",
"round",
"sin",
"sqrt",
"tan",
"atan2",
"pow",
"max",
"min"
],
Number: [
"isFinite",
"isNaN"
],
Object: [
"create",
"getOwnPropertyDescriptor",
"getOwnPropertyNames",
"getPrototypeOf",
"isExtensible",
"isFrozen",
"isSealed",
"hasOwn",
"keys"
],
String: [
"fromCharCode"
]
}), is_pure_native_value = make_nested_lookup({
Math: [
"E",
"LN10",
"LN2",
"LOG2E",
"LOG10E",
"PI",
"SQRT1_2",
"SQRT2"
],
Number: [
"MAX_VALUE",
"MIN_VALUE",
"NaN",
"NEGATIVE_INFINITY",
"POSITIVE_INFINITY"
]
}), is_undeclared_ref = (node)=>node instanceof AST_SymbolRef && node.definition().undeclared, lazy_op = makePredicate("&& || ??"), unary_side_effects = makePredicate("delete ++ --");
function is_undefined(node, compressor) {
return has_flag(node, 0b00001000) || node instanceof AST_Undefined || node instanceof AST_UnaryPrefix && "void" == node.operator && !node.expression.has_side_effects(compressor);
}
// Is the node explicitly null or undefined.
function is_null_or_undefined(node, compressor) {
let fixed;
return node instanceof AST_Null || is_undefined(node, compressor) || node instanceof AST_SymbolRef && (fixed = node.definition().fixed) instanceof AST_Node && is_nullish(fixed, compressor);
}
// Find out if this expression is optionally chained from a base-point that we
// can statically analyze as null or undefined.
function is_nullish_shortcircuited(node, compressor) {
return node instanceof AST_PropAccess || node instanceof AST_Call ? node.optional && is_null_or_undefined(node.expression, compressor) || is_nullish_shortcircuited(node.expression, compressor) : node instanceof AST_Chain && is_nullish_shortcircuited(node.expression, compressor);
}
// Find out if something is == null, or can short circuit into nullish.
// Used to optimize ?. and ??
function is_nullish(node, compressor) {
return !!is_null_or_undefined(node, compressor) || is_nullish_shortcircuited(node, compressor);
}
function is_lhs(node, parent) {
return parent instanceof AST_Unary && unary_side_effects.has(parent.operator) ? parent.expression : parent instanceof AST_Assign && parent.left === node ? node : void 0;
}
!// methods to determine whether an expression has a boolean result type
function(def_is_boolean) {
const unary_bool = makePredicate("! delete"), binary_bool = makePredicate("in instanceof == != === !== < <= >= >");
def_is_boolean(AST_Node, return_false), def_is_boolean(AST_UnaryPrefix, function() {
return unary_bool.has(this.operator);
}), def_is_boolean(AST_Binary, function() {
return binary_bool.has(this.operator) || lazy_op.has(this.operator) && this.left.is_boolean() && this.right.is_boolean();
}), def_is_boolean(AST_Conditional, function() {
return this.consequent.is_boolean() && this.alternative.is_boolean();
}), def_is_boolean(AST_Assign, function() {
return "=" == this.operator && this.right.is_boolean();
}), def_is_boolean(AST_Sequence, function() {
return this.tail_node().is_boolean();
}), def_is_boolean(AST_True, return_true), def_is_boolean(AST_False, return_true);
}(function(node, func) {
node.DEFMETHOD("is_boolean", func);
}), // methods to determine if an expression has a numeric result type
function(def_is_number) {
def_is_number(AST_Node, return_false), def_is_number(AST_Number, return_true);
const unary = makePredicate("+ - ~ ++ --");
def_is_number(AST_Unary, function() {
return unary.has(this.operator);
});
const numeric_ops = makePredicate("- * / % & | ^ << >> >>>");
def_is_number(AST_Binary, function(compressor) {
return numeric_ops.has(this.operator) || "+" == this.operator && this.left.is_number(compressor) && this.right.is_number(compressor);
}), def_is_number(AST_Assign, function(compressor) {
return numeric_ops.has(this.operator.slice(0, -1)) || "=" == this.operator && this.right.is_number(compressor);
}), def_is_number(AST_Sequence, function(compressor) {
return this.tail_node().is_number(compressor);
}), def_is_number(AST_Conditional, function(compressor) {
return this.consequent.is_number(compressor) && this.alternative.is_number(compressor);
});
}(function(node, func) {
node.DEFMETHOD("is_number", func);
}), (def_is_string = function(node, func) {
node.DEFMETHOD("is_string", func);
})(AST_Node, return_false), def_is_string(AST_String, return_true), def_is_string(AST_TemplateString, return_true), def_is_string(AST_UnaryPrefix, function() {
return "typeof" == this.operator;
}), def_is_string(AST_Binary, function(compressor) {
return "+" == this.operator && (this.left.is_string(compressor) || this.right.is_string(compressor));
}), def_is_string(AST_Assign, function(compressor) {
return ("=" == this.operator || "+=" == this.operator) && this.right.is_string(compressor);
}), def_is_string(AST_Sequence, function(compressor) {
return this.tail_node().is_string(compressor);
}), def_is_string(AST_Conditional, function(compressor) {
return this.consequent.is_string(compressor) && this.alternative.is_string(compressor);
}), // Determine if expression might cause side effects
// If there's a possibility that a node may change something when it's executed, this returns true
function(def_has_side_effects) {
function any(list, compressor) {
for(var i = list.length; --i >= 0;)if (list[i].has_side_effects(compressor)) return !0;
return !1;
}
def_has_side_effects(AST_Node, return_true), def_has_side_effects(AST_EmptyStatement, return_false), def_has_side_effects(AST_Constant, return_false), def_has_side_effects(AST_This, return_false), def_has_side_effects(AST_Block, function(compressor) {
return any(this.body, compressor);
}), def_has_side_effects(AST_Call, function(compressor) {
return !!(!this.is_callee_pure(compressor) && (!this.expression.is_call_pure(compressor) || this.expression.has_side_effects(compressor))) || any(this.args, compressor);
}), def_has_side_effects(AST_Switch, function(compressor) {
return this.expression.has_side_effects(compressor) || any(this.body, compressor);
}), def_has_side_effects(AST_Case, function(compressor) {
return this.expression.has_side_effects(compressor) || any(this.body, compressor);
}), def_has_side_effects(AST_Try, function(compressor) {
return any(this.body, compressor) || this.bcatch && this.bcatch.has_side_effects(compressor) || this.bfinally && this.bfinally.has_side_effects(compressor);
}), def_has_side_effects(AST_If, function(compressor) {
return this.condition.has_side_effects(compressor) || this.body && this.body.has_side_effects(compressor) || this.alternative && this.alternative.has_side_effects(compressor);
}), def_has_side_effects(AST_LabeledStatement, function(compressor) {
return this.body.has_side_effects(compressor);
}), def_has_side_effects(AST_SimpleStatement, function(compressor) {
return this.body.has_side_effects(compressor);
}), def_has_side_effects(AST_Lambda, return_false), def_has_side_effects(AST_Class, function(compressor) {
return !!(this.extends && this.extends.has_side_effects(compressor)) || any(this.properties, compressor);
}), def_has_side_effects(AST_Binary, function(compressor) {
return this.left.has_side_effects(compressor) || this.right.has_side_effects(compressor);
}), def_has_side_effects(AST_Assign, return_true), def_has_side_effects(AST_Conditional, function(compressor) {
return this.condition.has_side_effects(compressor) || this.consequent.has_side_effects(compressor) || this.alternative.has_side_effects(compressor);
}), def_has_side_effects(AST_Unary, function(compressor) {
return unary_side_effects.has(this.operator) || this.expression.has_side_effects(compressor);
}), def_has_side_effects(AST_SymbolRef, function(compressor) {
return !this.is_declared(compressor) && !pure_prop_access_globals.has(this.name);
}), def_has_side_effects(AST_SymbolClassProperty, return_false), def_has_side_effects(AST_SymbolDeclaration, return_false), def_has_side_effects(AST_Object, function(compressor) {
return any(this.properties, compressor);
}), def_has_side_effects(AST_ObjectProperty, function(compressor) {
return this.computed_key() && this.key.has_side_effects(compressor) || this.value && this.value.has_side_effects(compressor);
}), def_has_side_effects(AST_ClassProperty, function(compressor) {
return this.computed_key() && this.key.has_side_effects(compressor) || this.static && this.value && this.value.has_side_effects(compressor);
}), def_has_side_effects(AST_ConciseMethod, function(compressor) {
return this.computed_key() && this.key.has_side_effects(compressor);
}), def_has_side_effects(AST_ObjectGetter, function(compressor) {
return this.computed_key() && this.key.has_side_effects(compressor);
}), def_has_side_effects(AST_ObjectSetter, function(compressor) {
return this.computed_key() && this.key.has_side_effects(compressor);
}), def_has_side_effects(AST_Array, function(compressor) {
return any(this.elements, compressor);
}), def_has_side_effects(AST_Dot, function(compressor) {
return !is_nullish(this, compressor) && (!this.optional && this.expression.may_throw_on_access(compressor) || this.expression.has_side_effects(compressor));
}), def_has_side_effects(AST_Sub, function(compressor) {
return !is_nullish(this, compressor) && (!this.optional && this.expression.may_throw_on_access(compressor) || this.expression.has_side_effects(compressor) || this.property.has_side_effects(compressor));
}), def_has_side_effects(AST_Chain, function(compressor) {
return this.expression.has_side_effects(compressor);
}), def_has_side_effects(AST_Sequence, function(compressor) {
return any(this.expressions, compressor);
}), def_has_side_effects(AST_Definitions, function(compressor) {
return any(this.definitions, compressor);
}), def_has_side_effects(AST_VarDef, function() {
return this.value;
}), def_has_side_effects(AST_TemplateSegment, return_false), def_has_side_effects(AST_TemplateString, function(compressor) {
return any(this.segments, compressor);
});
}(function(node, func) {
node.DEFMETHOD("has_side_effects", func);
}), // determine if expression may throw
function(def_may_throw) {
function any(list, compressor) {
for(var i = list.length; --i >= 0;)if (list[i].may_throw(compressor)) return !0;
return !1;
}
def_may_throw(AST_Node, return_true), def_may_throw(AST_Constant, return_false), def_may_throw(AST_EmptyStatement, return_false), def_may_throw(AST_Lambda, return_false), def_may_throw(AST_SymbolDeclaration, return_false), def_may_throw(AST_This, return_false), def_may_throw(AST_Class, function(compressor) {
return !!(this.extends && this.extends.may_throw(compressor)) || any(this.properties, compressor);
}), def_may_throw(AST_Array, function(compressor) {
return any(this.elements, compressor);
}), def_may_throw(AST_Assign, function(compressor) {
return !!this.right.may_throw(compressor) || (!!compressor.has_directive("use strict") || "=" != this.operator || !(this.left instanceof AST_SymbolRef)) && this.left.may_throw(compressor);
}), def_may_throw(AST_Binary, function(compressor) {
return this.left.may_throw(compressor) || this.right.may_throw(compressor);
}), def_may_throw(AST_Block, function(compressor) {
return any(this.body, compressor);
}), def_may_throw(AST_Call, function(compressor) {
return !is_nullish(this, compressor) && (!!any(this.args, compressor) || !this.is_callee_pure(compressor) && (!!this.expression.may_throw(compressor) || !(this.expression instanceof AST_Lambda) || any(this.expression.body, compressor)));
}), def_may_throw(AST_Case, function(compressor) {
return this.expression.may_throw(compressor) || any(this.body, compressor);
}), def_may_throw(AST_Conditional, function(compressor) {
return this.condition.may_throw(compressor) || this.consequent.may_throw(compressor) || this.alternative.may_throw(compressor);
}), def_may_throw(AST_Definitions, function(compressor) {
return any(this.definitions, compressor);
}), def_may_throw(AST_If, function(compressor) {
return this.condition.may_throw(compressor) || this.body && this.body.may_throw(compressor) || this.alternative && this.alternative.may_throw(compressor);
}), def_may_throw(AST_LabeledStatement, function(compressor) {
return this.body.may_throw(compressor);
}), def_may_throw(AST_Object, function(compressor) {
return any(this.properties, compressor);
}), def_may_throw(AST_ObjectProperty, function(compressor) {
// TODO key may throw too
return !!this.value && this.value.may_throw(compressor);
}), def_may_throw(AST_ClassProperty, function(compressor) {
return this.computed_key() && this.key.may_throw(compressor) || this.static && this.value && this.value.may_throw(compressor);
}), def_may_throw(AST_ConciseMethod, function(compressor) {
return this.computed_key() && this.key.may_throw(compressor);
}), def_may_throw(AST_ObjectGetter, function(compressor) {
return this.computed_key() && this.key.may_throw(compressor);
}), def_may_throw(AST_ObjectSetter, function(compressor) {
return this.computed_key() && this.key.may_throw(compressor);
}), def_may_throw(AST_Return, function(compressor) {
return this.value && this.value.may_throw(compressor);
}), def_may_throw(AST_Sequence, function(compressor) {
return any(this.expressions, compressor);
}), def_may_throw(AST_SimpleStatement, function(compressor) {
return this.body.may_throw(compressor);
}), def_may_throw(AST_Dot, function(compressor) {
return !is_nullish(this, compressor) && (!this.optional && this.expression.may_throw_on_access(compressor) || this.expression.may_throw(compressor));
}), def_may_throw(AST_Sub, function(compressor) {
return !is_nullish(this, compressor) && (!this.optional && this.expression.may_throw_on_access(compressor) || this.expression.may_throw(compressor) || this.property.may_throw(compressor));
}), def_may_throw(AST_Chain, function(compressor) {
return this.expression.may_throw(compressor);
}), def_may_throw(AST_Switch, function(compressor) {
return this.expression.may_throw(compressor) || any(this.body, compressor);
}), def_may_throw(AST_SymbolRef, function(compressor) {
return !this.is_declared(compressor) && !pure_prop_access_globals.has(this.name);
}), def_may_throw(AST_SymbolClassProperty, return_false), def_may_throw(AST_Try, function(compressor) {
return this.bcatch ? this.bcatch.may_throw(compressor) : any(this.body, compressor) || this.bfinally && this.bfinally.may_throw(compressor);
}), def_may_throw(AST_Unary, function(compressor) {
return ("typeof" != this.operator || !(this.expression instanceof AST_SymbolRef)) && this.expression.may_throw(compressor);
}), def_may_throw(AST_VarDef, function(compressor) {
return !!this.value && this.value.may_throw(compressor);
});
}(function(node, func) {
node.DEFMETHOD("may_throw", func);
}), // determine if expression is constant
function(def_is_constant_expression) {
function all_refs_local(scope) {
let result = !0;
return walk(this, (node)=>{
if (node instanceof AST_SymbolRef) {
if (has_flag(this, 0b00010000)) return result = !1, walk_abort;
var def = node.definition();
if (member(def, this.enclosed) && !this.variables.has(def.name)) {
if (scope) {
var scope_def = scope.find_variable(node);
if (def.undeclared ? !scope_def : scope_def === def) return result = "f", !0;
}
return result = !1, walk_abort;
}
return !0;
}
if (node instanceof AST_This && this instanceof AST_Arrow) return(// TODO check arguments too!
result = !1, walk_abort);
}), result;
}
def_is_constant_expression(AST_Node, return_false), def_is_constant_expression(AST_Constant, return_true), def_is_constant_expression(AST_Class, function(scope) {
if (this.extends && !this.extends.is_constant_expression(scope)) return !1;
for (const prop of this.properties)if (prop.computed_key() && !prop.key.is_constant_expression(scope) || prop.static && prop.value && !prop.value.is_constant_expression(scope)) return !1;
return all_refs_local.call(this, scope);
}), def_is_constant_expression(AST_Lambda, all_refs_local), def_is_constant_expression(AST_Unary, function() {
return this.expression.is_constant_expression();
}), def_is_constant_expression(AST_Binary, function() {
return this.left.is_constant_expression() && this.right.is_constant_expression();
}), def_is_constant_expression(AST_Array, function() {
return this.elements.every((l)=>l.is_constant_expression());
}), def_is_constant_expression(AST_Object, function() {
return this.properties.every((l)=>l.is_constant_expression());
}), def_is_constant_expression(AST_ObjectProperty, function() {
return !!(!(this.key instanceof AST_Node) && this.value && this.value.is_constant_expression());
});
}(function(node, func) {
node.DEFMETHOD("is_constant_expression", func);
}), // may_throw_on_access()
// returns true if this node may be null, undefined or contain `AST_Accessor`
function(def_may_throw_on_access) {
function is_strict(compressor) {
return /strict/.test(compressor.option("pure_getters"));
}
AST_Node.DEFMETHOD("may_throw_on_access", function(compressor) {
return !compressor.option("pure_getters") || this._dot_throw(compressor);
}), def_may_throw_on_access(AST_Node, is_strict), def_may_throw_on_access(AST_Null, return_true), def_may_throw_on_access(AST_Undefined, return_true), def_may_throw_on_access(AST_Constant, return_false), def_may_throw_on_access(AST_Array, return_false), def_may_throw_on_access(AST_Object, function(compressor) {
if (!is_strict(compressor)) return !1;
for(var i = this.properties.length; --i >= 0;)if (this.properties[i]._dot_throw(compressor)) return !0;
return !1;
}), // Do not be as strict with classes as we are with objects.
// Hopefully the community is not going to abuse static getters and setters.
// https://github.com/terser/terser/issues/724#issuecomment-643655656
def_may_throw_on_access(AST_Class, return_false), def_may_throw_on_access(AST_ObjectProperty, return_false), def_may_throw_on_access(AST_ObjectGetter, return_true), def_may_throw_on_access(AST_Expansion, function(compressor) {
return this.expression._dot_throw(compressor);
}), def_may_throw_on_access(AST_Function, return_false), def_may_throw_on_access(AST_Arrow, return_false), def_may_throw_on_access(AST_UnaryPostfix, return_false), def_may_throw_on_access(AST_UnaryPrefix, function() {
return "void" == this.operator;
}), def_may_throw_on_access(AST_Binary, function(compressor) {
return ("&&" == this.operator || "||" == this.operator || "??" == this.operator) && (this.left._dot_throw(compressor) || this.right._dot_throw(compressor));
}), def_may_throw_on_access(AST_Assign, function(compressor) {
return !!this.logical || "=" == this.operator && this.right._dot_throw(compressor);
}), def_may_throw_on_access(AST_Conditional, function(compressor) {
return this.consequent._dot_throw(compressor) || this.alternative._dot_throw(compressor);
}), def_may_throw_on_access(AST_Dot, function(compressor) {
return !!is_strict(compressor) && ("prototype" != this.property || !(this.expression instanceof AST_Function || this.expression instanceof AST_Class));
}), def_may_throw_on_access(AST_Chain, function(compressor) {
return this.expression._dot_throw(compressor);
}), def_may_throw_on_access(AST_Sequence, function(compressor) {
return this.tail_node()._dot_throw(compressor);
}), def_may_throw_on_access(AST_SymbolRef, function(compressor) {
if ("arguments" === this.name) return !1;
if (has_flag(this, 0b00001000)) return !0;
if (!is_strict(compressor) || is_undeclared_ref(this) && this.is_declared(compressor) || this.is_immutable()) return !1;
var fixed = this.fixed_value();
return !fixed || fixed._dot_throw(compressor);
});
}(function(node, func) {
node.DEFMETHOD("_dot_throw", func);
}), def_find_defs = function(node, func) {
node.DEFMETHOD("_find_defs", func);
}, AST_Toplevel.DEFMETHOD("resolve_defines", function(compressor) {
return compressor.option("global_defs") ? (this.figure_out_scope({
ie8: compressor.option("ie8")
}), this.transform(new TreeTransformer(function(node) {
var def = node._find_defs(compressor, "");
if (def) {
for(var parent, level = 0, child = node; (parent = this.parent(level++)) && parent instanceof AST_PropAccess && parent.expression === child;)child = parent;
if (is_lhs(child, parent)) return;
return def;
}
}))) : this;
}), def_find_defs(AST_Node, noop), def_find_defs(AST_Chain, function(compressor, suffix) {
return this.expression._find_defs(compressor, suffix);
}), def_find_defs(AST_Dot, function(compressor, suffix) {
return this.expression._find_defs(compressor, "." + this.property + suffix);
}), def_find_defs(AST_SymbolDeclaration, function() {
if (!this.global()) return;
}), def_find_defs(AST_SymbolRef, function(compressor, suffix) {
if (this.global()) {
var defines = compressor.option("global_defs"), name = this.name + suffix;
if (HOP(defines, name)) return function to_node(value, orig) {
if (value instanceof AST_Node) return value instanceof AST_Constant || // Value may be a function, an array including functions and even a complex assign / block expression,
// so it should never be shared in different places.
// Otherwise wrong information may be used in the compression phase
(value = value.clone(!0)), make_node(value.CTOR, orig, value);
if (Array.isArray(value)) return make_node(AST_Array, orig, {
elements: value.map(function(value) {
return to_node(value, orig);
})
});
if (value && "object" == typeof value) {
var props = [];
for(var key in value)HOP(value, key) && props.push(make_node(AST_ObjectKeyVal, orig, {
key: key,
value: to_node(value[key], orig)
}));
return make_node(AST_Object, orig, {
properties: props
});
}
return make_node_from_constant(value, orig);
}(defines[name], this);
}
}), // method to negate an expression
function(def_negate) {
function basic_negation(exp) {
return make_node(AST_UnaryPrefix, exp, {
operator: "!",
expression: exp
});
}
function best(orig, alt, first_in_statement) {
var negated = basic_negation(orig);
if (first_in_statement) {
var stat = make_node(AST_SimpleStatement, alt, {
body: alt
});
return best_of_expression(negated, stat) === stat ? alt : negated;
}
return best_of_expression(negated, alt);
}
def_negate(AST_Node, function() {
return basic_negation(this);
}), def_negate(AST_Statement, function() {
throw Error("Cannot negate a statement");
}), def_negate(AST_Function, function() {
return basic_negation(this);
}), def_negate(AST_Arrow, function() {
return basic_negation(this);
}), def_negate(AST_UnaryPrefix, function() {
return "!" == this.operator ? this.expression : basic_negation(this);
}), def_negate(AST_Sequence, function(compressor) {
var expressions = this.expressions.slice();
return expressions.push(expressions.pop().negate(compressor)), make_sequence(this, expressions);
}), def_negate(AST_Conditional, function(compressor, first_in_statement) {
var self1 = this.clone();
return self1.consequent = self1.consequent.negate(compressor), self1.alternative = self1.alternative.negate(compressor), best(this, self1, first_in_statement);
}), def_negate(AST_Binary, function(compressor, first_in_statement) {
var self1 = this.clone(), op = this.operator;
if (compressor.option("unsafe_comps")) switch(op){
case "<=":
return self1.operator = ">", self1;
case "<":
return self1.operator = ">=", self1;
case ">=":
return self1.operator = "<", self1;
case ">":
return self1.operator = "<=", self1;
}
switch(op){
case "==":
return self1.operator = "!=", self1;
case "!=":
return self1.operator = "==", self1;
case "===":
return self1.operator = "!==", self1;
case "!==":
return self1.operator = "===", self1;
case "&&":
return self1.operator = "||", self1.left = self1.left.negate(compressor, first_in_statement), self1.right = self1.right.negate(compressor), best(this, self1, first_in_statement);
case "||":
return self1.operator = "&&", self1.left = self1.left.negate(compressor, first_in_statement), self1.right = self1.right.negate(compressor), best(this, self1, first_in_statement);
}
return basic_negation(this);
});
}(function(node, func) {
node.DEFMETHOD("negate", function(compressor, first_in_statement) {
return func.call(this, compressor, first_in_statement);
});
});
// Is the callee of this function pure?
var global_pure_fns = makePredicate("Boolean decodeURI decodeURIComponent Date encodeURI encodeURIComponent Error escape EvalError isFinite isNaN Number Object parseFloat parseInt RangeError ReferenceError String SyntaxError TypeError unescape URIError");
AST_Call.DEFMETHOD("is_callee_pure", function(compressor) {
if (compressor.option("unsafe")) {
var expr = this.expression, first_arg = this.args && this.args[0] && this.args[0].evaluate(compressor);
if (expr.expression && "hasOwnProperty" === expr.expression.name && (null == first_arg || first_arg.thedef && first_arg.thedef.undeclared)) return !1;
if (is_undeclared_ref(expr) && global_pure_fns.has(expr.name) || expr instanceof AST_Dot && is_undeclared_ref(expr.expression) && is_pure_native_fn(expr.expression.name, expr.property)) return !0;
}
return !!has_annotation(this, _PURE) || !compressor.pure_funcs(this);
}), // If I call this, is it a pure function?
AST_Node.DEFMETHOD("is_call_pure", return_false), AST_Dot.DEFMETHOD("is_call_pure", function(compressor) {
let native_obj;
if (!compressor.option("unsafe")) return;
const expr = this.expression;
return expr instanceof AST_Array ? native_obj = "Array" : expr.is_boolean() ? native_obj = "Boolean" : expr.is_number(compressor) ? native_obj = "Number" : expr instanceof AST_RegExp ? native_obj = "RegExp" : expr.is_string(compressor) ? native_obj = "String" : this.may_throw_on_access(compressor) || (native_obj = "Object"), null != native_obj && is_pure_native_method(native_obj, this.property);
});
// tell me if a statement aborts
const aborts = (thing)=>thing && thing.aborts();
function is_modified(compressor, tw, node, value, level, immutable) {
var parent = tw.parent(level), lhs = is_lhs(node, parent);
if (lhs) return lhs;
if (!immutable && parent instanceof AST_Call && parent.expression === node && !(value instanceof AST_Arrow) && !(value instanceof AST_Class) && !parent.is_callee_pure(compressor) && (!(value instanceof AST_Function) || !(parent instanceof AST_New) && value.contains_this())) return !0;
if (parent instanceof AST_Array) return is_modified(compressor, tw, parent, parent, level + 1);
if (parent instanceof AST_ObjectKeyVal && node === parent.value) {
var obj = tw.parent(level + 1);
return is_modified(compressor, tw, obj, obj, level + 2);
}
if (parent instanceof AST_PropAccess && parent.expression === node) {
var prop = read_property(value, parent.property);
return !immutable && is_modified(compressor, tw, parent, prop, level + 1);
}
}
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
***********************************************************************/ // methods to evaluate a constant expression
function def_eval(node, func) {
node.DEFMETHOD("_eval", func);
}
!function(def_aborts) {
function block_aborts() {
for(var i = 0; i < this.body.length; i++)if (aborts(this.body[i])) return this.body[i];
return null;
}
def_aborts(AST_Statement, return_null), def_aborts(AST_Jump, return_this), def_aborts(AST_Import, function() {
return null;
}), def_aborts(AST_BlockStatement, block_aborts), def_aborts(AST_SwitchBranch, block_aborts), def_aborts(AST_If, function() {
return this.alternative && aborts(this.body) && aborts(this.alternative) && this;
});
}(function(node, func) {
node.DEFMETHOD("aborts", func);
});
// Used to propagate a nullish short-circuit signal upwards through the chain.
const nullish = Symbol("This AST_Chain is nullish");
// If the node has been successfully reduced to a constant,
// then its value is returned; otherwise the element itself
// is returned.
// They can be distinguished as constant value is never a
// descendant of AST_Node.
AST_Node.DEFMETHOD("evaluate", function(compressor) {
if (!compressor.option("evaluate")) return this;
var val = this._eval(compressor, 1);
return !val || val instanceof RegExp ? val : "function" == typeof val || "object" == typeof val || val == nullish ? this : val;
});
var unaryPrefix = makePredicate("! ~ - + void");
AST_Node.DEFMETHOD("is_constant", function() {
return(// Accomodate when compress option evaluate=false
// as well as the common constant expressions !0 and -1
this instanceof AST_Constant ? !(this instanceof AST_RegExp) : this instanceof AST_UnaryPrefix && this.expression instanceof AST_Constant && unaryPrefix.has(this.operator));
}), def_eval(AST_Statement, function() {
throw Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start));
}), def_eval(AST_Lambda, return_this), def_eval(AST_Class, return_this), def_eval(AST_Node, return_this), def_eval(AST_Constant, function() {
return this.getValue();
}), def_eval(AST_BigInt, return_this), def_eval(AST_RegExp, function(compressor) {
let evaluated = compressor.evaluated_regexps.get(this);
if (void 0 === evaluated) {
try {
evaluated = (0, eval)(this.print_to_string());
} catch (e) {
evaluated = null;
}
compressor.evaluated_regexps.set(this, evaluated);
}
return evaluated || this;
}), def_eval(AST_TemplateString, function() {
return 1 !== this.segments.length ? this : this.segments[0].value;
}), def_eval(AST_Function, function(compressor) {
if (compressor.option("unsafe")) {
var fn = function() {};
return fn.node = this, fn.toString = ()=>this.print_to_string(), fn;
}
return this;
}), def_eval(AST_Array, function(compressor, depth) {
if (compressor.option("unsafe")) {
for(var elements = [], i = 0, len = this.elements.length; i < len; i++){
var element = this.elements[i], value = element._eval(compressor, depth);
if (element === value) return this;
elements.push(value);
}
return elements;
}
return this;
}), def_eval(AST_Object, function(compressor, depth) {
if (compressor.option("unsafe")) {
for(var val = {}, i = 0, len = this.properties.length; i < len; i++){
var prop = this.properties[i];
if (prop instanceof AST_Expansion) return this;
var key = prop.key;
if (key instanceof AST_Symbol) key = key.name;
else if (key instanceof AST_Node && (key = key._eval(compressor, depth)) === prop.key) return this;
if ("function" == typeof Object.prototype[key] || !(prop.value instanceof AST_Function) && (val[key] = prop.value._eval(compressor, depth), val[key] === prop.value)) return this;
}
return val;
}
return this;
});
var non_converting_unary = makePredicate("! typeof void");
def_eval(AST_UnaryPrefix, function(compressor, depth) {
var e = this.expression;
// Function would be evaluated to an array and so typeof would
// incorrectly return 'object'. Hence making is a special case.
if (compressor.option("typeofs") && "typeof" == this.operator && (e instanceof AST_Lambda || e instanceof AST_SymbolRef && e.fixed_value() instanceof AST_Lambda)) return "function";
if (!non_converting_unary.has(this.operator) && depth++, (e = e._eval(compressor, depth)) === this.expression) return this;
switch(this.operator){
case "!":
return !e;
case "typeof":
// typeof <RegExp> returns "object" or "function" on different platforms
// so cannot evaluate reliably
if (e instanceof RegExp) break;
return typeof e;
case "void":
return;
case "~":
return ~e;
case "-":
return -e;
case "+":
return +e;
}
return this;
});
var non_converting_binary = makePredicate("&& || ?? === !==");
const identity_comparison = makePredicate("== != === !=="), has_identity = (value)=>"object" == typeof value || "function" == typeof value || "symbol" == typeof value;
def_eval(AST_Binary, function(compressor, depth) {
!non_converting_binary.has(this.operator) && depth++;
var result, left = this.left._eval(compressor, depth);
if (left === this.left) return this;
var right = this.right._eval(compressor, depth);
if (right === this.right || null != left && null != right && identity_comparison.has(this.operator) && has_identity(left) && has_identity(right) && typeof left == typeof right) return this;
switch(this.operator){
case "&&":
result = left && right;
break;
case "||":
result = left || right;
break;
case "??":
result = null != left ? left : right;
break;
case "|":
result = left | right;
break;
case "&":
result = left & right;
break;
case "^":
result = left ^ right;
break;
case "+":
result = left + right;
break;
case "*":
result = left * right;
break;
case "**":
result = Math.pow(left, right);
break;
case "/":
result = left / right;
break;
case "%":
result = left % right;
break;
case "-":
result = left - right;
break;
case "<<":
result = left << right;
break;
case ">>":
result = left >> right;
break;
case ">>>":
result = left >>> right;
break;
case "==":
result = left == right;
break;
case "===":
result = left === right;
break;
case "!=":
result = left != right;
break;
case "!==":
result = left !== right;
break;
case "<":
result = left < right;
break;
case "<=":
result = left <= right;
break;
case ">":
result = left > right;
break;
case ">=":
result = left >= right;
break;
default:
return this;
}
return isNaN(result) && compressor.find_parent(AST_With) ? this : result;
}), def_eval(AST_Conditional, function(compressor, depth) {
var condition = this.condition._eval(compressor, depth);
if (condition === this.condition) return this;
var node = condition ? this.consequent : this.alternative, value = node._eval(compressor, depth);
return value === node ? this : value;
});
// Set of AST_SymbolRef which are currently being evaluated.
// Avoids infinite recursion of ._eval()
const reentrant_ref_eval = new Set();
def_eval(AST_SymbolRef, function(compressor, depth) {
if (reentrant_ref_eval.has(this)) return this;
var fixed = this.fixed_value();
if (!fixed) return this;
reentrant_ref_eval.add(this);
const value = fixed._eval(compressor, depth);
if (reentrant_ref_eval.delete(this), value === fixed) return this;
if (value && "object" == typeof value) {
var escaped = this.definition().escaped;
if (escaped && depth > escaped) return this;
}
return value;
});
const global_objs = {
Array,
Math,
Number,
Object,
String
}, regexp_flags = new Set([
"dotAll",
"global",
"ignoreCase",
"multiline",
"sticky",
"unicode"
]);
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
***********************************************************************/ // AST_Node#drop_side_effect_free() gets called when we don't care about the value,
// only about side effects. We'll be defining this method for each node type in this module
//
// Examples:
// foo++ -> foo++
// 1 + func() -> func()
// 10 -> (nothing)
// knownPureFunc(foo++) -> foo++
function def_drop_side_effect_free(node, func) {
node.DEFMETHOD("drop_side_effect_free", func);
}
// Drop side-effect-free elements from an array of expressions.
// Returns an array of expressions with side-effects or null
// if all elements were dropped. Note: original array may be
// returned if nothing changed.
function trim(nodes, compressor, first_in_statement) {
var len = nodes.length;
if (!len) return null;
for(var ret = [], changed = !1, i = 0; i < len; i++){
var node = nodes[i].drop_side_effect_free(compressor, first_in_statement);
changed |= node !== nodes[i], node && (ret.push(node), first_in_statement = !1);
}
return changed ? ret.length ? ret : null : nodes;
}
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
***********************************************************************/ // Define the method AST_Node#reduce_vars, which goes through the AST in
// execution order to perform basic flow analysis
function def_reduce_vars(node, func) {
node.DEFMETHOD("reduce_vars", func);
}
function reset_def(compressor, def) {
def.assignments = 0, def.chained = !1, def.direct_access = !1, def.escaped = 0, def.recursive_refs = 0, def.references = [], def.single_use = void 0, def.scope.pinned() ? def.fixed = !1 : def.orig[0] instanceof AST_SymbolConst || !compressor.exposed(def) ? def.fixed = def.init : def.fixed = !1;
}
function reset_variables(tw, compressor, node) {
node.variables.forEach(function(def) {
reset_def(compressor, def), null === def.fixed ? (tw.defs_to_safe_ids.set(def.id, tw.safe_ids), mark(tw, def, !0)) : def.fixed && (tw.loop_ids.set(def.id, tw.in_loop), mark(tw, def, !0));
});
}
function reset_block_variables(compressor, node) {
node.block_scope && node.block_scope.variables.forEach((def)=>{
reset_def(compressor, def);
});
}
function push(tw) {
tw.safe_ids = Object.create(tw.safe_ids);
}
function pop(tw) {
tw.safe_ids = Object.getPrototypeOf(tw.safe_ids);
}
function mark(tw, def, safe) {
tw.safe_ids[def.id] = safe;
}
function safe_to_read(tw, def) {
if ("m" == def.single_use) return !1;
if (tw.safe_ids[def.id]) {
if (null == def.fixed) {
var orig = def.orig[0];
if (orig instanceof AST_SymbolFunarg || "arguments" == orig.name) return !1;
def.fixed = make_node(AST_Undefined, orig);
}
return !0;
}
return def.fixed instanceof AST_Defun;
}
function safe_to_assign(tw, def, scope, value) {
let def_safe_ids;
return void 0 === def.fixed || (null === def.fixed && (def_safe_ids = tw.defs_to_safe_ids.get(def.id)) ? (def_safe_ids[def.id] = !1, tw.defs_to_safe_ids.delete(def.id), !0) : !!(HOP(tw.safe_ids, def.id) && safe_to_read(tw, def)) && !1 !== def.fixed && (null == def.fixed || !!value && !(def.references.length > def.assignments)) && (def.fixed instanceof AST_Defun ? value instanceof AST_Node && def.fixed.parent_scope === scope : def.orig.every((sym)=>!(sym instanceof AST_SymbolConst || sym instanceof AST_SymbolDefun || sym instanceof AST_SymbolLambda))));
}
// A definition "escapes" when its value can leave the point of use.
// Example: `a = b || c`
// In this example, "b" and "c" are escaping, because they're going into "a"
//
// def.escaped is != 0 when it escapes.
//
// When greater than 1, it means that N chained properties will be read off
// of that def before an escape occurs. This is useful for evaluating
// property accesses, where you need to know when to stop.
function mark_escaped(tw, d, scope, node, value, level = 0, depth = 1) {
var parent = tw.parent(level);
if (!(value && (value.is_constant() || value instanceof AST_ClassExpression))) {
if (parent instanceof AST_Assign && ("=" === parent.operator || parent.logical) && node === parent.right || parent instanceof AST_Call && (node !== parent.expression || parent instanceof AST_New) || parent instanceof AST_Exit && node === parent.value && node.scope !== d.scope || parent instanceof AST_VarDef && node === parent.value || parent instanceof AST_Yield && node === parent.value && node.scope !== d.scope) {
depth > 1 && !(value && value.is_constant_expression(scope)) && (depth = 1), (!d.escaped || d.escaped > depth) && (d.escaped = depth);
return;
}
if (parent instanceof AST_Array || parent instanceof AST_Await || parent instanceof AST_Binary && lazy_op.has(parent.operator) || parent instanceof AST_Conditional && node !== parent.condition || parent instanceof AST_Expansion || parent instanceof AST_Sequence && node === parent.tail_node()) mark_escaped(tw, d, scope, parent, parent, level + 1, depth);
else if (parent instanceof AST_ObjectKeyVal && node === parent.value) {
var obj = tw.parent(level + 1);
mark_escaped(tw, d, scope, obj, obj, level + 2, depth);
} else if (parent instanceof AST_PropAccess && node === parent.expression && (value = read_property(value, parent.property), mark_escaped(tw, d, scope, parent, value, level + 1, depth + 1), value)) return;
level > 0 || parent instanceof AST_Sequence && node !== parent.tail_node() || parent instanceof AST_SimpleStatement || (d.direct_access = !0);
}
}
def_eval(AST_PropAccess, function(compressor, depth) {
const obj = this.expression._eval(compressor, depth);
if (obj === nullish || this.optional && null == obj) return nullish;
if (compressor.option("unsafe")) {
var key = this.property;
if (key instanceof AST_Node && (key = key._eval(compressor, depth)) === this.property) return this;
var exp = this.expression;
if (is_undeclared_ref(exp)) {
var val, aa, first_arg = "hasOwnProperty" === exp.name && "call" === key && (aa = compressor.parent() && compressor.parent().args) && aa && aa[0] && aa[0].evaluate(compressor);
if (null == (first_arg = first_arg instanceof AST_Dot ? first_arg.expression : first_arg) || first_arg.thedef && first_arg.thedef.undeclared) return this.clone();
if (!is_pure_native_value(exp.name, key)) return this;
val = global_objs[exp.name];
} else {
if ((val = exp._eval(compressor, depth + 1)) instanceof RegExp) {
if ("source" == key) return regexp_source_fix(val.source);
if ("flags" == key || regexp_flags.has(key)) return val[key];
}
if (!val || val === exp || !HOP(val, key)) return this;
if ("function" == typeof val) switch(key){
case "name":
return val.node.name ? val.node.name.name : "";
case "length":
return val.node.length_property();
default:
return this;
}
}
return val[key];
}
return this;
}), def_eval(AST_Chain, function(compressor, depth) {
const evaluated = this.expression._eval(compressor, depth);
return evaluated === nullish ? void 0 : evaluated === this.expression ? this : evaluated;
}), def_eval(AST_Call, function(compressor, depth) {
var exp = this.expression;
const callee = exp._eval(compressor, depth);
if (callee === nullish || this.optional && null == callee) return nullish;
if (compressor.option("unsafe") && exp instanceof AST_PropAccess) {
var val, key = exp.property;
if (key instanceof AST_Node && (key = key._eval(compressor, depth)) === exp.property) return this;
var e = exp.expression;
if (is_undeclared_ref(e)) {
var first_arg = "hasOwnProperty" === e.name && "call" === key && this.args[0] && this.args[0].evaluate(compressor);
if (null == (first_arg = first_arg instanceof AST_Dot ? first_arg.expression : first_arg) || first_arg.thedef && first_arg.thedef.undeclared) return this.clone();
if (!is_pure_native_fn(e.name, key)) return this;
val = global_objs[e.name];
} else if ((val = e._eval(compressor, depth + 1)) === e || !val || !is_pure_native_method(val.constructor.name, key)) return this;
for(var args = [], i = 0, len = this.args.length; i < len; i++){
var arg = this.args[i], value = arg._eval(compressor, depth);
if (arg === value || arg instanceof AST_Lambda) return this;
args.push(value);
}
try {
return val[key].apply(val, args);
} catch (ex) {
// We don't really care
}
}
return this;
}), // Also a subclass of AST_Call
def_eval(AST_New, return_this), def_drop_side_effect_free(AST_Node, return_this), def_drop_side_effect_free(AST_Constant, return_null), def_drop_side_effect_free(AST_This, return_null), def_drop_side_effect_free(AST_Call, function(compressor, first_in_statement) {
if (is_nullish_shortcircuited(this, compressor)) return this.expression.drop_side_effect_free(compressor, first_in_statement);
if (!this.is_callee_pure(compressor)) {
if (this.expression.is_call_pure(compressor)) {
var exprs = this.args.slice();
return exprs.unshift(this.expression.expression), (exprs = trim(exprs, compressor, first_in_statement)) && make_sequence(this, exprs);
}
if (is_func_expr(this.expression) && (!this.expression.name || !this.expression.name.definition().references.length)) {
var node = this.clone();
return node.expression.process_expression(!1, compressor), node;
}
return this;
}
var args = trim(this.args, compressor, first_in_statement);
return args && make_sequence(this, args);
}), def_drop_side_effect_free(AST_Accessor, return_null), def_drop_side_effect_free(AST_Function, return_null), def_drop_side_effect_free(AST_Arrow, return_null), def_drop_side_effect_free(AST_Class, function(compressor) {
const with_effects = [], trimmed_extends = this.extends && this.extends.drop_side_effect_free(compressor);
for (const prop of (trimmed_extends && with_effects.push(trimmed_extends), this.properties)){
const trimmed_prop = prop.drop_side_effect_free(compressor);
trimmed_prop && with_effects.push(trimmed_prop);
}
return with_effects.length ? make_sequence(this, with_effects) : null;
}), def_drop_side_effect_free(AST_Binary, function(compressor, first_in_statement) {
var right = this.right.drop_side_effect_free(compressor);
if (!right) return this.left.drop_side_effect_free(compressor, first_in_statement);
if (lazy_op.has(this.operator)) {
if (right === this.right) return this;
var node = this.clone();
return node.right = right, node;
}
var left = this.left.drop_side_effect_free(compressor, first_in_statement);
return left ? make_sequence(this, [
left,
right
]) : this.right.drop_side_effect_free(compressor, first_in_statement);
}), def_drop_side_effect_free(AST_Assign, function(compressor) {
if (this.logical) return this;
var left = this.left;
if (left.has_side_effects(compressor) || compressor.has_directive("use strict") && left instanceof AST_PropAccess && left.expression.is_constant()) return this;
for(set_flag(this, 0b00100000); left instanceof AST_PropAccess;)left = left.expression;
return left.is_constant_expression(compressor.find_parent(AST_Scope)) ? this.right.drop_side_effect_free(compressor) : this;
}), def_drop_side_effect_free(AST_Conditional, function(compressor) {
var consequent = this.consequent.drop_side_effect_free(compressor), alternative = this.alternative.drop_side_effect_free(compressor);
if (consequent === this.consequent && alternative === this.alternative) return this;
if (!consequent) return alternative ? make_node(AST_Binary, this, {
operator: "||",
left: this.condition,
right: alternative
}) : this.condition.drop_side_effect_free(compressor);
if (!alternative) return make_node(AST_Binary, this, {
operator: "&&",
left: this.condition,
right: consequent
});
var node = this.clone();
return node.consequent = consequent, node.alternative = alternative, node;
}), def_drop_side_effect_free(AST_Unary, function(compressor, first_in_statement) {
if (unary_side_effects.has(this.operator)) return this.expression.has_side_effects(compressor) ? clear_flag(this, 0b00100000) : set_flag(this, 0b00100000), this;
if ("typeof" == this.operator && this.expression instanceof AST_SymbolRef) return null;
var expression = this.expression.drop_side_effect_free(compressor, first_in_statement);
return first_in_statement && expression && is_iife_call(expression) ? expression === this.expression && "!" == this.operator ? this : expression.negate(compressor, first_in_statement) : expression;
}), def_drop_side_effect_free(AST_SymbolRef, function(compressor) {
return this.is_declared(compressor) || pure_prop_access_globals.has(this.name) ? null : this;
}), def_drop_side_effect_free(AST_Object, function(compressor, first_in_statement) {
var values = trim(this.properties, compressor, first_in_statement);
return values && make_sequence(this, values);
}), def_drop_side_effect_free(AST_ObjectProperty, function(compressor, first_in_statement) {
const key = this instanceof AST_ObjectKeyVal && this.key instanceof AST_Node && this.key.drop_side_effect_free(compressor, first_in_statement), value = this.value && this.value.drop_side_effect_free(compressor, first_in_statement);
return key && value ? make_sequence(this, [
key,
value
]) : key || value;
}), def_drop_side_effect_free(AST_ClassProperty, function(compressor) {
const key = this.computed_key() && this.key.drop_side_effect_free(compressor), value = this.static && this.value && this.value.drop_side_effect_free(compressor);
return key && value ? make_sequence(this, [
key,
value
]) : key || value || null;
}), def_drop_side_effect_free(AST_ConciseMethod, function() {
return this.computed_key() ? this.key : null;
}), def_drop_side_effect_free(AST_ObjectGetter, function() {
return this.computed_key() ? this.key : null;
}), def_drop_side_effect_free(AST_ObjectSetter, function() {
return this.computed_key() ? this.key : null;
}), def_drop_side_effect_free(AST_Array, function(compressor, first_in_statement) {
var values = trim(this.elements, compressor, first_in_statement);
return values && make_sequence(this, values);
}), def_drop_side_effect_free(AST_Dot, function(compressor, first_in_statement) {
return is_nullish_shortcircuited(this, compressor) ? this.expression.drop_side_effect_free(compressor, first_in_statement) : this.expression.may_throw_on_access(compressor) ? this : this.expression.drop_side_effect_free(compressor, first_in_statement);
}), def_drop_side_effect_free(AST_Sub, function(compressor, first_in_statement) {
if (is_nullish_shortcircuited(this, compressor)) return this.expression.drop_side_effect_free(compressor, first_in_statement);
if (this.expression.may_throw_on_access(compressor)) return this;
var expression = this.expression.drop_side_effect_free(compressor, first_in_statement);
if (!expression) return this.property.drop_side_effect_free(compressor, first_in_statement);
var property = this.property.drop_side_effect_free(compressor);
return property ? make_sequence(this, [
expression,
property
]) : expression;
}), def_drop_side_effect_free(AST_Chain, function(compressor, first_in_statement) {
return this.expression.drop_side_effect_free(compressor, first_in_statement);
}), def_drop_side_effect_free(AST_Sequence, function(compressor) {
var last = this.tail_node(), expr = last.drop_side_effect_free(compressor);
if (expr === last) return this;
var expressions = this.expressions.slice(0, -1);
return (expr && expressions.push(expr), expressions.length) ? make_sequence(this, expressions) : make_node(AST_Number, this, {
value: 0
});
}), def_drop_side_effect_free(AST_Expansion, function(compressor, first_in_statement) {
return this.expression.drop_side_effect_free(compressor, first_in_statement);
}), def_drop_side_effect_free(AST_TemplateSegment, return_null), def_drop_side_effect_free(AST_TemplateString, function(compressor) {
var values = trim(this.segments, compressor, first_in_statement);
return values && make_sequence(this, values);
}), def_reduce_vars(AST_Node, noop);
const suppress = (node)=>walk(node, (node)=>{
if (node instanceof AST_Symbol) {
var d = node.definition();
d && (node instanceof AST_SymbolRef && d.references.push(node), d.fixed = !1);
}
});
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
***********************************************************************/ function loop_body(x) {
return x instanceof AST_IterationStatement && x.body instanceof AST_BlockStatement ? x.body : x;
}
// Remove code which we know is unreachable.
function trim_unreachable_code(compressor, stat, target) {
walk(stat, (node)=>node instanceof AST_Var ? (node.remove_initializers(), target.push(node), !0) : node instanceof AST_Defun && (node === stat || !compressor.has_directive("use strict")) ? (target.push(node === stat ? node : make_node(AST_Var, node, {
definitions: [
make_node(AST_VarDef, node, {
name: make_node(AST_SymbolVar, node.name, node.name),
value: null
})
]
})), !0) : node instanceof AST_Export || node instanceof AST_Import ? (target.push(node), !0) : node instanceof AST_Scope || void 0);
}
// Tighten a bunch of statements together, and perform statement-level optimization.
function tighten_body(statements, compressor) {
var scope = compressor.find_parent(AST_Scope).get_defun_scope();
!function() {
var node = compressor.self(), level = 0;
do if (node instanceof AST_Catch || node instanceof AST_Finally) level++;
else if (node instanceof AST_IterationStatement) in_loop = !0;
else if (node instanceof AST_Scope) {
scope = node;
break;
} else node instanceof AST_Try && (in_try = !0);
while (node = compressor.parent(level++))
}();
var in_loop, in_try, CHANGED, max_iter = 10;
do CHANGED = !1, function eliminate_spurious_blocks(statements) {
for(var seen_dirs = [], i = 0; i < statements.length;){
var stat = statements[i];
stat instanceof AST_BlockStatement && stat.body.every(can_be_evicted_from_block) ? (CHANGED = !0, eliminate_spurious_blocks(stat.body), statements.splice(i, 1, ...stat.body), i += stat.body.length) : stat instanceof AST_EmptyStatement ? (CHANGED = !0, statements.splice(i, 1)) : stat instanceof AST_Directive ? 0 > seen_dirs.indexOf(stat.value) ? (i++, seen_dirs.push(stat.value)) : (CHANGED = !0, statements.splice(i, 1)) : i++;
}
}(statements), compressor.option("dead_code") && function(statements, compressor) {
for(var has_quit, self1 = compressor.self(), i = 0, n = 0, len = statements.length; i < len; i++){
var stat = statements[i];
if (stat instanceof AST_LoopControl) {
var lct = compressor.loopcontrol_target(stat);
stat instanceof AST_Break && !(lct instanceof AST_IterationStatement) && loop_body(lct) === self1 || stat instanceof AST_Continue && loop_body(lct) === self1 ? stat.label && remove(stat.label.thedef.references, stat) : statements[n++] = stat;
} else statements[n++] = stat;
if (aborts(stat)) {
has_quit = statements.slice(i + 1);
break;
}
}
statements.length = n, CHANGED = n != len, has_quit && has_quit.forEach(function(stat) {
trim_unreachable_code(compressor, stat, statements);
});
}(statements, compressor), compressor.option("if_return") && function(statements, compressor) {
for(var self1 = compressor.self(), multiple_if_returns = function(statements) {
for(var n = 0, i = statements.length; --i >= 0;){
var stat = statements[i];
if (stat instanceof AST_If && stat.body instanceof AST_Return && ++n > 1) return !0;
}
return !1;
}(statements), in_lambda = self1 instanceof AST_Lambda, i = statements.length; --i >= 0;){
var stat = statements[i], j = next_index(i), next = statements[j];
if (in_lambda && !next && stat instanceof AST_Return) {
if (!stat.value) {
CHANGED = !0, statements.splice(i, 1);
continue;
}
if (stat.value instanceof AST_UnaryPrefix && "void" == stat.value.operator) {
CHANGED = !0, statements[i] = make_node(AST_SimpleStatement, stat, {
body: stat.value.expression
});
continue;
}
}
if (stat instanceof AST_If) {
var ab = aborts(stat.body);
if (can_merge_flow(ab)) {
ab.label && remove(ab.label.thedef.references, ab), CHANGED = !0, (stat = stat.clone()).condition = stat.condition.negate(compressor);
var body = as_statement_array_with_return(stat.body, ab);
stat.body = make_node(AST_BlockStatement, stat, {
body: as_statement_array(stat.alternative).concat(extract_functions())
}), stat.alternative = make_node(AST_BlockStatement, stat, {
body: body
}), statements[i] = stat.transform(compressor);
continue;
}
var ab = aborts(stat.alternative);
if (can_merge_flow(ab)) {
ab.label && remove(ab.label.thedef.references, ab), CHANGED = !0, (stat = stat.clone()).body = make_node(AST_BlockStatement, stat.body, {
body: as_statement_array(stat.body).concat(extract_functions())
});
var body = as_statement_array_with_return(stat.alternative, ab);
stat.alternative = make_node(AST_BlockStatement, stat.alternative, {
body: body
}), statements[i] = stat.transform(compressor);
continue;
}
}
if (stat instanceof AST_If && stat.body instanceof AST_Return) {
var value = stat.body.value;
//---
// pretty silly case, but:
// if (foo()) return; return; ==> foo(); return;
if (!value && !stat.alternative && (in_lambda && !next || next instanceof AST_Return && !next.value)) {
CHANGED = !0, statements[i] = make_node(AST_SimpleStatement, stat.condition, {
body: stat.condition
});
continue;
}
//---
// if (foo()) return x; return y; ==> return foo() ? x : y;
if (value && !stat.alternative && next instanceof AST_Return && next.value) {
CHANGED = !0, (stat = stat.clone()).alternative = next, statements[i] = stat.transform(compressor), statements.splice(j, 1);
continue;
}
//---
// if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined;
if (value && !stat.alternative && (!next && in_lambda && multiple_if_returns || next instanceof AST_Return)) {
CHANGED = !0, (stat = stat.clone()).alternative = next || make_node(AST_Return, stat, {
value: null
}), statements[i] = stat.transform(compressor), next && statements.splice(j, 1);
continue;
}
//---
// if (a) return b; if (c) return d; e; ==> return a ? b : c ? d : void e;
//
// if sequences is not enabled, this can lead to an endless loop (issue #866).
// however, with sequences on this helps producing slightly better output for
// the example code.
var prev = statements[function(i) {
for(var j = i; --j >= 0;){
var stat = statements[j];
if (!(stat instanceof AST_Var && declarations_only(stat))) break;
}
return j;
}(i)];
if (compressor.option("sequences") && in_lambda && !stat.alternative && prev instanceof AST_If && prev.body instanceof AST_Return && next_index(j) == statements.length && next instanceof AST_SimpleStatement) {
CHANGED = !0, (stat = stat.clone()).alternative = make_node(AST_BlockStatement, next, {
body: [
next,
make_node(AST_Return, next, {
value: null
})
]
}), statements[i] = stat.transform(compressor), statements.splice(j, 1);
continue;
}
}
}
function can_merge_flow(ab) {
if (!ab) return !1;
for(var value, j = i + 1, len = statements.length; j < len; j++){
var stat = statements[j];
if (stat instanceof AST_Const || stat instanceof AST_Let) return !1;
}
var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab) : null;
return ab instanceof AST_Return && in_lambda && (!(value = ab.value) || value instanceof AST_UnaryPrefix && "void" == value.operator) || ab instanceof AST_Continue && self1 === loop_body(lct) || ab instanceof AST_Break && lct instanceof AST_BlockStatement && self1 === lct;
}
function extract_functions() {
var tail = statements.slice(i + 1);
return statements.length = i + 1, tail.filter(function(stat) {
return !(stat instanceof AST_Defun) || (statements.push(stat), !1);
});
}
function as_statement_array_with_return(node, ab) {
var body = as_statement_array(node).slice(0, -1);
return ab.value && body.push(make_node(AST_SimpleStatement, ab.value, {
body: ab.value.expression
})), body;
}
function next_index(i) {
for(var j = i + 1, len = statements.length; j < len; j++){
var stat = statements[j];
if (!(stat instanceof AST_Var && declarations_only(stat))) break;
}
return j;
}
}(statements, compressor), compressor.sequences_limit > 0 && (function(statements, compressor) {
if (!(statements.length < 2)) {
for(var seq = [], n = 0, i = 0, len = statements.length; i < len; i++){
var stat = statements[i];
if (stat instanceof AST_SimpleStatement) {
seq.length >= compressor.sequences_limit && push_seq();
var body = stat.body;
seq.length > 0 && (body = body.drop_side_effect_free(compressor)), body && merge_sequence(seq, body);
} else stat instanceof AST_Definitions && declarations_only(stat) || stat instanceof AST_Defun || push_seq(), statements[n++] = stat;
}
push_seq(), statements.length = n, n != len && (CHANGED = !0);
}
function push_seq() {
if (seq.length) {
var body = make_sequence(seq[0], seq);
statements[n++] = make_node(AST_SimpleStatement, body, {
body: body
}), seq = [];
}
}
}(statements, compressor), function(statements, compressor) {
function cons_seq(right) {
n--, CHANGED = !0;
var left = prev.body;
return make_sequence(left, [
left,
right
]).transform(compressor);
}
for(var prev, n = 0, i = 0; i < statements.length; i++){
var stat = statements[i];
if (!prev || (stat instanceof AST_Exit ? stat.value = cons_seq(stat.value || make_node(AST_Undefined, stat).transform(compressor)) : stat instanceof AST_For ? stat.init instanceof AST_Definitions || walk(prev.body, (node)=>node instanceof AST_Scope || (node instanceof AST_Binary && "in" === node.operator ? walk_abort : void 0)) || (stat.init ? stat.init = cons_seq(stat.init) : (stat.init = prev.body, n--, CHANGED = !0)) : stat instanceof AST_ForIn ? stat.init instanceof AST_Const || stat.init instanceof AST_Let || (stat.object = cons_seq(stat.object)) : stat instanceof AST_If ? stat.condition = cons_seq(stat.condition) : stat instanceof AST_Switch ? stat.expression = cons_seq(stat.expression) : stat instanceof AST_With && (stat.expression = cons_seq(stat.expression))), compressor.option("conditionals") && stat instanceof AST_If) {
var decls = [], body = to_simple_statement(stat.body, decls), alt = to_simple_statement(stat.alternative, decls);
if (!1 !== body && !1 !== alt && decls.length > 0) {
var len = decls.length;
decls.push(make_node(AST_If, stat, {
condition: stat.condition,
body: body || make_node(AST_EmptyStatement, stat.body),
alternative: alt
})), decls.unshift(n, 1), [].splice.apply(statements, decls), i += len, n += len + 1, prev = null, CHANGED = !0;
continue;
}
}
statements[n++] = stat, prev = stat instanceof AST_SimpleStatement ? stat : null;
}
statements.length = n;
}(statements, compressor)), compressor.option("join_vars") && function(statements) {
for(var defs, i = 0, j = -1, len = statements.length; i < len; i++){
var stat = statements[i], prev = statements[j];
if (stat instanceof AST_Definitions) prev && prev.TYPE == stat.TYPE ? (prev.definitions = prev.definitions.concat(stat.definitions), CHANGED = !0) : defs && defs.TYPE == stat.TYPE && declarations_only(stat) ? (defs.definitions = defs.definitions.concat(stat.definitions), CHANGED = !0) : (statements[++j] = stat, defs = stat);
else if (stat instanceof AST_Exit) stat.value = extract_object_assignments(stat.value);
else if (stat instanceof AST_For) {
var exprs = join_object_assignments(prev, stat.init);
exprs ? (CHANGED = !0, stat.init = exprs.length ? make_sequence(stat.init, exprs) : null, statements[++j] = stat) : prev instanceof AST_Var && (!stat.init || stat.init.TYPE == prev.TYPE) ? (stat.init && (prev.definitions = prev.definitions.concat(stat.init.definitions)), stat.init = prev, statements[j] = stat, CHANGED = !0) : defs && stat.init && defs.TYPE == stat.init.TYPE && declarations_only(stat.init) ? (defs.definitions = defs.definitions.concat(stat.init.definitions), stat.init = null, statements[++j] = stat, CHANGED = !0) : statements[++j] = stat;
} else if (stat instanceof AST_ForIn) stat.object = extract_object_assignments(stat.object);
else if (stat instanceof AST_If) stat.condition = extract_object_assignments(stat.condition);
else if (stat instanceof AST_SimpleStatement) {
var exprs = join_object_assignments(prev, stat.body);
if (exprs) {
if (CHANGED = !0, !exprs.length) continue;
stat.body = make_sequence(stat.body, exprs);
}
statements[++j] = stat;
} else stat instanceof AST_Switch ? stat.expression = extract_object_assignments(stat.expression) : stat instanceof AST_With ? stat.expression = extract_object_assignments(stat.expression) : statements[++j] = stat;
}
function extract_object_assignments(value) {
statements[++j] = stat;
var exprs = join_object_assignments(prev, value);
return exprs ? (CHANGED = !0, exprs.length) ? make_sequence(value, exprs) : value instanceof AST_Sequence ? value.tail_node().left : value.left : value;
}
statements.length = j + 1;
}(statements), compressor.option("collapse_vars") && // Search from right to left for assignment-like expressions:
// - `var a = x;`
// - `a = x;`
// - `++a`
// For each candidate, scan from left to right for first usage, then try
// to fold assignment into the site for compression.
// Will not attempt to collapse assignments into or past code blocks
// which are not sequentially executed, e.g. loops and conditionals.
function(statements, compressor) {
if (!scope.pinned()) for(var args, candidates = [], stat_index = statements.length, scanner = new TreeTransformer(function(node) {
if (abort) return node;
// Skip nodes before `candidate` as quickly as possible
if (!hit) return node !== hit_stack[hit_index] ? node : ++hit_index < hit_stack.length ? handle_custom_scan_order(node) : (hit = !0, (stop_after = function find_stop(node, level, write_only) {
var parent = scanner.parent(level);
return parent instanceof AST_Assign ? !write_only || parent.logical || parent.left instanceof AST_PropAccess || lvalues.has(parent.left.name) ? node : find_stop(parent, level + 1, write_only) : parent instanceof AST_Binary ? write_only && (!lazy_op.has(parent.operator) || parent.left === node) ? find_stop(parent, level + 1, write_only) : node : parent instanceof AST_Call || parent instanceof AST_Case ? node : parent instanceof AST_Conditional ? write_only && parent.condition === node ? find_stop(parent, level + 1, write_only) : node : parent instanceof AST_Definitions ? find_stop(parent, level + 1, !0) : parent instanceof AST_Exit ? write_only ? find_stop(parent, level + 1, write_only) : node : parent instanceof AST_If ? write_only && parent.condition === node ? find_stop(parent, level + 1, write_only) : node : parent instanceof AST_IterationStatement ? node : parent instanceof AST_Sequence ? find_stop(parent, level + 1, parent.tail_node() !== node) : parent instanceof AST_SimpleStatement ? find_stop(parent, level + 1, !0) : parent instanceof AST_Switch || parent instanceof AST_VarDef ? node : null;
}(node, 0)) === node && (abort = !0), node);
// Stop immediately if these node types are encountered
var sym, parent = scanner.parent();
if (node instanceof AST_Assign && (node.logical || "=" != node.operator && lhs.equivalent_to(node.left)) || node instanceof AST_Await || node instanceof AST_Call && lhs instanceof AST_PropAccess && lhs.equivalent_to(node.expression) || node instanceof AST_Debugger || node instanceof AST_Destructuring || node instanceof AST_Expansion && node.expression instanceof AST_Symbol && (node.expression instanceof AST_This || node.expression.definition().references.length > 1) || node instanceof AST_IterationStatement && !(node instanceof AST_For) || node instanceof AST_LoopControl || node instanceof AST_Try || node instanceof AST_With || node instanceof AST_Yield || node instanceof AST_Export || node instanceof AST_Class || parent instanceof AST_For && node !== parent.init || !replace_all && node instanceof AST_SymbolRef && !node.is_declared(compressor) && !pure_prop_access_globals.has(node) || node instanceof AST_SymbolRef && parent instanceof AST_Call && has_annotation(parent, _NOINLINE)) return abort = !0, node;
// Replace variable with assignment when found
if (!stop_if_hit && (!lhs_local || !replace_all) && (parent instanceof AST_Binary && lazy_op.has(parent.operator) && parent.left !== node || parent instanceof AST_Conditional && parent.condition !== node || parent instanceof AST_If && parent.condition !== node) && (stop_if_hit = parent), can_replace && !(node instanceof AST_SymbolDeclaration) && lhs.equivalent_to(node) && !function(newScope, lvalues) {
for (const { def } of lvalues.values()){
let current = newScope;
for(; current && current !== def.scope;){
let nested_def = current.variables.get(def.name);
if (nested_def && nested_def !== def) return !0;
current = current.parent_scope;
}
}
return !1;
}(node.scope, lvalues)) {
if (stop_if_hit) return abort = !0, node;
if (is_lhs(node, parent)) return value_def && replaced++, node;
if (replaced++, value_def && candidate instanceof AST_VarDef) return node;
if (CHANGED = abort = !0, candidate instanceof AST_UnaryPostfix) return make_node(AST_UnaryPrefix, candidate, candidate);
if (candidate instanceof AST_VarDef) {
var def = candidate.name.definition(), value = candidate.value;
return def.references.length - def.replaced != 1 || compressor.exposed(def) ? make_node(AST_Assign, candidate, {
operator: "=",
logical: !1,
left: make_node(AST_SymbolRef, candidate.name, candidate.name),
right: value
}) : (def.replaced++, funarg && is_identifier_atom(value)) ? value.transform(compressor) : maintain_this_binding(parent, node, value);
}
return clear_flag(candidate, 0b00100000), candidate;
}
return (node instanceof AST_Call || node instanceof AST_Exit && (side_effects || lhs instanceof AST_PropAccess || may_modify(lhs)) || node instanceof AST_PropAccess && (side_effects || node.expression.may_throw_on_access(compressor)) || node instanceof AST_SymbolRef && (lvalues.has(node.name) && lvalues.get(node.name).modified || side_effects && may_modify(node)) || node instanceof AST_VarDef && node.value && (lvalues.has(node.name.name) || side_effects && may_modify(node.name)) || (sym = is_lhs(node.left, node)) && (sym instanceof AST_PropAccess || lvalues.has(sym.name)) || may_throw && (in_try ? node.has_side_effects(compressor) : function side_effects_external(node, lhs) {
if (node instanceof AST_Assign) return side_effects_external(node.left, !0);
if (node instanceof AST_Unary) return side_effects_external(node.expression, !0);
if (node instanceof AST_VarDef) return node.value && side_effects_external(node.value);
if (lhs) {
if (node instanceof AST_Dot || node instanceof AST_Sub) return side_effects_external(node.expression, !0);
if (node instanceof AST_SymbolRef) return node.definition().scope !== scope;
}
return !1;
}(node))) && (stop_after = node, node instanceof AST_Scope && (abort = !0)), handle_custom_scan_order(node);
}, function(node) {
abort || (stop_after === node && (abort = !0), stop_if_hit !== node || (stop_if_hit = null));
}), multi_replacer = new TreeTransformer(function(node) {
if (abort) return node;
// Skip nodes before `candidate` as quickly as possible
if (!hit) {
if (node !== hit_stack[hit_index]) return node;
if (++hit_index < hit_stack.length) return;
return hit = !0, node;
}
return(// Replace variable when found
node instanceof AST_SymbolRef && node.name == def.name ? (--replaced || (abort = !0), is_lhs(node, multi_replacer.parent())) ? node : (def.replaced++, value_def.replaced--, candidate.value) : node instanceof AST_Default || node instanceof AST_Scope ? node : void 0);
}); --stat_index >= 0;){
0 == stat_index && compressor.option("unused") && function() {
var iife, fn = compressor.self();
if (is_func_expr(fn) && !fn.name && !fn.uses_arguments && !fn.pinned() && (iife = compressor.parent()) instanceof AST_Call && iife.expression === fn && iife.args.every((arg)=>!(arg instanceof AST_Expansion))) {
var fn_strict = compressor.has_directive("use strict");
fn_strict && !member(fn_strict, fn.body) && (fn_strict = !1);
var len = fn.argnames.length;
args = iife.args.slice(len);
for(var names = new Set(), i = len; --i >= 0;){
var sym = fn.argnames[i], arg = iife.args[i];
// The following two line fix is a duplicate of the fix at
// https://github.com/terser/terser/commit/011d3eb08cefe6922c7d1bdfa113fc4aeaca1b75
// This might mean that these two pieces of code (one here in collapse_vars and another in reduce_vars
// Might be doing the exact same thing.
const def = sym.definition && sym.definition();
if ((!def || !(def.orig.length > 1)) && (args.unshift(make_node(AST_VarDef, sym, {
name: sym,
value: arg
})), !names.has(sym.name))) {
if (names.add(sym.name), sym instanceof AST_Expansion) {
var elements = iife.args.slice(i);
elements.every((arg)=>!has_overlapping_symbol(fn, arg, fn_strict)) && candidates.unshift([
make_node(AST_VarDef, sym, {
name: sym.expression,
value: make_node(AST_Array, iife, {
elements: elements
})
})
]);
} else arg ? (arg instanceof AST_Lambda && arg.pinned() || has_overlapping_symbol(fn, arg, fn_strict)) && (arg = null) : arg = make_node(AST_Undefined, sym).transform(compressor), arg && candidates.unshift([
make_node(AST_VarDef, sym, {
name: sym,
value: arg
})
]);
}
}
}
}();
// Find collapsible assignments
var hit_stack = [];
for(function extract_candidates(expr) {
if (hit_stack.push(expr), expr instanceof AST_Assign) expr.left.has_side_effects(compressor) || expr.right instanceof AST_Chain || candidates.push(hit_stack.slice()), extract_candidates(expr.right);
else if (expr instanceof AST_Binary) extract_candidates(expr.left), extract_candidates(expr.right);
else if (expr instanceof AST_Call && !has_annotation(expr, _NOINLINE)) extract_candidates(expr.expression), expr.args.forEach(extract_candidates);
else if (expr instanceof AST_Case) extract_candidates(expr.expression);
else if (expr instanceof AST_Conditional) extract_candidates(expr.condition), extract_candidates(expr.consequent), extract_candidates(expr.alternative);
else if (expr instanceof AST_Definitions) {
var len = expr.definitions.length, i = len - 200;
for(i < 0 && (i = 0); i < len; i++)extract_candidates(expr.definitions[i]);
} else expr instanceof AST_DWLoop ? (extract_candidates(expr.condition), expr.body instanceof AST_Block || extract_candidates(expr.body)) : expr instanceof AST_Exit ? expr.value && extract_candidates(expr.value) : expr instanceof AST_For ? (expr.init && extract_candidates(expr.init), expr.condition && extract_candidates(expr.condition), expr.step && extract_candidates(expr.step), expr.body instanceof AST_Block || extract_candidates(expr.body)) : expr instanceof AST_ForIn ? (extract_candidates(expr.object), expr.body instanceof AST_Block || extract_candidates(expr.body)) : expr instanceof AST_If ? (extract_candidates(expr.condition), expr.body instanceof AST_Block || extract_candidates(expr.body), !expr.alternative || expr.alternative instanceof AST_Block || extract_candidates(expr.alternative)) : expr instanceof AST_Sequence ? expr.expressions.forEach(extract_candidates) : expr instanceof AST_SimpleStatement ? extract_candidates(expr.body) : expr instanceof AST_Switch ? (extract_candidates(expr.expression), expr.body.forEach(extract_candidates)) : expr instanceof AST_Unary ? ("++" == expr.operator || "--" == expr.operator) && candidates.push(hit_stack.slice()) : expr instanceof AST_VarDef && expr.value && !(expr.value instanceof AST_Chain) && (candidates.push(hit_stack.slice()), extract_candidates(expr.value));
hit_stack.pop();
}(statements[stat_index]); candidates.length > 0;){
hit_stack = candidates.pop();
var hit_index = 0, candidate = hit_stack[hit_stack.length - 1], value_def = null, stop_after = null, stop_if_hit = null, lhs = function(expr) {
if (expr instanceof AST_Assign && expr.logical) return !1;
if (expr instanceof AST_VarDef && expr.name instanceof AST_SymbolDeclaration) {
var def = expr.name.definition();
if (!member(expr.name, def.orig)) return;
var referenced = def.references.length - def.replaced;
if (!referenced) return;
if (def.orig.length - def.eliminated > 1 && !(expr.name instanceof AST_SymbolFunarg) || (referenced > 1 ? function(var_def) {
var value = var_def.value;
if (value instanceof AST_SymbolRef && "arguments" != value.name) {
var def = value.definition();
if (!def.undeclared) return value_def = def;
}
}(expr) : !compressor.exposed(def))) return make_node(AST_SymbolRef, expr.name, expr.name);
} else {
const lhs = expr instanceof AST_Assign ? expr.left : expr.expression;
return !is_ref_of(lhs, AST_SymbolConst) && !is_ref_of(lhs, AST_SymbolLet) && lhs;
}
}(candidate);
if (!(!lhs || function is_lhs_read_only(lhs) {
if (lhs instanceof AST_This) return !0;
if (lhs instanceof AST_SymbolRef) return lhs.definition().orig[0] instanceof AST_SymbolLambda;
if (lhs instanceof AST_PropAccess) {
if ((lhs = lhs.expression) instanceof AST_SymbolRef) {
if (lhs.is_immutable()) return !1;
lhs = lhs.fixed_value();
}
return !lhs || !(lhs instanceof AST_RegExp) && (lhs instanceof AST_Constant || is_lhs_read_only(lhs));
}
return !1;
}(lhs) || lhs.has_side_effects(compressor))) {
// Locate symbols which may execute code outside of scanning range
var expr, lvalues = function(expr) {
var lvalues = new Map();
if (expr instanceof AST_Unary) return lvalues;
var tw = new TreeWalker(function(node) {
for(var sym = node; sym instanceof AST_PropAccess;)sym = sym.expression;
if (sym instanceof AST_SymbolRef) {
const prev = lvalues.get(sym.name);
prev && prev.modified || lvalues.set(sym.name, {
def: sym.definition(),
modified: is_modified(compressor, tw, node, node, 0)
});
}
});
return get_rvalue(expr).walk(tw), lvalues;
}(candidate), lhs_local = function(lhs) {
for(; lhs instanceof AST_PropAccess;)lhs = lhs.expression;
return lhs instanceof AST_SymbolRef && lhs.definition().scope === scope && !(in_loop && (lvalues.has(lhs.name) || candidate instanceof AST_Unary || candidate instanceof AST_Assign && !candidate.logical && "=" != candidate.operator));
}(lhs);
lhs instanceof AST_SymbolRef && lvalues.set(lhs.name, {
def: lhs.definition(),
modified: !1
});
var side_effects = (expr = candidate) instanceof AST_Unary ? unary_side_effects.has(expr.operator) : get_rvalue(expr).has_side_effects(compressor), replace_all = function() {
if (side_effects) return !1;
if (value_def) return !0;
if (lhs instanceof AST_SymbolRef) {
var def = lhs.definition();
if (def.references.length - def.replaced == (candidate instanceof AST_VarDef ? 1 : 2)) return !0;
}
return !1;
}(), may_throw = candidate.may_throw(compressor), funarg = candidate.name instanceof AST_SymbolFunarg, hit = funarg, abort = !1, replaced = 0, can_replace = !args || !hit;
if (!can_replace) {
for(var j = compressor.self().argnames.lastIndexOf(candidate.name) + 1; !abort && j < args.length; j++)args[j].transform(scanner);
can_replace = !0;
}
for(var i = stat_index; !abort && i < statements.length; i++)statements[i].transform(scanner);
if (value_def) {
var def = candidate.name.definition();
if (abort && def.references.length - def.replaced > replaced) replaced = !1;
else {
abort = !1, hit_index = 0, hit = funarg;
for(var i = stat_index; !abort && i < statements.length; i++)statements[i].transform(multi_replacer);
value_def.single_use = !1;
}
}
replaced && !function(expr) {
if (expr.name instanceof AST_SymbolFunarg) {
var iife = compressor.parent(), argnames = compressor.self().argnames, index = argnames.indexOf(expr.name);
if (index < 0) iife.args.length = Math.min(iife.args.length, argnames.length - 1);
else {
var args = iife.args;
args[index] && (args[index] = make_node(AST_Number, args[index], {
value: 0
}));
}
return !0;
}
var found = !1;
return statements[stat_index].transform(new TreeTransformer(function(node, descend, in_list) {
return found ? node : node === expr || node.body === expr ? (found = !0, node instanceof AST_VarDef) ? (node.value = node.name instanceof AST_SymbolConst ? make_node(AST_Undefined, node.value) // `const` always needs value.
: null, node) : in_list ? MAP.skip : null : void 0;
}, function(node) {
if (node instanceof AST_Sequence) switch(node.expressions.length){
case 0:
return null;
case 1:
return node.expressions[0];
}
}));
}(candidate) && statements.splice(stat_index, 1);
}
}
}
function handle_custom_scan_order(node) {
// Skip (non-executed) functions
if (node instanceof AST_Scope) return node;
// Scan case expressions first in a switch statement
if (node instanceof AST_Switch) {
node.expression = node.expression.transform(scanner);
for(var i = 0, len = node.body.length; !abort && i < len; i++){
var branch = node.body[i];
if (branch instanceof AST_Case) {
if (!hit) {
if (branch !== hit_stack[hit_index]) continue;
hit_index++;
}
if (branch.expression = branch.expression.transform(scanner), !replace_all) break;
}
}
return abort = !0, node;
}
}
function has_overlapping_symbol(fn, arg, fn_strict) {
var found = !1, scan_this = !(fn instanceof AST_Arrow);
return arg.walk(new TreeWalker(function(node, descend) {
if (found) return !0;
if (node instanceof AST_SymbolRef && (fn.variables.has(node.name) || function(def, scope) {
if (def.global) return !1;
let cur_scope = def.scope;
for(; cur_scope && cur_scope !== scope;){
if (cur_scope.variables.has(def.name)) return !0;
cur_scope = cur_scope.parent_scope;
}
return !1;
}(node.definition(), fn))) {
var s = node.definition().scope;
if (s !== scope) {
for(; s = s.parent_scope;)if (s === scope) return !0;
}
return found = !0;
}
if ((fn_strict || scan_this) && node instanceof AST_This) return found = !0;
if (node instanceof AST_Scope && !(node instanceof AST_Arrow)) {
var prev = scan_this;
return scan_this = !1, descend(), scan_this = prev, !0;
}
})), found;
}
function get_rvalue(expr) {
return expr instanceof AST_Assign ? expr.right : expr.value;
}
function may_modify(sym) {
if (!sym.definition) return !0; // AST_Destructuring
var def = sym.definition();
return (1 != def.orig.length || !(def.orig[0] instanceof AST_SymbolDefun)) && (def.scope.get_defun_scope() !== scope || !def.references.every((ref)=>{
var s = ref.scope.get_defun_scope();
return "Scope" == s.TYPE && (s = s.parent_scope), s === scope;
}));
}
}(statements, compressor);
while (CHANGED && max_iter-- > 0)
function declarations_only(node) {
return node.definitions.every((var_def)=>!var_def.value);
}
function to_simple_statement(block, decls) {
if (!(block instanceof AST_BlockStatement)) return block;
for(var stat = null, i = 0, len = block.body.length; i < len; i++){
var line = block.body[i];
if (line instanceof AST_Var && declarations_only(line)) decls.push(line);
else {
if (stat) return !1;
stat = line;
}
}
return stat;
}
function join_object_assignments(defn, body) {
if (defn instanceof AST_Definitions) {
var exprs, def = defn.definitions[defn.definitions.length - 1];
if (def.value instanceof AST_Object && (body instanceof AST_Assign && !body.logical ? exprs = [
body
] : body instanceof AST_Sequence && (exprs = body.expressions.slice()), exprs)) {
var trimmed = !1;
do {
var node = exprs[0];
if (!(node instanceof AST_Assign) || "=" != node.operator || !(node.left instanceof AST_PropAccess)) break;
var sym = node.left.expression;
if (!(sym instanceof AST_SymbolRef) || def.name.name != sym.name || !node.right.is_constant_expression(scope)) break;
var prop = node.left.property;
if (prop instanceof AST_Node && (prop = prop.evaluate(compressor)), prop instanceof AST_Node) break;
prop = "" + prop;
var diff = 2015 > compressor.option("ecma") && compressor.has_directive("use strict") ? function(node) {
return node.key != prop && node.key && node.key.name != prop;
} : function(node) {
return node.key && node.key.name != prop;
};
if (!def.value.properties.every(diff)) break;
var p = def.value.properties.filter(function(p) {
return p.key === prop;
})[0];
p ? p.value = new AST_Sequence({
start: p.start,
expressions: [
p.value.clone(),
node.right.clone()
],
end: p.end
}) : def.value.properties.push(make_node(AST_ObjectKeyVal, node, {
key: prop,
value: node.right
})), exprs.shift(), trimmed = !0;
}while (exprs.length)
return trimmed && exprs;
}
}
}
}
def_reduce_vars(AST_Accessor, function(tw, descend, compressor) {
return push(tw), reset_variables(tw, compressor, this), descend(), pop(tw), !0;
}), def_reduce_vars(AST_Assign, function(tw, descend, compressor) {
var node = this;
if (node.left instanceof AST_Destructuring) {
suppress(node.left);
return;
}
const finish_walk = ()=>{
if (node.logical) return node.left.walk(tw), push(tw), node.right.walk(tw), pop(tw), !0;
};
var sym = node.left;
if (!(sym instanceof AST_SymbolRef)) return finish_walk();
var def = sym.definition(), safe = safe_to_assign(tw, def, sym.scope, node.right);
if (def.assignments++, !safe) return finish_walk();
var fixed = def.fixed;
if (!fixed && "=" != node.operator && !node.logical) return finish_walk();
var eq = "=" == node.operator, value = eq ? node.right : node;
return is_modified(compressor, tw, node, value, 0) ? finish_walk() : ((def.references.push(sym), node.logical || (eq || (def.chained = !0), def.fixed = eq ? function() {
return node.right;
} : function() {
return make_node(AST_Binary, node, {
operator: node.operator.slice(0, -1),
left: fixed instanceof AST_Node ? fixed : fixed(),
right: node.right
});
}), node.logical) ? (mark(tw, def, !1), push(tw), node.right.walk(tw), pop(tw)) : (mark(tw, def, !1), node.right.walk(tw), mark(tw, def, !0), mark_escaped(tw, def, sym.scope, node, value, 0, 1)), !0);
}), def_reduce_vars(AST_Binary, function(tw) {
if (lazy_op.has(this.operator)) return this.left.walk(tw), push(tw), this.right.walk(tw), pop(tw), !0;
}), def_reduce_vars(AST_Block, function(tw, descend, compressor) {
reset_block_variables(compressor, this);
}), def_reduce_vars(AST_Case, function(tw) {
return push(tw), this.expression.walk(tw), pop(tw), push(tw), walk_body(this, tw), pop(tw), !0;
}), def_reduce_vars(AST_Class, function(tw, descend) {
return clear_flag(this, 0b00010000), push(tw), descend(), pop(tw), !0;
}), def_reduce_vars(AST_Conditional, function(tw) {
return this.condition.walk(tw), push(tw), this.consequent.walk(tw), pop(tw), push(tw), this.alternative.walk(tw), pop(tw), !0;
}), def_reduce_vars(AST_Chain, function(tw, descend) {
// Chains' conditions apply left-to-right, cumulatively.
// If we walk normally we don't go in that order because we would pop before pushing again
// Solution: AST_PropAccess and AST_Call push when they are optional, and never pop.
// Then we pop everything when they are done being walked.
const safe_ids = tw.safe_ids;
return descend(), // Unroll back to start
tw.safe_ids = safe_ids, !0;
}), def_reduce_vars(AST_Call, function(tw) {
for (const arg of (this.expression.walk(tw), this.optional && // Never pop -- it's popped at AST_Chain above
push(tw), this.args))arg.walk(tw);
return !0;
}), def_reduce_vars(AST_PropAccess, function(tw) {
if (this.optional) return this.expression.walk(tw), // Never pop -- it's popped at AST_Chain above
push(tw), this.property instanceof AST_Node && this.property.walk(tw), !0;
}), def_reduce_vars(AST_Default, function(tw, descend) {
return push(tw), descend(), pop(tw), !0;
}), def_reduce_vars(AST_Lambda, function(tw, descend, compressor) {
var iife;
if (clear_flag(this, 0b00010000), push(tw), reset_variables(tw, compressor, this), this.uses_arguments) {
descend(), pop(tw);
return;
}
return !this.name && (iife = tw.parent()) instanceof AST_Call && iife.expression === this && !iife.args.some((arg)=>arg instanceof AST_Expansion) && this.argnames.every((arg_name)=>arg_name instanceof AST_Symbol) && // Virtually turn IIFE parameters into variable definitions:
// (function(a,b) {...})(c,d) => (function() {var a=c,b=d; ...})()
// So existing transformation rules can work on them.
this.argnames.forEach((arg, i)=>{
if (arg.definition) {
var d = arg.definition();
// Avoid setting fixed when there's more than one origin for a variable value
d.orig.length > 1 || (void 0 === d.fixed && (!this.uses_arguments || tw.has_directive("use strict")) ? (d.fixed = function() {
return iife.args[i] || make_node(AST_Undefined, iife);
}, tw.loop_ids.set(d.id, tw.in_loop), mark(tw, d, !0)) : d.fixed = !1);
}
}), descend(), pop(tw), !0;
}), def_reduce_vars(AST_Do, function(tw, descend, compressor) {
reset_block_variables(compressor, this);
const saved_loop = tw.in_loop;
return tw.in_loop = this, push(tw), this.body.walk(tw), has_break_or_continue(this) && (pop(tw), push(tw)), this.condition.walk(tw), pop(tw), tw.in_loop = saved_loop, !0;
}), def_reduce_vars(AST_For, function(tw, descend, compressor) {
reset_block_variables(compressor, this), this.init && this.init.walk(tw);
const saved_loop = tw.in_loop;
return tw.in_loop = this, push(tw), this.condition && this.condition.walk(tw), this.body.walk(tw), this.step && (has_break_or_continue(this) && (pop(tw), push(tw)), this.step.walk(tw)), pop(tw), tw.in_loop = saved_loop, !0;
}), def_reduce_vars(AST_ForIn, function(tw, descend, compressor) {
reset_block_variables(compressor, this), suppress(this.init), this.object.walk(tw);
const saved_loop = tw.in_loop;
return tw.in_loop = this, push(tw), this.body.walk(tw), pop(tw), tw.in_loop = saved_loop, !0;
}), def_reduce_vars(AST_If, function(tw) {
return this.condition.walk(tw), push(tw), this.body.walk(tw), pop(tw), this.alternative && (push(tw), this.alternative.walk(tw), pop(tw)), !0;
}), def_reduce_vars(AST_LabeledStatement, function(tw) {
return push(tw), this.body.walk(tw), pop(tw), !0;
}), def_reduce_vars(AST_SymbolCatch, function() {
this.definition().fixed = !1;
}), def_reduce_vars(AST_SymbolRef, function(tw, descend, compressor) {
var value, fixed_value, d = this.definition();
(d.references.push(this), 1 == d.references.length && !d.fixed && d.orig[0] instanceof AST_SymbolDefun && tw.loop_ids.set(d.id, tw.in_loop), void 0 !== d.fixed && safe_to_read(tw, d)) ? d.fixed && ((fixed_value = this.fixed_value()) instanceof AST_Lambda && is_recursive_ref(tw, d) ? d.recursive_refs++ : fixed_value && !compressor.exposed(d) && compressor.option("unused") && !d.scope.pinned() && d.references.length - d.recursive_refs == 1 && tw.loop_ids.get(d.id) === tw.in_loop ? d.single_use = fixed_value instanceof AST_Lambda && !fixed_value.pinned() || fixed_value instanceof AST_Class || d.scope === this.scope && fixed_value.is_constant_expression() : d.single_use = !1, is_modified(compressor, tw, this, fixed_value, 0, !!(value = fixed_value) && (value.is_constant() || value instanceof AST_Lambda || value instanceof AST_This)) && (d.single_use ? d.single_use = "m" : d.fixed = !1)) : d.fixed = !1, mark_escaped(tw, d, this.scope, this, fixed_value, 0, 1);
}), def_reduce_vars(AST_Toplevel, function(tw, descend, compressor) {
this.globals.forEach(function(def) {
reset_def(compressor, def);
}), reset_variables(tw, compressor, this);
}), def_reduce_vars(AST_Try, function(tw, descend, compressor) {
return reset_block_variables(compressor, this), push(tw), walk_body(this, tw), pop(tw), this.bcatch && (push(tw), this.bcatch.walk(tw), pop(tw)), this.bfinally && this.bfinally.walk(tw), !0;
}), def_reduce_vars(AST_Unary, function(tw) {
var node = this;
if ("++" === node.operator || "--" === node.operator) {
var exp = node.expression;
if (exp instanceof AST_SymbolRef) {
var def = exp.definition(), safe = safe_to_assign(tw, def, exp.scope, !0);
if (def.assignments++, safe) {
var fixed = def.fixed;
if (fixed) return def.references.push(exp), def.chained = !0, def.fixed = function() {
return make_node(AST_Binary, node, {
operator: node.operator.slice(0, -1),
left: make_node(AST_UnaryPrefix, node, {
operator: "+",
expression: fixed instanceof AST_Node ? fixed : fixed()
}),
right: make_node(AST_Number, node, {
value: 1
})
});
}, mark(tw, def, !0), !0;
}
}
}
}), def_reduce_vars(AST_VarDef, function(tw, descend) {
var node = this;
if (node.name instanceof AST_Destructuring) {
suppress(node.name);
return;
}
var d = node.name.definition();
if (node.value) {
if (safe_to_assign(tw, d, node.name.scope, node.value)) return d.fixed = function() {
return node.value;
}, tw.loop_ids.set(d.id, tw.in_loop), mark(tw, d, !1), descend(), mark(tw, d, !0), !0;
d.fixed = !1;
}
}), def_reduce_vars(AST_While, function(tw, descend, compressor) {
reset_block_variables(compressor, this);
const saved_loop = tw.in_loop;
return tw.in_loop = this, push(tw), descend(), pop(tw), tw.in_loop = saved_loop, !0;
});
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
***********************************************************************/ class Compressor extends TreeWalker {
constructor(options, { false_by_default = !1, mangle_options = !1 }){
super(), void 0 === options.defaults || options.defaults || (false_by_default = !0), this.options = defaults(options, {
arguments: !1,
arrows: !false_by_default,
booleans: !false_by_default,
booleans_as_integers: !1,
collapse_vars: !false_by_default,
comparisons: !false_by_default,
computed_props: !false_by_default,
conditionals: !false_by_default,
dead_code: !false_by_default,
defaults: !0,
directives: !false_by_default,
drop_console: !1,
drop_debugger: !false_by_default,
ecma: 5,
evaluate: !false_by_default,
expression: !1,
global_defs: !1,
hoist_funs: !1,
hoist_props: !false_by_default,
hoist_vars: !1,
ie8: !1,
if_return: !false_by_default,
inline: !false_by_default,
join_vars: !false_by_default,
keep_classnames: !1,
keep_fargs: !0,
keep_fnames: !1,
keep_infinity: !1,
loops: !false_by_default,
module: !1,
negate_iife: !false_by_default,
passes: 1,
properties: !false_by_default,
pure_getters: !false_by_default && "strict",
pure_funcs: null,
reduce_funcs: !false_by_default,
reduce_vars: !false_by_default,
sequences: !false_by_default,
side_effects: !false_by_default,
switches: !false_by_default,
top_retain: null,
toplevel: !!(options && options.top_retain),
typeofs: !false_by_default,
unsafe: !1,
unsafe_arrows: !1,
unsafe_comps: !1,
unsafe_Function: !1,
unsafe_math: !1,
unsafe_symbols: !1,
unsafe_methods: !1,
unsafe_proto: !1,
unsafe_regexp: !1,
unsafe_undefined: !1,
unused: !false_by_default,
warnings: !1 // legacy
}, !0);
var global_defs = this.options.global_defs;
if ("object" == typeof global_defs) for(var key in global_defs)"@" === key[0] && HOP(global_defs, key) && (global_defs[key.slice(1)] = parse(global_defs[key], {
expression: !0
}));
!0 === this.options.inline && (this.options.inline = 3);
var pure_funcs = this.options.pure_funcs;
"function" == typeof pure_funcs ? this.pure_funcs = pure_funcs : this.pure_funcs = pure_funcs ? function(node) {
return !pure_funcs.includes(node.expression.print_to_string());
} : return_true;
var top_retain = this.options.top_retain;
top_retain instanceof RegExp ? this.top_retain = function(def) {
return top_retain.test(def.name);
} : "function" == typeof top_retain ? this.top_retain = top_retain : top_retain && ("string" == typeof top_retain && (top_retain = top_retain.split(/,/)), this.top_retain = function(def) {
return top_retain.includes(def.name);
}), this.options.module && (this.directives["use strict"] = !0, this.options.toplevel = !0);
var toplevel = this.options.toplevel;
this.toplevel = "string" == typeof toplevel ? {
funcs: /funcs/.test(toplevel),
vars: /vars/.test(toplevel)
} : {
funcs: toplevel,
vars: toplevel
};
var sequences = this.options.sequences;
this.sequences_limit = 1 == sequences ? 800 : 0 | sequences, this.evaluated_regexps = new Map(), this._toplevel = void 0, this.mangle_options = mangle_options;
}
option(key) {
return this.options[key];
}
exposed(def) {
if (def.export) return !0;
if (def.global) {
for(var i = 0, len = def.orig.length; i < len; i++)if (!this.toplevel[def.orig[i] instanceof AST_SymbolDefun ? "funcs" : "vars"]) return !0;
}
return !1;
}
in_boolean_context() {
if (!this.option("booleans")) return !1;
for(var p, self1 = this.self(), i = 0; p = this.parent(i); i++){
if (p instanceof AST_SimpleStatement || p instanceof AST_Conditional && p.condition === self1 || p instanceof AST_DWLoop && p.condition === self1 || p instanceof AST_For && p.condition === self1 || p instanceof AST_If && p.condition === self1 || p instanceof AST_UnaryPrefix && "!" == p.operator && p.expression === self1) return !0;
if ((!(p instanceof AST_Binary) || "&&" != p.operator && "||" != p.operator && "??" != p.operator) && !(p instanceof AST_Conditional) && p.tail_node() !== self1) return !1;
self1 = p;
}
}
get_toplevel() {
return this._toplevel;
}
compress(toplevel) {
toplevel = toplevel.resolve_defines(this), this._toplevel = toplevel, this.option("expression") && this._toplevel.process_expression(!0);
for(var passes = +this.options.passes || 1, min_count = 1 / 0, stopping = !1, nth_identifier = this.mangle_options && this.mangle_options.nth_identifier || base54, mangle = {
ie8: this.option("ie8"),
nth_identifier: nth_identifier
}, pass = 0; pass < passes; pass++)if (this._toplevel.figure_out_scope(mangle), 0 === pass && this.option("drop_console") && // must be run before reduce_vars and compress pass
(this._toplevel = this._toplevel.drop_console()), (pass > 0 || this.option("reduce_vars")) && this._toplevel.reset_opt_flags(this), this._toplevel = this._toplevel.transform(this), passes > 1) {
let count = 0;
if (walk(this._toplevel, ()=>{
count++;
}), count < min_count) min_count = count, stopping = !1;
else if (stopping) break;
else stopping = !0;
}
return this.option("expression") && this._toplevel.process_expression(!1), toplevel = this._toplevel, this._toplevel = void 0, toplevel;
}
before(node, descend) {
if (has_flag(node, 0b0000000100000000)) return node;
var was_scope = !1;
node instanceof AST_Scope && (node = (node = node.hoist_properties(this)).hoist_declarations(this), was_scope = !0), // Before https://github.com/mishoo/UglifyJS2/pull/1602 AST_Node.optimize()
// would call AST_Node.transform() if a different instance of AST_Node is
// produced after def_optimize().
// This corrupts TreeWalker.stack, which cause AST look-ups to malfunction.
// Migrate and defer all children's AST_Node.transform() to below, which
// will now happen after this parent AST_Node has been properly substituted
// thus gives a consistent AST snapshot.
descend(node, this), // Existing code relies on how AST_Node.optimize() worked, and omitting the
// following replacement call would result in degraded efficiency of both
// output and performance.
descend(node, this);
var opt = node.optimize(this);
return was_scope && opt instanceof AST_Scope && (opt.drop_unused(this), descend(opt, this)), opt === node && set_flag(opt, 0b0000000100000000), opt;
}
}
function def_optimize(node, optimizer) {
node.DEFMETHOD("optimize", function(compressor) {
if (has_flag(this, 0b0000001000000000) || compressor.has_directive("use asm")) return this;
var opt = optimizer(this, compressor);
return set_flag(opt, 0b0000001000000000), opt;
});
}
function find_scope(tw) {
for(let i = 0;; i++){
const p = tw.parent(i);
if (p instanceof AST_Toplevel || p instanceof AST_Lambda) return p;
if (p.block_scope) return p.block_scope;
}
}
function find_variable(compressor, name) {
for(var scope, i = 0; (scope = compressor.parent(i++)) && !(scope instanceof AST_Scope);)if (scope instanceof AST_Catch && scope.argname) {
scope = scope.argname.definition().scope;
break;
}
return scope.find_variable(name);
}
function is_empty(thing) {
return null === thing || thing instanceof AST_EmptyStatement || thing instanceof AST_BlockStatement && 0 == thing.body.length;
}
def_optimize(AST_Node, function(self1) {
return self1;
}), AST_Toplevel.DEFMETHOD("drop_console", function() {
return this.transform(new TreeTransformer(function(self1) {
if ("Call" == self1.TYPE) {
var exp = self1.expression;
if (exp instanceof AST_PropAccess) {
for(var name = exp.expression; name.expression;)name = name.expression;
if (is_undeclared_ref(name) && "console" == name.name) return make_node(AST_Undefined, self1);
}
}
}));
}), AST_Node.DEFMETHOD("equivalent_to", function(node) {
return equivalent_to(this, node);
}), AST_Scope.DEFMETHOD("process_expression", function(insert, compressor) {
var self1 = this, tt = new TreeTransformer(function(node) {
if (insert && node instanceof AST_SimpleStatement) return make_node(AST_Return, node, {
value: node.body
});
if (!insert && node instanceof AST_Return) {
if (compressor) {
var value = node.value && node.value.drop_side_effect_free(compressor, !0);
return value ? make_node(AST_SimpleStatement, node, {
body: value
}) : make_node(AST_EmptyStatement, node);
}
return make_node(AST_SimpleStatement, node, {
body: node.value || make_node(AST_UnaryPrefix, node, {
operator: "void",
expression: make_node(AST_Number, node, {
value: 0
})
})
});
}
if (node instanceof AST_Class || node instanceof AST_Lambda && node !== self1) return node;
if (node instanceof AST_Block) {
var index = node.body.length - 1;
index >= 0 && (node.body[index] = node.body[index].transform(tt));
} else node instanceof AST_If ? (node.body = node.body.transform(tt), node.alternative && (node.alternative = node.alternative.transform(tt))) : node instanceof AST_With && (node.body = node.body.transform(tt));
return node;
});
self1.transform(tt);
}), AST_Toplevel.DEFMETHOD("reset_opt_flags", function(compressor) {
const self1 = this, reduce_vars = compressor.option("reduce_vars"), preparation = new TreeWalker(function(node, descend) {
if (clear_flag(node, 1792), reduce_vars) return compressor.top_retain && node instanceof AST_Defun // Only functions are retained
&& preparation.parent() === self1 && set_flag(node, 0b0000010000000000), node.reduce_vars(preparation, descend, compressor);
});
// Stack of look-up tables to keep track of whether a `SymbolDef` has been
// properly assigned before use:
// - `push()` & `pop()` when visiting conditional branches
preparation.safe_ids = Object.create(null), preparation.in_loop = null, preparation.loop_ids = new Map(), preparation.defs_to_safe_ids = new Map(), self1.walk(preparation);
}), AST_Symbol.DEFMETHOD("fixed_value", function() {
var fixed = this.thedef.fixed;
return !fixed || fixed instanceof AST_Node ? fixed : fixed();
}), AST_SymbolRef.DEFMETHOD("is_immutable", function() {
var orig = this.definition().orig;
return 1 == orig.length && orig[0] instanceof AST_SymbolLambda;
});
var global_names = makePredicate("Array Boolean clearInterval clearTimeout console Date decodeURI decodeURIComponent encodeURI encodeURIComponent Error escape eval EvalError Function isFinite isNaN JSON Math Number parseFloat parseInt RangeError ReferenceError RegExp Object setInterval setTimeout String SyntaxError TypeError unescape URIError");
AST_SymbolRef.DEFMETHOD("is_declared", function(compressor) {
return !this.definition().undeclared || compressor.option("unsafe") && global_names.has(this.name);
});
/* -----[ optimizers ]----- */ var directives = new Set([
"use asm",
"use strict"
]);
function opt_AST_Lambda(self1, compressor) {
return tighten_body(self1.body, compressor), compressor.option("side_effects") && 1 == self1.body.length && self1.body[0] === compressor.has_directive("use strict") && (self1.body.length = 0), self1;
}
def_optimize(AST_Directive, function(self1, compressor) {
return compressor.option("directives") && (!directives.has(self1.value) || compressor.has_directive(self1.value) !== self1) ? make_node(AST_EmptyStatement, self1) : self1;
}), def_optimize(AST_Debugger, function(self1, compressor) {
return compressor.option("drop_debugger") ? make_node(AST_EmptyStatement, self1) : self1;
}), def_optimize(AST_LabeledStatement, function(self1, compressor) {
return self1.body instanceof AST_Break && compressor.loopcontrol_target(self1.body) === self1.body ? make_node(AST_EmptyStatement, self1) : 0 == self1.label.references.length ? self1.body : self1;
}), def_optimize(AST_Block, function(self1, compressor) {
return tighten_body(self1.body, compressor), self1;
}), def_optimize(AST_BlockStatement, function(self1, compressor) {
switch(tighten_body(self1.body, compressor), self1.body.length){
case 1:
var node;
if (!compressor.has_directive("use strict") && compressor.parent() instanceof AST_If && !((node = self1.body[0]) instanceof AST_Const || node instanceof AST_Let || node instanceof AST_Class) || can_be_evicted_from_block(self1.body[0])) return self1.body[0];
break;
case 0:
return make_node(AST_EmptyStatement, self1);
}
return self1;
}), def_optimize(AST_Lambda, opt_AST_Lambda);
const r_keep_assign = /keep_assign/;
// TODO this only works with AST_Defun, shouldn't it work for other ways of defining functions?
function retain_top_func(fn, compressor) {
return compressor.top_retain && fn instanceof AST_Defun && has_flag(fn, 0b0000010000000000) && fn.name && compressor.top_retain(fn.name);
}
AST_Scope.DEFMETHOD("drop_unused", function(compressor) {
if (!compressor.option("unused") || compressor.has_directive("use asm")) return;
var self1 = this;
if (self1.pinned()) return;
var drop_funcs = !(self1 instanceof AST_Toplevel) || compressor.toplevel.funcs, drop_vars = !(self1 instanceof AST_Toplevel) || compressor.toplevel.vars;
const assign_as_unused = r_keep_assign.test(compressor.option("unused")) ? return_false : function(node) {
return node instanceof AST_Assign && !node.logical && (has_flag(node, 0b00100000) || "=" == node.operator) ? node.left : node instanceof AST_Unary && has_flag(node, 0b00100000) ? node.expression : void 0;
};
var in_use_ids = new Map(), fixed_ids = new Map();
self1 instanceof AST_Toplevel && compressor.top_retain && self1.variables.forEach(function(def) {
compressor.top_retain(def) && !in_use_ids.has(def.id) && in_use_ids.set(def.id, def);
});
var var_defs_by_id = new Map(), initializations = new Map(), scope = this, tw = new TreeWalker(function(node, descend) {
if (node instanceof AST_Lambda && node.uses_arguments && !tw.has_directive("use strict") && node.argnames.forEach(function(argname) {
if (argname instanceof AST_SymbolDeclaration) {
var def = argname.definition();
in_use_ids.has(def.id) || in_use_ids.set(def.id, def);
}
}), node !== self1) {
if (node instanceof AST_Defun || node instanceof AST_DefClass) {
var node_def = node.name.definition();
if ((tw.parent() instanceof AST_Export || !drop_funcs && scope === self1) && node_def.global && !in_use_ids.has(node_def.id) && in_use_ids.set(node_def.id, node_def), node instanceof AST_DefClass) for (const prop of (node.extends && (node.extends.has_side_effects(compressor) || node.extends.may_throw(compressor)) && node.extends.walk(tw), node.properties))(prop.has_side_effects(compressor) || prop.may_throw(compressor)) && prop.walk(tw);
return map_add(initializations, node_def.id, node), !0; // don't go in nested scopes
}
if (node instanceof AST_SymbolFunarg && scope === self1 && map_add(var_defs_by_id, node.definition().id, node), node instanceof AST_Definitions && scope === self1) {
const in_export = tw.parent() instanceof AST_Export;
return node.definitions.forEach(function(def) {
if (def.name instanceof AST_SymbolVar && map_add(var_defs_by_id, def.name.definition().id, def), (in_export || !drop_vars) && walk(def.name, (node)=>{
if (node instanceof AST_SymbolDeclaration) {
const def = node.definition();
(in_export || def.global) && !in_use_ids.has(def.id) && in_use_ids.set(def.id, def);
}
}), def.value) {
if (def.name instanceof AST_Destructuring) def.walk(tw);
else {
var node_def = def.name.definition();
map_add(initializations, node_def.id, def.value), node_def.chained || def.name.fixed_value() !== def.value || fixed_ids.set(node_def.id, def);
}
def.value.has_side_effects(compressor) && def.value.walk(tw);
}
}), !0;
}
return scan_ref_scoped(node, descend);
}
});
self1.walk(tw), // pass 2: for every used symbol we need to walk its
// initialization code to figure out if it uses other
// symbols (that may not be in_use).
tw = new TreeWalker(scan_ref_scoped), in_use_ids.forEach(function(def) {
var init = initializations.get(def.id);
init && init.forEach(function(init) {
init.walk(tw);
});
});
// pass 3: we should drop declarations not in_use
var tt = new TreeTransformer(function(node, descend, in_list) {
var def, block, parent = tt.parent();
if (drop_vars) {
const sym = assign_as_unused(node);
if (sym instanceof AST_SymbolRef) {
var def = sym.definition(), in_use = in_use_ids.has(def.id);
if (node instanceof AST_Assign) {
if (!in_use || fixed_ids.has(def.id) && fixed_ids.get(def.id) !== node) return maintain_this_binding(parent, node, node.right.transform(tt));
} else if (!in_use) return in_list ? MAP.skip : make_node(AST_Number, node, {
value: 0
});
}
}
if (scope === self1) {
if (node.name && (node instanceof AST_ClassExpression && !keep_name(compressor.option("keep_classnames"), (def = node.name.definition()).name) || node instanceof AST_Function && !keep_name(compressor.option("keep_fnames"), (def = node.name.definition()).name)) && (!in_use_ids.has(def.id) || def.orig.length > 1) && (node.name = null), node instanceof AST_Lambda && !(node instanceof AST_Accessor)) for(var trim = !compressor.option("keep_fargs"), a = node.argnames, i = a.length; --i >= 0;){
var sym = a[i];
sym instanceof AST_Expansion && (sym = sym.expression), sym instanceof AST_DefaultAssign && (sym = sym.left), sym instanceof AST_Destructuring || in_use_ids.has(sym.definition().id) ? trim = !1 : (set_flag(sym, 0b00000001), trim && a.pop());
}
if ((node instanceof AST_Defun || node instanceof AST_DefClass) && node !== self1) {
const def = node.name.definition();
if (!(def.global && !drop_funcs || in_use_ids.has(def.id))) {
if (def.eliminated++, node instanceof AST_DefClass) {
// Classes might have extends with side effects
const side_effects = node.drop_side_effect_free(compressor);
if (side_effects) return make_node(AST_SimpleStatement, node, {
body: side_effects
});
}
return in_list ? MAP.skip : make_node(AST_EmptyStatement, node);
}
}
if (node instanceof AST_Definitions && !(parent instanceof AST_ForIn && parent.init === node)) {
var drop_block = !(parent instanceof AST_Toplevel) && !(node instanceof AST_Var), body = [], head = [], tail = [], side_effects = [];
switch(node.definitions.forEach(function(def) {
def.value && (def.value = def.value.transform(tt));
var is_destructure = def.name instanceof AST_Destructuring, sym = is_destructure ? new SymbolDef(null, {
name: "<destructure>"
}) : def.name.definition();
if (drop_block && sym.global) return tail.push(def);
if (!(drop_vars || drop_block) || is_destructure && (def.name.names.length || def.name.is_array || !0 != compressor.option("pure_getters")) || in_use_ids.has(sym.id)) {
if (def.value && fixed_ids.has(sym.id) && fixed_ids.get(sym.id) !== def && (def.value = def.value.drop_side_effect_free(compressor)), def.name instanceof AST_SymbolVar) {
var var_defs = var_defs_by_id.get(sym.id);
if (var_defs.length > 1 && (!def.value || sym.orig.indexOf(def.name) > sym.eliminated)) {
if (def.value) {
var ref = make_node(AST_SymbolRef, def.name, def.name);
sym.references.push(ref);
var assign = make_node(AST_Assign, def, {
operator: "=",
logical: !1,
left: ref,
right: def.value
});
fixed_ids.get(sym.id) === def && fixed_ids.set(sym.id, assign), side_effects.push(assign.transform(tt));
}
remove(var_defs, def), sym.eliminated++;
return;
}
}
def.value ? (side_effects.length > 0 && (tail.length > 0 ? (side_effects.push(def.value), def.value = make_sequence(def.value, side_effects)) : body.push(make_node(AST_SimpleStatement, node, {
body: make_sequence(node, side_effects)
})), side_effects = []), tail.push(def)) : head.push(def);
} else if (sym.orig[0] instanceof AST_SymbolCatch) {
var value = def.value && def.value.drop_side_effect_free(compressor);
value && side_effects.push(value), def.value = null, head.push(def);
} else {
var value = def.value && def.value.drop_side_effect_free(compressor);
value && side_effects.push(value), sym.eliminated++;
}
}), (head.length > 0 || tail.length > 0) && (node.definitions = head.concat(tail), body.push(node)), side_effects.length > 0 && body.push(make_node(AST_SimpleStatement, node, {
body: make_sequence(node, side_effects)
})), body.length){
case 0:
return in_list ? MAP.skip : make_node(AST_EmptyStatement, node);
case 1:
return body[0];
default:
return in_list ? MAP.splice(body) : make_node(AST_BlockStatement, node, {
body: body
});
}
}
// certain combination of unused name + side effect leads to:
// https://github.com/mishoo/UglifyJS2/issues/44
// https://github.com/mishoo/UglifyJS2/issues/1830
// https://github.com/mishoo/UglifyJS2/issues/1838
// that's an invalid AST.
// We fix it at this stage by moving the `var` outside the `for`.
if (node instanceof AST_For) return descend(node, this), node.init instanceof AST_BlockStatement && (block = node.init, node.init = block.body.pop(), block.body.push(node)), node.init instanceof AST_SimpleStatement ? node.init = node.init.body : is_empty(node.init) && (node.init = null), block ? in_list ? MAP.splice(block.body) : block : node;
if (node instanceof AST_LabeledStatement && node.body instanceof AST_For) {
if (descend(node, this), node.body instanceof AST_BlockStatement) {
var block = node.body;
return node.body = block.body.pop(), block.body.push(node), in_list ? MAP.splice(block.body) : block;
}
return node;
}
if (node instanceof AST_BlockStatement) return (descend(node, this), in_list && node.body.every(can_be_evicted_from_block)) ? MAP.splice(node.body) : node;
if (node instanceof AST_Scope) {
const save_scope = scope;
return scope = node, descend(node, this), scope = save_scope, node;
}
}
});
function scan_ref_scoped(node, descend) {
var node_def;
const sym = assign_as_unused(node);
if (sym instanceof AST_SymbolRef && !is_ref_of(node.left, AST_SymbolBlockDeclaration) && self1.variables.get(sym.name) === (node_def = sym.definition())) return node instanceof AST_Assign && (node.right.walk(tw), node_def.chained || node.left.fixed_value() !== node.right || fixed_ids.set(node_def.id, node)), !0;
if (node instanceof AST_SymbolRef) {
if (node_def = node.definition(), !in_use_ids.has(node_def.id) && (in_use_ids.set(node_def.id, node_def), node_def.orig[0] instanceof AST_SymbolCatch)) {
const redef = node_def.scope.is_block_scope() && node_def.scope.get_defun_scope().variables.get(node_def.name);
redef && in_use_ids.set(redef.id, redef);
}
return !0;
}
if (node instanceof AST_Scope) {
var save_scope = scope;
return scope = node, descend(), scope = save_scope, !0;
}
}
self1.transform(tt);
}), AST_Scope.DEFMETHOD("hoist_declarations", function(compressor) {
var self1 = this;
if (compressor.has_directive("use asm") || !Array.isArray(self1.body)) return self1;
var hoist_funs = compressor.option("hoist_funs"), hoist_vars = compressor.option("hoist_vars");
if (hoist_funs || hoist_vars) {
var dirs = [], hoisted = [], vars = new Map(), vars_found = 0, var_decl = 0;
// let's count var_decl first, we seem to waste a lot of
// space if we hoist `var` when there's only one.
walk(self1, (node)=>node instanceof AST_Scope && node !== self1 || (node instanceof AST_Var ? (++var_decl, !0) : void 0)), hoist_vars = hoist_vars && var_decl > 1;
var tt = new TreeTransformer(function(node) {
if (node !== self1) {
if (node instanceof AST_Directive) return dirs.push(node), make_node(AST_EmptyStatement, node);
if (hoist_funs && node instanceof AST_Defun && !(tt.parent() instanceof AST_Export) && tt.parent() === self1) return hoisted.push(node), make_node(AST_EmptyStatement, node);
if (hoist_vars && node instanceof AST_Var && !node.definitions.some((def)=>def.name instanceof AST_Destructuring)) {
node.definitions.forEach(function(def) {
vars.set(def.name.name, def), ++vars_found;
});
var seq = node.to_assignments(compressor), p = tt.parent();
if (p instanceof AST_ForIn && p.init === node) {
if (null == seq) {
var def = node.definitions[0].name;
return make_node(AST_SymbolRef, def, def);
}
return seq;
}
return p instanceof AST_For && p.init === node ? seq : seq ? make_node(AST_SimpleStatement, node, {
body: seq
}) : make_node(AST_EmptyStatement, node);
}
if (node instanceof AST_Scope) return node; // to avoid descending in nested scopes
}
});
if (self1 = self1.transform(tt), vars_found > 0) {
// collect only vars which don't show up in self's arguments list
var defs = [];
const is_lambda = self1 instanceof AST_Lambda, args_as_names = is_lambda ? self1.args_as_names() : null;
if (vars.forEach((def, name)=>{
is_lambda && args_as_names.some((x)=>x.name === def.name.name) ? vars.delete(name) : ((def = def.clone()).value = null, defs.push(def), vars.set(name, def));
}), defs.length > 0) {
// try to merge in assignments
for(; 0 < self1.body.length;){
if (self1.body[0] instanceof AST_SimpleStatement) {
var sym, assign, expr = self1.body[0].body;
if (expr instanceof AST_Assign && "=" == expr.operator && (sym = expr.left) instanceof AST_Symbol && vars.has(sym.name)) {
var def = vars.get(sym.name);
if (def.value) break;
def.value = expr.right, remove(defs, def), defs.push(def), self1.body.splice(0, 1);
continue;
}
if (expr instanceof AST_Sequence && (assign = expr.expressions[0]) instanceof AST_Assign && "=" == assign.operator && (sym = assign.left) instanceof AST_Symbol && vars.has(sym.name)) {
var def = vars.get(sym.name);
if (def.value) break;
def.value = assign.right, remove(defs, def), defs.push(def), self1.body[0].body = make_sequence(expr, expr.expressions.slice(1));
continue;
}
}
if (self1.body[0] instanceof AST_EmptyStatement) {
self1.body.splice(0, 1);
continue;
}
if (self1.body[0] instanceof AST_BlockStatement) {
self1.body.splice(0, 1, ...self1.body[0].body);
continue;
}
break;
}
defs = make_node(AST_Var, self1, {
definitions: defs
}), hoisted.push(defs);
}
}
self1.body = dirs.concat(hoisted, self1.body);
}
return self1;
}), AST_Scope.DEFMETHOD("hoist_properties", function(compressor) {
var self1 = this;
if (!compressor.option("hoist_props") || compressor.has_directive("use asm")) return self1;
var top_retain = self1 instanceof AST_Toplevel && compressor.top_retain || return_false, defs_by_id = new Map(), hoister = new TreeTransformer(function(node, descend) {
if (node instanceof AST_Definitions && hoister.parent() instanceof AST_Export) return node;
if (node instanceof AST_VarDef) {
let def, value;
const sym = node.name;
if (sym.scope === self1 && 1 != (def = sym.definition()).escaped && !def.assignments && !def.direct_access && !def.single_use && !compressor.exposed(def) && !top_retain(def) && (value = sym.fixed_value()) === node.value && value instanceof AST_Object && !value.properties.some((prop)=>prop instanceof AST_Expansion || prop.computed_key())) {
descend(node, this);
const defs = new Map(), assignments = [];
return value.properties.forEach(({ key, value })=>{
const scope = find_scope(hoister), symbol = self1.create_symbol(sym.CTOR, {
source: sym,
scope,
conflict_scopes: new Set([
scope,
...sym.definition().references.map((ref)=>ref.scope)
]),
tentative_name: sym.name + "_" + key
});
defs.set(String(key), symbol.definition()), assignments.push(make_node(AST_VarDef, node, {
name: symbol,
value
}));
}), defs_by_id.set(def.id, defs), MAP.splice(assignments);
}
} else if (node instanceof AST_PropAccess && node.expression instanceof AST_SymbolRef) {
const defs = defs_by_id.get(node.expression.definition().id);
if (defs) {
const def = defs.get(String(get_simple_key(node.property))), sym = make_node(AST_SymbolRef, node, {
name: def.name,
scope: node.expression.scope,
thedef: def
});
return sym.reference({}), sym;
}
}
});
return self1.transform(hoister);
}), def_optimize(AST_SimpleStatement, function(self1, compressor) {
if (compressor.option("side_effects")) {
var body = self1.body, node = body.drop_side_effect_free(compressor, !0);
if (!node) return make_node(AST_EmptyStatement, self1);
if (node !== body) return make_node(AST_SimpleStatement, self1, {
body: node
});
}
return self1;
}), def_optimize(AST_While, function(self1, compressor) {
return compressor.option("loops") ? make_node(AST_For, self1, self1).optimize(compressor) : self1;
}), def_optimize(AST_Do, function(self1, compressor) {
if (!compressor.option("loops")) return self1;
var cond = self1.condition.tail_node().evaluate(compressor);
if (!(cond instanceof AST_Node)) {
if (cond) return make_node(AST_For, self1, {
body: make_node(AST_BlockStatement, self1.body, {
body: [
self1.body,
make_node(AST_SimpleStatement, self1.condition, {
body: self1.condition
})
]
})
}).optimize(compressor);
if (!has_break_or_continue(self1, compressor.parent())) return make_node(AST_BlockStatement, self1.body, {
body: [
self1.body,
make_node(AST_SimpleStatement, self1.condition, {
body: self1.condition
})
]
}).optimize(compressor);
}
return self1;
}), def_optimize(AST_For, function(self1, compressor) {
if (!compressor.option("loops")) return self1;
if (compressor.option("side_effects") && self1.init && (self1.init = self1.init.drop_side_effect_free(compressor)), self1.condition) {
var cond = self1.condition.evaluate(compressor);
if (!(cond instanceof AST_Node)) {
if (cond) self1.condition = null;
else if (!compressor.option("dead_code")) {
var orig = self1.condition;
self1.condition = make_node_from_constant(cond, self1.condition), self1.condition = best_of_expression(self1.condition.transform(compressor), orig);
}
}
if (compressor.option("dead_code") && (cond instanceof AST_Node && (cond = self1.condition.tail_node().evaluate(compressor)), !cond)) {
var body = [];
return trim_unreachable_code(compressor, self1.body, body), self1.init instanceof AST_Statement ? body.push(self1.init) : self1.init && body.push(make_node(AST_SimpleStatement, self1.init, {
body: self1.init
})), body.push(make_node(AST_SimpleStatement, self1.condition, {
body: self1.condition
})), make_node(AST_BlockStatement, self1, {
body: body
}).optimize(compressor);
}
}
return function if_break_in_loop(self1, compressor) {
var first = self1.body instanceof AST_BlockStatement ? self1.body.body[0] : self1.body;
if (compressor.option("dead_code") && is_break(first)) {
var body = [];
return self1.init instanceof AST_Statement ? body.push(self1.init) : self1.init && body.push(make_node(AST_SimpleStatement, self1.init, {
body: self1.init
})), self1.condition && body.push(make_node(AST_SimpleStatement, self1.condition, {
body: self1.condition
})), trim_unreachable_code(compressor, self1.body, body), make_node(AST_BlockStatement, self1, {
body: body
});
}
return first instanceof AST_If && (is_break(first.body) ? (self1.condition ? self1.condition = make_node(AST_Binary, self1.condition, {
left: self1.condition,
operator: "&&",
right: first.condition.negate(compressor)
}) : self1.condition = first.condition.negate(compressor), drop_it(first.alternative)) : is_break(first.alternative) && (self1.condition ? self1.condition = make_node(AST_Binary, self1.condition, {
left: self1.condition,
operator: "&&",
right: first.condition
}) : self1.condition = first.condition, drop_it(first.body))), self1;
function is_break(node) {
return node instanceof AST_Break && compressor.loopcontrol_target(node) === compressor.self();
}
function drop_it(rest) {
rest = as_statement_array(rest), self1.body instanceof AST_BlockStatement ? (self1.body = self1.body.clone(), self1.body.body = rest.concat(self1.body.body.slice(1)), self1.body = self1.body.transform(compressor)) : self1.body = make_node(AST_BlockStatement, self1.body, {
body: rest
}).transform(compressor), self1 = if_break_in_loop(self1, compressor);
}
}(self1, compressor);
}), def_optimize(AST_If, function(self1, compressor) {
if (is_empty(self1.alternative) && (self1.alternative = null), !compressor.option("conditionals")) return self1;
// if condition can be statically determined, drop
// one of the blocks. note, statically determined implies
// “has no side effects”; also it doesn't work for cases like
// `x && true`, though it probably should.
var cond = self1.condition.evaluate(compressor);
if (!compressor.option("dead_code") && !(cond instanceof AST_Node)) {
var orig = self1.condition;
self1.condition = make_node_from_constant(cond, orig), self1.condition = best_of_expression(self1.condition.transform(compressor), orig);
}
if (compressor.option("dead_code")) {
if (cond instanceof AST_Node && (cond = self1.condition.tail_node().evaluate(compressor)), cond) {
if (!(cond instanceof AST_Node)) {
var body = [];
return body.push(make_node(AST_SimpleStatement, self1.condition, {
body: self1.condition
})), body.push(self1.body), self1.alternative && trim_unreachable_code(compressor, self1.alternative, body), make_node(AST_BlockStatement, self1, {
body: body
}).optimize(compressor);
}
} else {
var body = [];
return trim_unreachable_code(compressor, self1.body, body), body.push(make_node(AST_SimpleStatement, self1.condition, {
body: self1.condition
})), self1.alternative && body.push(self1.alternative), make_node(AST_BlockStatement, self1, {
body: body
}).optimize(compressor);
}
}
var negated = self1.condition.negate(compressor), self_condition_length = self1.condition.size(), negated_length = negated.size(), negated_is_best = negated_length < self_condition_length;
if (self1.alternative && negated_is_best) {
negated_is_best = !1, // no need to swap values of self_condition_length and negated_length
// here because they are only used in an equality comparison later on.
self1.condition = negated;
var tmp = self1.body;
self1.body = self1.alternative || make_node(AST_EmptyStatement, self1), self1.alternative = tmp;
}
if (is_empty(self1.body) && is_empty(self1.alternative)) return make_node(AST_SimpleStatement, self1.condition, {
body: self1.condition.clone()
}).optimize(compressor);
if (self1.body instanceof AST_SimpleStatement && self1.alternative instanceof AST_SimpleStatement) return make_node(AST_SimpleStatement, self1, {
body: make_node(AST_Conditional, self1, {
condition: self1.condition,
consequent: self1.body.body,
alternative: self1.alternative.body
})
}).optimize(compressor);
if (is_empty(self1.alternative) && self1.body instanceof AST_SimpleStatement) return (self_condition_length === negated_length && !negated_is_best && self1.condition instanceof AST_Binary && "||" == self1.condition.operator && // although the code length of self.condition and negated are the same,
// negated does not require additional surrounding parentheses.
// see https://github.com/mishoo/UglifyJS2/issues/979
(negated_is_best = !0), negated_is_best) ? make_node(AST_SimpleStatement, self1, {
body: make_node(AST_Binary, self1, {
operator: "||",
left: negated,
right: self1.body.body
})
}).optimize(compressor) : make_node(AST_SimpleStatement, self1, {
body: make_node(AST_Binary, self1, {
operator: "&&",
left: self1.condition,
right: self1.body.body
})
}).optimize(compressor);
if (self1.body instanceof AST_EmptyStatement && self1.alternative instanceof AST_SimpleStatement) return make_node(AST_SimpleStatement, self1, {
body: make_node(AST_Binary, self1, {
operator: "||",
left: self1.condition,
right: self1.alternative.body
})
}).optimize(compressor);
if (self1.body instanceof AST_Exit && self1.alternative instanceof AST_Exit && self1.body.TYPE == self1.alternative.TYPE) return make_node(self1.body.CTOR, self1, {
value: make_node(AST_Conditional, self1, {
condition: self1.condition,
consequent: self1.body.value || make_node(AST_Undefined, self1.body),
alternative: self1.alternative.value || make_node(AST_Undefined, self1.alternative)
}).transform(compressor)
}).optimize(compressor);
if (self1.body instanceof AST_If && !self1.body.alternative && !self1.alternative && (self1 = make_node(AST_If, self1, {
condition: make_node(AST_Binary, self1.condition, {
operator: "&&",
left: self1.condition,
right: self1.body.condition
}),
body: self1.body.body,
alternative: null
})), aborts(self1.body) && self1.alternative) {
var alt = self1.alternative;
return self1.alternative = null, make_node(AST_BlockStatement, self1, {
body: [
self1,
alt
]
}).optimize(compressor);
}
if (aborts(self1.alternative)) {
var body = self1.body;
return self1.body = self1.alternative, self1.condition = negated_is_best ? negated : self1.condition.negate(compressor), self1.alternative = null, make_node(AST_BlockStatement, self1, {
body: [
self1,
body
]
}).optimize(compressor);
}
return self1;
}), def_optimize(AST_Switch, function(self1, compressor) {
if (!compressor.option("switches")) return self1;
var branch, default_branch, exact_match, value = self1.expression.evaluate(compressor);
if (!(value instanceof AST_Node)) {
var orig = self1.expression;
self1.expression = make_node_from_constant(value, orig), self1.expression = best_of_expression(self1.expression.transform(compressor), orig);
}
if (!compressor.option("dead_code")) return self1;
value instanceof AST_Node && (value = self1.expression.tail_node().evaluate(compressor));
for(var decl = [], body = [], i = 0, len = self1.body.length; i < len && !exact_match; i++){
if ((branch = self1.body[i]) instanceof AST_Default) default_branch ? eliminate_branch(branch, body[body.length - 1]) : default_branch = branch;
else if (!(value instanceof AST_Node)) {
var exp = branch.expression.evaluate(compressor);
if (!(exp instanceof AST_Node) && exp !== value) {
eliminate_branch(branch, body[body.length - 1]);
continue;
}
if (exp instanceof AST_Node && (exp = branch.expression.tail_node().evaluate(compressor)), exp === value && (exact_match = branch, default_branch)) {
var default_index = body.indexOf(default_branch);
body.splice(default_index, 1), eliminate_branch(default_branch, body[default_index - 1]), default_branch = null;
}
}
body.push(branch);
}
for(; i < len;)eliminate_branch(self1.body[i++], body[body.length - 1]);
self1.body = body;
let default_or_exact = default_branch || exact_match;
// group equivalent branches so they will be located next to each other,
// that way the next micro-optimization will merge them.
// ** bail micro-optimization if not a simple switch case with breaks
if (default_branch = null, exact_match = null, body.every((branch, i)=>(branch === default_or_exact || branch.expression instanceof AST_Constant) && (0 === branch.body.length || aborts(branch) || body.length - 1 === i))) for(let i = 0; i < body.length; i++){
const branch = body[i];
for(let j = i + 1; j < body.length; j++){
const next = body[j];
if (0 === next.body.length) continue;
const last_branch = j === body.length - 1, equivalentBranch = branches_equivalent(next, branch, !1);
if (equivalentBranch || last_branch && branches_equivalent(next, branch, !0)) {
!equivalentBranch && last_branch && next.body.push(make_node(AST_Break));
// let's find previous siblings with inert fallthrough...
let x = j - 1, fallthroughDepth = 0;
for(; x > i;)if (is_inert_body(body[x--])) fallthroughDepth++;
else break;
const plucked = body.splice(j - fallthroughDepth, 1 + fallthroughDepth);
body.splice(i + 1, 0, ...plucked), i += plucked.length;
}
}
}
// merge equivalent branches in a row
for(let i = 0; i < body.length; i++){
let branch = body[i];
if (0 !== branch.body.length && aborts(branch)) for(let j = i + 1; j < body.length; i++, j++){
let next = body[j];
if (0 !== next.body.length) {
if (branches_equivalent(next, branch, !1) || j === body.length - 1 && branches_equivalent(next, branch, !0)) {
branch.body = [], branch = next;
continue;
}
break;
}
}
}
// Prune any empty branches at the end of the switch statement.
{
let i = body.length - 1;
for(; i >= 0; i--){
let bbody = body[i].body;
if (is_break(bbody[bbody.length - 1], compressor) && bbody.pop(), !is_inert_body(body[i])) break;
}
if (// i now points to the index of a branch that contains a body. By incrementing, it's
// pointing to the first branch that's empty.
i++, !default_or_exact || body.indexOf(default_or_exact) >= i) // The default behavior is to do nothing. We can take advantage of that to
// remove all case expressions that are side-effect free that also do
// nothing, since they'll default to doing nothing. But we can't remove any
// case expressions before one that would side-effect, since they may cause
// the side-effect to be skipped.
for(let j = body.length - 1; j >= i; j--){
let branch = body[j];
if (branch === default_or_exact) default_or_exact = null, body.pop();
else if (branch.expression.has_side_effects(compressor)) break;
else body.pop();
}
}
// Prune side-effect free branches that fall into default.
DEFAULT: if (default_or_exact) {
let default_index = body.indexOf(default_or_exact), default_body_index = default_index;
for(; default_body_index < body.length - 1 && is_inert_body(body[default_body_index]); default_body_index++);
if (default_body_index < body.length - 1) break DEFAULT;
let side_effect_index = body.length - 1;
for(; side_effect_index >= 0; side_effect_index--){
let branch = body[side_effect_index];
if (branch !== default_or_exact && branch.expression.has_side_effects(compressor)) break;
}
// If the default behavior comes after any side-effect case expressions,
// then we can fold all side-effect free cases into the default branch.
// If the side-effect case is after the default, then any side-effect
// free cases could prevent the side-effect from occurring.
if (default_body_index > side_effect_index) {
let prev_body_index = default_index - 1;
for(; prev_body_index >= 0 && is_inert_body(body[prev_body_index]); prev_body_index--);
let before = Math.max(side_effect_index, prev_body_index) + 1, after = default_index;
side_effect_index > default_index ? (// If the default falls into the same body as a side-effect
// case, then we need preserve that case and only prune the
// cases after it.
after = side_effect_index, body[side_effect_index].body = body[default_body_index].body) : // The default will be the last branch.
default_or_exact.body = body[default_body_index].body, // Prune everything after the default (or last side-effect case)
// until the next case with a body.
body.splice(after + 1, default_body_index - after), // Prune everything before the default that falls into it.
body.splice(before, default_index - before);
}
}
// See if we can remove the switch entirely if all cases (the default) fall into the same case body.
DEFAULT: if (default_or_exact) {
let caseBody, i = body.findIndex((branch)=>!is_inert_body(branch));
// `i` is equal to one of the following:
// - `-1`, there is no body in the switch statement.
// - `body.length - 1`, all cases fall into the same body.
// - anything else, there are multiple bodies in the switch.
if (i === body.length - 1) {
// All cases fall into the case body.
let branch = body[i];
if (has_nested_break(self1)) break DEFAULT;
// This is the last case body, and we've already pruned any breaks, so it's
// safe to hoist.
caseBody = make_node(AST_BlockStatement, branch, {
body: branch.body
}), branch.body = [];
} else if (-1 !== i) break DEFAULT;
// If no cases cause a side-effect, we can eliminate the switch entirely.
if (!body.find((branch)=>branch !== default_or_exact && branch.expression.has_side_effects(compressor))) return make_node(AST_BlockStatement, self1, {
body: decl.concat(statement(self1.expression), default_or_exact.expression ? statement(default_or_exact.expression) : [], caseBody || [])
}).optimize(compressor);
// If we're this far, either there was no body or all cases fell into the same body.
// If there was no body, then we don't need a default branch (because the default is
// do nothing). If there was a body, we'll extract it to after the switch, so the
// switch's new default is to do nothing and we can still prune it.
const default_index = body.indexOf(default_or_exact);
if (body.splice(default_index, 1), default_or_exact = null, caseBody) // Recurse into switch statement one more time so that we can append the case body
// outside of the switch. This recursion will only happen once since we've pruned
// the default case.
return make_node(AST_BlockStatement, self1, {
body: decl.concat(self1, caseBody)
}).optimize(compressor);
// If we fall here, there is a default branch somewhere, there are no case bodies,
// and there's a side-effect somewhere. Just let the below paths take care of it.
}
if (body.length > 0 && (body[0].body = decl.concat(body[0].body)), 0 == body.length) return make_node(AST_BlockStatement, self1, {
body: decl.concat(statement(self1.expression))
}).optimize(compressor);
if (1 == body.length && !has_nested_break(self1)) {
// This is the last case body, and we've already pruned any breaks, so it's
// safe to hoist.
let branch = body[0];
return make_node(AST_If, self1, {
condition: make_node(AST_Binary, self1, {
operator: "===",
left: self1.expression,
right: branch.expression
}),
body: make_node(AST_BlockStatement, branch, {
body: branch.body
}),
alternative: null
}).optimize(compressor);
}
if (2 === body.length && default_or_exact && !has_nested_break(self1)) {
let branch = body[0] === default_or_exact ? body[1] : body[0], exact_exp = default_or_exact.expression && statement(default_or_exact.expression);
if (aborts(body[0])) {
// Only the first branch body could have a break (at the last statement)
let first = body[0];
return is_break(first.body[first.body.length - 1], compressor) && first.body.pop(), make_node(AST_If, self1, {
condition: make_node(AST_Binary, self1, {
operator: "===",
left: self1.expression,
right: branch.expression
}),
body: make_node(AST_BlockStatement, branch, {
body: branch.body
}),
alternative: make_node(AST_BlockStatement, default_or_exact, {
body: [].concat(exact_exp || [], default_or_exact.body)
})
}).optimize(compressor);
}
let operator = "===", consequent = make_node(AST_BlockStatement, branch, {
body: branch.body
}), always = make_node(AST_BlockStatement, default_or_exact, {
body: [].concat(exact_exp || [], default_or_exact.body)
});
if (body[0] === default_or_exact) {
operator = "!==";
let tmp = always;
always = consequent, consequent = tmp;
}
return make_node(AST_BlockStatement, self1, {
body: [
make_node(AST_If, self1, {
condition: make_node(AST_Binary, self1, {
operator: operator,
left: self1.expression,
right: branch.expression
}),
body: consequent,
alternative: null
})
].concat(always)
}).optimize(compressor);
}
return self1;
function eliminate_branch(branch, prev) {
prev && !aborts(prev) ? prev.body = prev.body.concat(branch.body) : trim_unreachable_code(compressor, branch, decl);
}
function branches_equivalent(branch, prev, insertBreak) {
let bbody = branch.body, pbody = prev.body;
if (insertBreak && (bbody = bbody.concat(make_node(AST_Break))), bbody.length !== pbody.length) return !1;
let bblock = make_node(AST_BlockStatement, branch, {
body: bbody
}), pblock = make_node(AST_BlockStatement, prev, {
body: pbody
});
return bblock.equivalent_to(pblock);
}
function statement(expression) {
return make_node(AST_SimpleStatement, expression, {
body: expression
});
}
function has_nested_break(root) {
let has_break = !1, tw = new TreeWalker((node)=>{
if (has_break || node instanceof AST_Lambda || node instanceof AST_SimpleStatement) return !0;
if (!is_break(node, tw)) return;
let parent = tw.parent();
parent instanceof AST_SwitchBranch && parent.body[parent.body.length - 1] === node || (has_break = !0);
});
return root.walk(tw), has_break;
}
function is_break(node, stack) {
return node instanceof AST_Break && stack.loopcontrol_target(node) === self1;
}
function is_inert_body(branch) {
return !aborts(branch) && !make_node(AST_BlockStatement, branch, {
body: branch.body
}).has_side_effects(compressor);
}
}), def_optimize(AST_Try, function(self1, compressor) {
if (tighten_body(self1.body, compressor), self1.bcatch && self1.bfinally && self1.bfinally.body.every(is_empty) && (self1.bfinally = null), compressor.option("dead_code") && self1.body.every(is_empty)) {
var body = [];
return self1.bcatch && trim_unreachable_code(compressor, self1.bcatch, body), self1.bfinally && body.push(...self1.bfinally.body), make_node(AST_BlockStatement, self1, {
body: body
}).optimize(compressor);
}
return self1;
}), AST_Definitions.DEFMETHOD("remove_initializers", function() {
var decls = [];
this.definitions.forEach(function(def) {
def.name instanceof AST_SymbolDeclaration ? (def.value = null, decls.push(def)) : walk(def.name, (node)=>{
node instanceof AST_SymbolDeclaration && decls.push(make_node(AST_VarDef, def, {
name: node,
value: null
}));
});
}), this.definitions = decls;
}), AST_Definitions.DEFMETHOD("to_assignments", function(compressor) {
var reduce_vars = compressor.option("reduce_vars"), assignments = [];
for (const def of this.definitions){
if (def.value) {
var name = make_node(AST_SymbolRef, def.name, def.name);
assignments.push(make_node(AST_Assign, def, {
operator: "=",
logical: !1,
left: name,
right: def.value
})), reduce_vars && (name.definition().fixed = !1);
} else if (def.value) {
// Because it's a destructuring, do not turn into an assignment.
var varDef = make_node(AST_VarDef, def, {
name: def.name,
value: def.value
}), var_ = make_node(AST_Var, def, {
definitions: [
varDef
]
});
assignments.push(var_);
}
const thedef = def.name.definition();
thedef.eliminated++, thedef.replaced--;
}
return 0 == assignments.length ? null : make_sequence(this, assignments);
}), def_optimize(AST_Definitions, function(self1) {
return 0 == self1.definitions.length ? make_node(AST_EmptyStatement, self1) : self1;
}), def_optimize(AST_VarDef, function(self1, compressor) {
return self1.name instanceof AST_SymbolLet && null != self1.value && is_undefined(self1.value, compressor) && (self1.value = null), self1;
}), def_optimize(AST_Import, function(self1) {
return self1;
}), def_optimize(AST_Call, function(self1, compressor) {
var exp = self1.expression, fn = exp;
inline_array_like_spread(self1.args);
var simple_args = self1.args.every((arg)=>!(arg instanceof AST_Expansion));
if (compressor.option("reduce_vars") && fn instanceof AST_SymbolRef && !has_annotation(self1, _NOINLINE)) {
const fixed = fn.fixed_value();
retain_top_func(fixed, compressor) || (fn = fixed);
}
var is_func = fn instanceof AST_Lambda;
if (is_func && fn.pinned()) return self1;
if (compressor.option("unused") && simple_args && is_func && !fn.uses_arguments) {
for(var pos = 0, last = 0, i = 0, len = self1.args.length; i < len; i++){
if (fn.argnames[i] instanceof AST_Expansion) {
if (has_flag(fn.argnames[i].expression, 0b00000001)) for(; i < len;){
var node = self1.args[i++].drop_side_effect_free(compressor);
node && (self1.args[pos++] = node);
}
else for(; i < len;)self1.args[pos++] = self1.args[i++];
last = pos;
break;
}
var trim = i >= fn.argnames.length;
if (trim || has_flag(fn.argnames[i], 0b00000001)) {
var node = self1.args[i].drop_side_effect_free(compressor);
if (node) self1.args[pos++] = node;
else if (!trim) {
self1.args[pos++] = make_node(AST_Number, self1.args[i], {
value: 0
});
continue;
}
} else self1.args[pos++] = self1.args[i];
last = pos;
}
self1.args.length = last;
}
if (compressor.option("unsafe")) {
if (exp instanceof AST_Dot && "Array" === exp.start.value && "from" === exp.property && 1 === self1.args.length) {
const [argument] = self1.args;
if (argument instanceof AST_Array) return make_node(AST_Array, argument, {
elements: argument.elements
}).optimize(compressor);
}
if (is_undeclared_ref(exp)) switch(exp.name){
case "Array":
if (1 != self1.args.length) return make_node(AST_Array, self1, {
elements: self1.args
}).optimize(compressor);
if (self1.args[0] instanceof AST_Number && self1.args[0].value <= 11) {
const elements = [];
for(let i = 0; i < self1.args[0].value; i++)elements.push(new AST_Hole);
return new AST_Array({
elements
});
}
break;
case "Object":
if (0 == self1.args.length) return make_node(AST_Object, self1, {
properties: []
});
break;
case "String":
if (0 == self1.args.length) return make_node(AST_String, self1, {
value: ""
});
if (self1.args.length <= 1) return make_node(AST_Binary, self1, {
left: self1.args[0],
operator: "+",
right: make_node(AST_String, self1, {
value: ""
})
}).optimize(compressor);
break;
case "Number":
if (0 == self1.args.length) return make_node(AST_Number, self1, {
value: 0
});
if (1 == self1.args.length && compressor.option("unsafe_math")) return make_node(AST_UnaryPrefix, self1, {
expression: self1.args[0],
operator: "+"
}).optimize(compressor);
break;
case "Symbol":
1 == self1.args.length && self1.args[0] instanceof AST_String && compressor.option("unsafe_symbols") && (self1.args.length = 0);
break;
case "Boolean":
if (0 == self1.args.length) return make_node(AST_False, self1);
if (1 == self1.args.length) return make_node(AST_UnaryPrefix, self1, {
expression: make_node(AST_UnaryPrefix, self1, {
expression: self1.args[0],
operator: "!"
}),
operator: "!"
}).optimize(compressor);
break;
case "RegExp":
var params = [];
if (self1.args.length >= 1 && self1.args.length <= 2 && self1.args.every((arg)=>{
var value = arg.evaluate(compressor);
return params.push(value), arg !== value;
})) {
let [source, flags] = params;
const rx = make_node(AST_RegExp, self1, {
value: {
source: source = regexp_source_fix(new RegExp(source).source),
flags
}
});
if (rx._eval(compressor) !== rx) return rx;
}
}
else if (exp instanceof AST_Dot) switch(exp.property){
case "toString":
if (0 == self1.args.length && !exp.expression.may_throw_on_access(compressor)) return make_node(AST_Binary, self1, {
left: make_node(AST_String, self1, {
value: ""
}),
operator: "+",
right: exp.expression
}).optimize(compressor);
break;
case "join":
if (exp.expression instanceof AST_Array) {
EXIT: if (!(self1.args.length > 0) || (separator = self1.args[0].evaluate(compressor)) !== self1.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, self1, {
value: consts.join(separator)
})), consts.length = 0), elements.push(el));
}
if (consts.length > 0 && elements.push(make_node(AST_String, self1, {
value: consts.join(separator)
})), 0 == elements.length) return make_node(AST_String, self1, {
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, self1, {
value: ""
}),
right: elements[0]
});
}
if ("" == separator) return first = elements[0].is_string(compressor) || elements[1].is_string(compressor) ? elements.shift() : make_node(AST_String, self1, {
value: ""
}), elements.reduce(function(prev, el) {
return make_node(AST_Binary, el, {
operator: "+",
left: prev,
right: el
});
}, first).optimize(compressor);
// need this awkward cloning to not affect original element
// best_of will decide which one to get through.
var node = self1.clone();
return node.expression = node.expression.clone(), node.expression.expression = node.expression.expression.clone(), node.expression.expression.elements = elements, best_of(compressor, self1, node);
}
}
break;
case "charAt":
if (exp.expression.is_string(compressor)) {
var arg = self1.args[0], index = arg ? arg.evaluate(compressor) : 0;
if (index !== arg) return make_node(AST_Sub, exp, {
expression: exp.expression,
property: make_node_from_constant(0 | index, arg || exp)
}).optimize(compressor);
}
break;
case "apply":
if (2 == self1.args.length && self1.args[1] instanceof AST_Array) {
var args = self1.args[1].elements.slice();
return args.unshift(self1.args[0]), make_node(AST_Call, self1, {
expression: make_node(AST_Dot, exp, {
expression: exp.expression,
optional: !1,
property: "call"
}),
args: args
}).optimize(compressor);
}
break;
case "call":
var func = exp.expression;
if (func instanceof AST_SymbolRef && (func = func.fixed_value()), func instanceof AST_Lambda && !func.contains_this()) return (self1.args.length ? make_sequence(this, [
self1.args[0],
make_node(AST_Call, self1, {
expression: exp.expression,
args: self1.args.slice(1)
})
]) : make_node(AST_Call, self1, {
expression: exp.expression,
args: []
})).optimize(compressor);
}
}
if (compressor.option("unsafe_Function") && is_undeclared_ref(exp) && "Function" == exp.name) {
// new Function() => function(){}
if (0 == self1.args.length) return make_node(AST_Function, self1, {
argnames: [],
body: []
}).optimize(compressor);
var nth_identifier = compressor.mangle_options && compressor.mangle_options.nth_identifier || base54;
if (self1.args.every((x)=>x instanceof AST_String)) // quite a corner-case, but we can handle it:
// https://github.com/mishoo/UglifyJS2/issues/203
// if the code argument is a constant, then we can minify it.
try {
var fun, code = "n(function(" + self1.args.slice(0, -1).map(function(arg) {
return arg.value;
}).join(",") + "){" + self1.args[self1.args.length - 1].value + "})", ast = parse(code), mangle = {
ie8: compressor.option("ie8"),
nth_identifier: nth_identifier
};
ast.figure_out_scope(mangle);
var comp = new Compressor(compressor.options, {
mangle_options: compressor.mangle_options
});
(ast = ast.transform(comp)).figure_out_scope(mangle), ast.compute_char_frequency(mangle), ast.mangle_names(mangle), walk(ast, (node)=>{
if (is_func_expr(node)) return fun = node, walk_abort;
});
var code = OutputStream();
return AST_BlockStatement.prototype._codegen.call(fun, fun, code), self1.args = [
make_node(AST_String, self1, {
value: fun.argnames.map(function(arg) {
return arg.print_to_string();
}).join(",")
}),
make_node(AST_String, self1.args[self1.args.length - 1], {
value: code.get().replace(/^{|}$/g, "")
})
], self1;
} catch (ex) {
if (!(ex instanceof JS_Parse_Error)) throw ex;
// Otherwise, it crashes at runtime. Or maybe it's nonstandard syntax.
}
}
var stat = is_func && fn.body[0], is_regular_func = is_func && !fn.is_generator && !fn.async, can_inline = is_regular_func && compressor.option("inline") && !self1.is_callee_pure(compressor);
if (can_inline && stat instanceof AST_Return) {
let returned = stat.value;
if (!returned || returned.is_constant_expression()) {
returned = returned ? returned.clone(!0) : make_node(AST_Undefined, self1);
const args = self1.args.concat(returned);
return make_sequence(self1, args).optimize(compressor);
}
// optimize identity function
if (1 === fn.argnames.length && fn.argnames[0] instanceof AST_SymbolFunarg && self1.args.length < 2 && returned instanceof AST_SymbolRef && returned.name === fn.argnames[0].name) {
let parent;
const replacement = (self1.args[0] || make_node(AST_Undefined)).optimize(compressor);
return replacement instanceof AST_PropAccess && (parent = compressor.parent()) instanceof AST_Call && parent.expression === self1 ? make_sequence(self1, [
make_node(AST_Number, self1, {
value: 0
}),
replacement
]) : replacement;
}
}
if (can_inline) {
let def, returned_value, nearest_scope;
var scope, in_loop, level = -1;
if (simple_args && !fn.uses_arguments && !(compressor.parent() instanceof AST_Class) && !(fn.name && fn instanceof AST_Function) && (returned_value = function(stat) {
var body = fn.body, len = body.length;
if (3 > compressor.option("inline")) return 1 == len && return_value(stat);
stat = null;
for(var i = 0; i < len; i++){
var line = body[i];
if (line instanceof AST_Var) {
if (stat && !line.definitions.every((var_def)=>!var_def.value)) return !1;
} else {
if (stat) return !1;
line instanceof AST_EmptyStatement || (stat = line);
}
}
return return_value(stat);
}(stat)) && (exp === fn || has_annotation(self1, _INLINE) || compressor.option("unused") && 1 == (def = exp.definition()).references.length && !is_recursive_ref(compressor, def) && fn.is_constant_expression(exp.scope)) && !has_annotation(self1, _PURE | _NOINLINE) && !fn.contains_this() && function() {
var block_scoped = new Set();
do if ((scope = compressor.parent(++level)).is_block_scope() && scope.block_scope && // TODO this is sometimes undefined during compression.
// But it should always have a value!
scope.block_scope.variables.forEach(function(variable) {
block_scoped.add(variable.name);
}), scope instanceof AST_Catch) // TODO can we delete? AST_Catch is a block scope.
scope.argname && block_scoped.add(scope.argname.name);
else if (scope instanceof AST_IterationStatement) in_loop = [];
else if (scope instanceof AST_SymbolRef && scope.fixed_value() instanceof AST_Scope) return !1;
while (!(scope instanceof AST_Scope))
var safe_to_inject = !(scope instanceof AST_Toplevel) || compressor.toplevel.vars, inline = compressor.option("inline");
return !!function(block_scoped, safe_to_inject) {
for(var len = fn.body.length, i = 0; i < len; i++){
var stat = fn.body[i];
if (stat instanceof AST_Var) {
if (!safe_to_inject) return !1;
for(var j = stat.definitions.length; --j >= 0;){
var name = stat.definitions[j].name;
if (name instanceof AST_Destructuring || block_scoped.has(name.name) || identifier_atom.has(name.name) || scope.conflicting_def(name.name)) return !1;
in_loop && in_loop.push(name.definition());
}
}
}
return !0;
}(block_scoped, inline >= 3 && safe_to_inject) && !!function(block_scoped, safe_to_inject) {
for(var i = 0, len = fn.argnames.length; i < len; i++){
var arg = fn.argnames[i];
if (arg instanceof AST_DefaultAssign) {
if (has_flag(arg.left, 0b00000001)) continue;
return !1;
}
if (arg instanceof AST_Destructuring) return !1;
if (arg instanceof AST_Expansion) {
if (has_flag(arg.expression, 0b00000001)) continue;
return !1;
}
if (!has_flag(arg, 0b00000001)) {
if (!safe_to_inject || block_scoped.has(arg.name) || identifier_atom.has(arg.name) || scope.conflicting_def(arg.name)) return !1;
in_loop && in_loop.push(arg.definition());
}
}
return !0;
}(block_scoped, inline >= 2 && safe_to_inject) && (!in_loop || 0 == in_loop.length || !is_reachable(fn, in_loop));
}() && (nearest_scope = find_scope(compressor)) && !scope_encloses_variables_in_this_scope(nearest_scope, fn) && !function() {
// Due to the fact function parameters have their own scope
// which can't use `var something` in the function body within,
// we simply don't inline into DefaultAssign.
let p, i = 0;
for(; p = compressor.parent(i++);){
if (p instanceof AST_DefaultAssign) return !0;
if (p instanceof AST_Block) break;
}
return !1;
}() && !(scope instanceof AST_Class)) return set_flag(fn, 0b0000000100000000), nearest_scope.add_child_scope(fn), make_sequence(self1, function(returned_value) {
var decls = [], expressions = [];
if (function(decls, expressions) {
for(var len = fn.argnames.length, i = self1.args.length; --i >= len;)expressions.push(self1.args[i]);
for(i = len; --i >= 0;){
var name = fn.argnames[i], value = self1.args[i];
if (has_flag(name, 0b00000001) || !name.name || scope.conflicting_def(name.name)) value && expressions.push(value);
else {
var symbol = make_node(AST_SymbolVar, name, name);
name.definition().orig.push(symbol), !value && in_loop && (value = make_node(AST_Undefined, self1)), append_var(decls, expressions, symbol, value);
}
}
decls.reverse(), expressions.reverse();
}(decls, expressions), function(decls, expressions) {
for(var pos = expressions.length, i = 0, lines = fn.body.length; i < lines; i++){
var stat = fn.body[i];
if (stat instanceof AST_Var) for(var j = 0, defs = stat.definitions.length; j < defs; j++){
var var_def = stat.definitions[j], name = var_def.name;
if (append_var(decls, expressions, name, var_def.value), in_loop && fn.argnames.every((argname)=>argname.name != name.name)) {
var def = fn.variables.get(name.name), sym = make_node(AST_SymbolRef, name, name);
def.references.push(sym), expressions.splice(pos++, 0, make_node(AST_Assign, var_def, {
operator: "=",
logical: !1,
left: sym,
right: make_node(AST_Undefined, name)
}));
}
}
}
}(decls, expressions), expressions.push(returned_value), decls.length) {
const i = scope.body.indexOf(compressor.parent(level - 1)) + 1;
scope.body.splice(i, 0, make_node(AST_Var, fn, {
definitions: decls
}));
}
return expressions.map((exp)=>exp.clone(!0));
}(returned_value)).optimize(compressor);
}
if (can_inline && has_annotation(self1, _INLINE)) return set_flag(fn, 0b0000000100000000), (fn = (fn = make_node(fn.CTOR === AST_Defun ? AST_Function : fn.CTOR, fn, fn)).clone(!0)).figure_out_scope({}, {
parent_scope: find_scope(compressor),
toplevel: compressor.get_toplevel()
}), make_node(AST_Call, self1, {
expression: fn,
args: self1.args
}).optimize(compressor);
if (is_regular_func && compressor.option("side_effects") && fn.body.every(is_empty)) {
var args = self1.args.concat(make_node(AST_Undefined, self1));
return make_sequence(self1, args).optimize(compressor);
}
if (compressor.option("negate_iife") && compressor.parent() instanceof AST_SimpleStatement && is_iife_call(self1)) return self1.negate(compressor, !0);
var ev = self1.evaluate(compressor);
if (ev !== self1) return ev = make_node_from_constant(ev, self1).optimize(compressor), best_of(compressor, ev, self1);
return self1;
function return_value(stat) {
return stat ? stat instanceof AST_Return ? stat.value ? stat.value.clone(!0) : make_node(AST_Undefined, self1) : stat instanceof AST_SimpleStatement ? make_node(AST_UnaryPrefix, stat, {
operator: "void",
expression: stat.body.clone(!0)
}) : void 0 : make_node(AST_Undefined, self1);
}
function append_var(decls, expressions, name, value) {
var def = name.definition();
scope.variables.has(name.name) || (scope.variables.set(name.name, def), scope.enclosed.push(def), decls.push(make_node(AST_VarDef, name, {
name: name,
value: null
})));
var sym = make_node(AST_SymbolRef, name, name);
def.references.push(sym), value && expressions.push(make_node(AST_Assign, self1, {
operator: "=",
logical: !1,
left: sym,
right: value.clone()
}));
}
}), def_optimize(AST_New, function(self1, compressor) {
return compressor.option("unsafe") && is_undeclared_ref(self1.expression) && [
"Object",
"RegExp",
"Function",
"Error",
"Array"
].includes(self1.expression.name) ? make_node(AST_Call, self1, self1).transform(compressor) : self1;
}), def_optimize(AST_Sequence, function(self1, compressor) {
if (!compressor.option("side_effects")) return self1;
var first, last, expressions = [];
first = first_in_statement(compressor), last = self1.expressions.length - 1, self1.expressions.forEach(function(expr, index) {
index < last && (expr = expr.drop_side_effect_free(compressor, first)), expr && (merge_sequence(expressions, expr), first = !1);
});
var end = expressions.length - 1;
return (function() {
for(; end > 0 && is_undefined(expressions[end], compressor);)end--;
end < expressions.length - 1 && (expressions[end] = make_node(AST_UnaryPrefix, self1, {
operator: "void",
expression: expressions[end]
}), expressions.length = end + 1);
}(), 0 == end) ? (self1 = maintain_this_binding(compressor.parent(), compressor.self(), expressions[0])) instanceof AST_Sequence || (self1 = self1.optimize(compressor)) : self1.expressions = expressions, self1;
}), AST_Unary.DEFMETHOD("lift_sequences", function(compressor) {
if (compressor.option("sequences") && this.expression instanceof AST_Sequence) {
var x = this.expression.expressions.slice(), e = this.clone();
return e.expression = x.pop(), x.push(e), make_sequence(this, x).optimize(compressor);
}
return this;
}), def_optimize(AST_UnaryPostfix, function(self1, compressor) {
return self1.lift_sequences(compressor);
}), def_optimize(AST_UnaryPrefix, function(self1, compressor) {
var e = self1.expression;
if ("delete" == self1.operator && !(e instanceof AST_SymbolRef || e instanceof AST_PropAccess || e instanceof AST_Chain || is_identifier_atom(e))) return make_sequence(self1, [
e,
make_node(AST_True, self1)
]).optimize(compressor);
var seq = self1.lift_sequences(compressor);
if (seq !== self1) return seq;
if (compressor.option("side_effects") && "void" == self1.operator) return (e = e.drop_side_effect_free(compressor)) ? (self1.expression = e, self1) : make_node(AST_Undefined, self1).optimize(compressor);
if (compressor.in_boolean_context()) switch(self1.operator){
case "!":
if (e instanceof AST_UnaryPrefix && "!" == e.operator) // !!foo ==> foo, if we're in boolean context
return e.expression;
e instanceof AST_Binary && (self1 = best_of(compressor, self1, e.negate(compressor, first_in_statement(compressor))));
break;
case "typeof":
// typeof always returns a non-empty string, thus it's
// always true in booleans
// And we don't need to check if it's undeclared, because in typeof, that's OK
return (e instanceof AST_SymbolRef ? make_node(AST_True, self1) : make_sequence(self1, [
e,
make_node(AST_True, self1)
])).optimize(compressor);
}
if ("-" == self1.operator && e instanceof AST_Infinity && (e = e.transform(compressor)), e instanceof AST_Binary && ("+" == self1.operator || "-" == self1.operator) && ("*" == e.operator || "/" == e.operator || "%" == e.operator)) return make_node(AST_Binary, self1, {
operator: e.operator,
left: make_node(AST_UnaryPrefix, e.left, {
operator: self1.operator,
expression: e.left
}),
right: e.right
});
// avoids infinite recursion of numerals
if ("-" != self1.operator || !(e instanceof AST_Number || e instanceof AST_Infinity || e instanceof AST_BigInt)) {
var ev = self1.evaluate(compressor);
if (ev !== self1) return ev = make_node_from_constant(ev, self1).optimize(compressor), best_of(compressor, ev, self1);
}
return self1;
}), AST_Binary.DEFMETHOD("lift_sequences", function(compressor) {
if (compressor.option("sequences")) {
if (this.left instanceof AST_Sequence) {
var x = this.left.expressions.slice(), e = this.clone();
return e.left = x.pop(), x.push(e), make_sequence(this, x).optimize(compressor);
}
if (this.right instanceof AST_Sequence && !this.left.has_side_effects(compressor)) {
for(var assign = "=" == this.operator && this.left instanceof AST_SymbolRef, x = this.right.expressions, last = x.length - 1, i = 0; i < last && !(!assign && x[i].has_side_effects(compressor)); i++);
if (i == last) {
x = x.slice();
var e = this.clone();
return e.right = x.pop(), x.push(e), make_sequence(this, x).optimize(compressor);
}
if (i > 0) {
var e = this.clone();
return e.right = make_sequence(this.right, x.slice(i)), (x = x.slice(0, i)).push(e), make_sequence(this, x).optimize(compressor);
}
}
}
return this;
});
var commutativeOperators = makePredicate("== === != !== * & | ^");
function scope_encloses_variables_in_this_scope(scope, pulled_scope) {
for (const enclosed of pulled_scope.enclosed){
if (pulled_scope.variables.has(enclosed.name)) continue;
const looked_up = scope.find_variable(enclosed.name);
if (looked_up) {
if (looked_up === enclosed) continue;
return !0;
}
}
return !1;
}
function is_atomic(lhs, self1) {
return lhs instanceof AST_SymbolRef || lhs.TYPE === self1.TYPE;
}
function is_reachable(self1, defs) {
const find_ref = (node)=>{
if (node instanceof AST_SymbolRef && member(node.definition(), defs)) return walk_abort;
};
return walk_parent(self1, (node, info)=>{
if (node instanceof AST_Scope && node !== self1) {
var parent = info.parent();
return parent instanceof AST_Call && parent.expression === node && !(node.async || node.is_generator) ? void 0 : !walk(node, find_ref) || walk_abort;
}
});
}
def_optimize(AST_Binary, function(self1, compressor) {
function reversible() {
return self1.left.is_constant() || self1.right.is_constant() || !self1.left.has_side_effects(compressor) && !self1.right.has_side_effects(compressor);
}
function reverse(op) {
if (reversible()) {
op && (self1.operator = op);
var tmp = self1.left;
self1.left = self1.right, self1.right = tmp;
}
}
if (commutativeOperators.has(self1.operator) && self1.right.is_constant() && !self1.left.is_constant() && !(self1.left instanceof AST_Binary && PRECEDENCE[self1.left.operator] >= PRECEDENCE[self1.operator]) && reverse(), self1 = self1.lift_sequences(compressor), compressor.option("comparisons")) switch(self1.operator){
case "===":
case "!==":
var is_strict_comparison = !0;
(self1.left.is_string(compressor) && self1.right.is_string(compressor) || self1.left.is_number(compressor) && self1.right.is_number(compressor) || self1.left.is_boolean() && self1.right.is_boolean() || self1.left.equivalent_to(self1.right)) && (self1.operator = self1.operator.substr(0, 2));
// XXX: intentionally falling down to the next case
case "==":
case "!=":
// void 0 == x => null == x
if (!is_strict_comparison && is_undefined(self1.left, compressor)) self1.left = make_node(AST_Null, self1.left);
else if (compressor.option("typeofs") && self1.left instanceof AST_String && "undefined" == self1.left.value && self1.right instanceof AST_UnaryPrefix && "typeof" == self1.right.operator) {
var node, expr = self1.right.expression;
(expr instanceof AST_SymbolRef ? expr.is_declared(compressor) : !(expr instanceof AST_PropAccess && compressor.option("ie8"))) && (self1.right = expr, self1.left = make_node(AST_Undefined, self1.left).optimize(compressor), 2 == self1.operator.length && (self1.operator += "="));
} else if (self1.left instanceof AST_SymbolRef && self1.right instanceof AST_SymbolRef && self1.left.definition() === self1.right.definition() && ((node = self1.left.fixed_value()) instanceof AST_Array || node instanceof AST_Lambda || node instanceof AST_Object || node instanceof AST_Class)) return make_node("=" == self1.operator[0] ? AST_True : AST_False, self1);
break;
case "&&":
case "||":
var lhs = self1.left;
if (lhs.operator == self1.operator && (lhs = lhs.right), lhs instanceof AST_Binary && lhs.operator == ("&&" == self1.operator ? "!==" : "===") && self1.right instanceof AST_Binary && lhs.operator == self1.right.operator && (is_undefined(lhs.left, compressor) && self1.right.left instanceof AST_Null || lhs.left instanceof AST_Null && is_undefined(self1.right.left, compressor)) && !lhs.right.has_side_effects(compressor) && lhs.right.equivalent_to(self1.right.right)) {
var combined = make_node(AST_Binary, self1, {
operator: lhs.operator.slice(0, -1),
left: make_node(AST_Null, self1),
right: lhs.right
});
return lhs !== self1.left && (combined = make_node(AST_Binary, self1, {
operator: self1.operator,
left: self1.left.left,
right: combined
})), combined;
}
}
if ("+" == self1.operator && compressor.in_boolean_context()) {
var ll = self1.left.evaluate(compressor), rr = self1.right.evaluate(compressor);
if (ll && "string" == typeof ll) return make_sequence(self1, [
self1.right,
make_node(AST_True, self1)
]).optimize(compressor);
if (rr && "string" == typeof rr) return make_sequence(self1, [
self1.left,
make_node(AST_True, self1)
]).optimize(compressor);
}
if (compressor.option("comparisons") && self1.is_boolean()) {
if (!(compressor.parent() instanceof AST_Binary) || compressor.parent() instanceof AST_Assign) {
var negated = make_node(AST_UnaryPrefix, self1, {
operator: "!",
expression: self1.negate(compressor, first_in_statement(compressor))
});
self1 = best_of(compressor, self1, negated);
}
if (compressor.option("unsafe_comps")) switch(self1.operator){
case "<":
reverse(">");
break;
case "<=":
reverse(">=");
}
}
if ("+" == self1.operator) {
if (self1.right instanceof AST_String && "" == self1.right.getValue() && self1.left.is_string(compressor)) return self1.left;
if (self1.left instanceof AST_String && "" == self1.left.getValue() && self1.right.is_string(compressor)) return self1.right;
if (self1.left instanceof AST_Binary && "+" == self1.left.operator && self1.left.left instanceof AST_String && "" == self1.left.left.getValue() && self1.right.is_string(compressor)) return self1.left = self1.left.right, self1;
}
if (compressor.option("evaluate")) {
switch(self1.operator){
case "&&":
var ll = !!has_flag(self1.left, 0b00000010) || !has_flag(self1.left, 0b00000100) && self1.left.evaluate(compressor);
if (!ll) return maintain_this_binding(compressor.parent(), compressor.self(), self1.left).optimize(compressor);
if (!(ll instanceof AST_Node)) return make_sequence(self1, [
self1.left,
self1.right
]).optimize(compressor);
var rr = self1.right.evaluate(compressor);
if (rr) {
if (!(rr instanceof AST_Node)) {
var parent = compressor.parent();
if ("&&" == parent.operator && parent.left === compressor.self() || compressor.in_boolean_context()) return self1.left.optimize(compressor);
}
} else {
if (compressor.in_boolean_context()) return make_sequence(self1, [
self1.left,
make_node(AST_False, self1)
]).optimize(compressor);
set_flag(self1, 0b00000100);
}
// x || false && y ---> x ? y : false
if ("||" == self1.left.operator) {
var lr = self1.left.right.evaluate(compressor);
if (!lr) return make_node(AST_Conditional, self1, {
condition: self1.left.left,
consequent: self1.right,
alternative: self1.left.right
}).optimize(compressor);
}
break;
case "||":
var ll = !!has_flag(self1.left, 0b00000010) || !has_flag(self1.left, 0b00000100) && self1.left.evaluate(compressor);
if (!ll) return make_sequence(self1, [
self1.left,
self1.right
]).optimize(compressor);
if (!(ll instanceof AST_Node)) return maintain_this_binding(compressor.parent(), compressor.self(), self1.left).optimize(compressor);
var rr = self1.right.evaluate(compressor);
if (rr) {
if (!(rr instanceof AST_Node)) {
if (compressor.in_boolean_context()) return make_sequence(self1, [
self1.left,
make_node(AST_True, self1)
]).optimize(compressor);
set_flag(self1, 0b00000010);
}
} else {
var parent = compressor.parent();
if ("||" == parent.operator && parent.left === compressor.self() || compressor.in_boolean_context()) return self1.left.optimize(compressor);
}
if ("&&" == self1.left.operator) {
var lr = self1.left.right.evaluate(compressor);
if (lr && !(lr instanceof AST_Node)) return make_node(AST_Conditional, self1, {
condition: self1.left.left,
consequent: self1.left.right,
alternative: self1.right
}).optimize(compressor);
}
break;
case "??":
if (is_nullish(self1.left, compressor)) return self1.right;
var ll = self1.left.evaluate(compressor);
if (!(ll instanceof AST_Node)) // if we know the value for sure we can simply compute right away.
return null == ll ? self1.right : self1.left;
if (compressor.in_boolean_context()) {
const rr = self1.right.evaluate(compressor);
if (!(rr instanceof AST_Node) && !rr) return self1.left;
}
}
var associative = !0;
switch(self1.operator){
case "+":
// (x + "foo") + "bar" => x + "foobar"
if (self1.right instanceof AST_Constant && self1.left instanceof AST_Binary && "+" == self1.left.operator && self1.left.is_string(compressor)) {
var binary = make_node(AST_Binary, self1, {
operator: "+",
left: self1.left.right,
right: self1.right
}), r = binary.optimize(compressor);
binary !== r && (self1 = make_node(AST_Binary, self1, {
operator: "+",
left: self1.left.left,
right: r
}));
}
// (x + "foo") + ("bar" + y) => (x + "foobar") + y
if (self1.left instanceof AST_Binary && "+" == self1.left.operator && self1.left.is_string(compressor) && self1.right instanceof AST_Binary && "+" == self1.right.operator && self1.right.is_string(compressor)) {
var binary = make_node(AST_Binary, self1, {
operator: "+",
left: self1.left.right,
right: self1.right.left
}), m = binary.optimize(compressor);
binary !== m && (self1 = make_node(AST_Binary, self1, {
operator: "+",
left: make_node(AST_Binary, self1.left, {
operator: "+",
left: self1.left.left,
right: m
}),
right: self1.right.right
}));
}
// a + -b => a - b
if (self1.right instanceof AST_UnaryPrefix && "-" == self1.right.operator && self1.left.is_number(compressor)) {
self1 = make_node(AST_Binary, self1, {
operator: "-",
left: self1.left,
right: self1.right.expression
});
break;
}
// -a + b => b - a
if (self1.left instanceof AST_UnaryPrefix && "-" == self1.left.operator && reversible() && self1.right.is_number(compressor)) {
self1 = make_node(AST_Binary, self1, {
operator: "-",
left: self1.right,
right: self1.left.expression
});
break;
}
// `foo${bar}baz` + 1 => `foo${bar}baz1`
if (self1.left instanceof AST_TemplateString) {
var l = self1.left, r = self1.right.evaluate(compressor);
if (r != self1.right) return l.segments[l.segments.length - 1].value += String(r), l;
}
// 1 + `foo${bar}baz` => `1foo${bar}baz`
if (self1.right instanceof AST_TemplateString) {
var r = self1.right, l = self1.left.evaluate(compressor);
if (l != self1.left) return r.segments[0].value = String(l) + r.segments[0].value, r;
}
// `1${bar}2` + `foo${bar}baz` => `1${bar}2foo${bar}baz`
if (self1.left instanceof AST_TemplateString && self1.right instanceof AST_TemplateString) {
var l = self1.left, segments = l.segments, r = self1.right;
segments[segments.length - 1].value += r.segments[0].value;
for(var i = 1; i < r.segments.length; i++)segments.push(r.segments[i]);
return l;
}
case "*":
associative = compressor.option("unsafe_math");
case "&":
case "|":
case "^":
// a + +b => +b + a
if (self1.left.is_number(compressor) && self1.right.is_number(compressor) && reversible() && !(self1.left instanceof AST_Binary && self1.left.operator != self1.operator && PRECEDENCE[self1.left.operator] >= PRECEDENCE[self1.operator])) {
var reversed = make_node(AST_Binary, self1, {
operator: self1.operator,
left: self1.right,
right: self1.left
});
self1 = self1.right instanceof AST_Constant && !(self1.left instanceof AST_Constant) ? best_of(compressor, reversed, self1) : best_of(compressor, self1, reversed);
}
associative && self1.is_number(compressor) && (self1.right instanceof AST_Binary && self1.right.operator == self1.operator && (self1 = make_node(AST_Binary, self1, {
operator: self1.operator,
left: make_node(AST_Binary, self1.left, {
operator: self1.operator,
left: self1.left,
right: self1.right.left,
start: self1.left.start,
end: self1.right.left.end
}),
right: self1.right.right
})), self1.right instanceof AST_Constant && self1.left instanceof AST_Binary && self1.left.operator == self1.operator && (self1.left.left instanceof AST_Constant ? self1 = make_node(AST_Binary, self1, {
operator: self1.operator,
left: make_node(AST_Binary, self1.left, {
operator: self1.operator,
left: self1.left.left,
right: self1.right,
start: self1.left.left.start,
end: self1.right.end
}),
right: self1.left.right
}) : self1.left.right instanceof AST_Constant && (self1 = make_node(AST_Binary, self1, {
operator: self1.operator,
left: make_node(AST_Binary, self1.left, {
operator: self1.operator,
left: self1.left.right,
right: self1.right,
start: self1.left.right.start,
end: self1.right.end
}),
right: self1.left.left
}))), self1.left instanceof AST_Binary && self1.left.operator == self1.operator && self1.left.right instanceof AST_Constant && self1.right instanceof AST_Binary && self1.right.operator == self1.operator && self1.right.left instanceof AST_Constant && (self1 = make_node(AST_Binary, self1, {
operator: self1.operator,
left: make_node(AST_Binary, self1.left, {
operator: self1.operator,
left: make_node(AST_Binary, self1.left.left, {
operator: self1.operator,
left: self1.left.right,
right: self1.right.left,
start: self1.left.right.start,
end: self1.right.left.end
}),
right: self1.left.left
}),
right: self1.right.right
})));
}
}
// x && (y && z) ==> x && y && z
// x || (y || z) ==> x || y || z
// x + ("y" + z) ==> x + "y" + z
// "x" + (y + "z")==> "x" + y + "z"
if (self1.right instanceof AST_Binary && self1.right.operator == self1.operator && (lazy_op.has(self1.operator) || "+" == self1.operator && (self1.right.left.is_string(compressor) || self1.left.is_string(compressor) && self1.right.right.is_string(compressor)))) return self1.left = make_node(AST_Binary, self1.left, {
operator: self1.operator,
left: self1.left.transform(compressor),
right: self1.right.left.transform(compressor)
}), self1.right = self1.right.right.transform(compressor), self1.transform(compressor);
var ev = self1.evaluate(compressor);
return ev !== self1 ? (ev = make_node_from_constant(ev, self1).optimize(compressor), best_of(compressor, ev, self1)) : self1;
}), def_optimize(AST_SymbolExport, function(self1) {
return self1;
}), def_optimize(AST_SymbolRef, function(self1, compressor) {
if (!compressor.option("ie8") && is_undeclared_ref(self1) && !compressor.find_parent(AST_With)) switch(self1.name){
case "undefined":
return make_node(AST_Undefined, self1).optimize(compressor);
case "NaN":
return make_node(AST_NaN, self1).optimize(compressor);
case "Infinity":
return make_node(AST_Infinity, self1).optimize(compressor);
}
const parent = compressor.parent();
if (compressor.option("reduce_vars") && is_lhs(self1, parent) !== self1) {
const def = self1.definition(), nearest_scope = find_scope(compressor);
if (compressor.top_retain && def.global && compressor.top_retain(def)) return def.fixed = !1, def.single_use = !1, self1;
let fixed = self1.fixed_value(), single_use = def.single_use && !(parent instanceof AST_Call && parent.is_callee_pure(compressor) || has_annotation(parent, _NOINLINE)) && !(parent instanceof AST_Export && fixed instanceof AST_Lambda && fixed.name);
if (single_use && fixed instanceof AST_Node && (single_use = !fixed.has_side_effects(compressor) && !fixed.may_throw(compressor)), single_use && (fixed instanceof AST_Lambda || fixed instanceof AST_Class)) {
if (retain_top_func(fixed, compressor)) single_use = !1;
else if (def.scope !== self1.scope && (1 == def.escaped || has_flag(fixed, 0b00010000) || function(compressor) {
for(var node, level = 0; (node = compressor.parent(level++)) && !(node instanceof AST_Statement);)if (node instanceof AST_Array || node instanceof AST_ObjectKeyVal || node instanceof AST_Object) return !0;
return !1;
}(compressor) || !compressor.option("reduce_funcs"))) single_use = !1;
else if (is_recursive_ref(compressor, def)) single_use = !1;
else if ((def.scope !== self1.scope || def.orig[0] instanceof AST_SymbolFunarg) && "f" == (single_use = fixed.is_constant_expression(self1.scope))) {
var scope = self1.scope;
do (scope instanceof AST_Defun || is_func_expr(scope)) && set_flag(scope, 0b00010000);
while (scope = scope.parent_scope)
}
}
if (single_use && fixed instanceof AST_Lambda && (single_use = def.scope === self1.scope && !scope_encloses_variables_in_this_scope(nearest_scope, fixed) || parent instanceof AST_Call && parent.expression === self1 && !scope_encloses_variables_in_this_scope(nearest_scope, fixed) && !(fixed.name && fixed.name.definition().recursive_refs > 0)), single_use && fixed) {
if (fixed instanceof AST_DefClass && (set_flag(fixed, 0b0000000100000000), fixed = make_node(AST_ClassExpression, fixed, fixed)), fixed instanceof AST_Defun && (set_flag(fixed, 0b0000000100000000), fixed = make_node(AST_Function, fixed, fixed)), def.recursive_refs > 0 && fixed.name instanceof AST_SymbolDefun) {
const defun_def = fixed.name.definition();
let lambda_def = fixed.variables.get(fixed.name.name), name = lambda_def && lambda_def.orig[0];
name instanceof AST_SymbolLambda || ((name = make_node(AST_SymbolLambda, fixed.name, fixed.name)).scope = fixed, fixed.name = name, lambda_def = fixed.def_function(name)), walk(fixed, (node)=>{
node instanceof AST_SymbolRef && node.definition() === defun_def && (node.thedef = lambda_def, lambda_def.references.push(node));
});
}
return (fixed instanceof AST_Lambda || fixed instanceof AST_Class) && fixed.parent_scope !== nearest_scope && (fixed = fixed.clone(!0, compressor.get_toplevel()), nearest_scope.add_child_scope(fixed)), fixed.optimize(compressor);
}
// multiple uses
if (fixed) {
let replace;
if (fixed instanceof AST_This) !(def.orig[0] instanceof AST_SymbolFunarg) && def.references.every((ref)=>def.scope === ref.scope) && (replace = fixed);
else {
var ev = fixed.evaluate(compressor);
ev !== fixed && (compressor.option("unsafe_regexp") || !(ev instanceof RegExp)) && (replace = make_node_from_constant(ev, fixed));
}
if (replace) {
const name_length = self1.size(compressor), replace_size = replace.size(compressor);
let overhead = 0;
if (compressor.option("unused") && !compressor.exposed(def) && (overhead = (name_length + 2 + replace_size) / (def.references.length - def.assignments)), replace_size <= name_length + overhead) return replace;
}
}
}
return self1;
}), def_optimize(AST_Undefined, function(self1, compressor) {
if (compressor.option("unsafe_undefined")) {
var undef = find_variable(compressor, "undefined");
if (undef) {
var ref = make_node(AST_SymbolRef, self1, {
name: "undefined",
scope: undef.scope,
thedef: undef
});
return set_flag(ref, 0b00001000), ref;
}
}
var lhs = is_lhs(compressor.self(), compressor.parent());
return lhs && is_atomic(lhs, self1) ? self1 : make_node(AST_UnaryPrefix, self1, {
operator: "void",
expression: make_node(AST_Number, self1, {
value: 0
})
});
}), def_optimize(AST_Infinity, function(self1, compressor) {
var lhs = is_lhs(compressor.self(), compressor.parent());
return lhs && is_atomic(lhs, self1) || compressor.option("keep_infinity") && !(lhs && !is_atomic(lhs, self1)) && !find_variable(compressor, "Infinity") ? self1 : make_node(AST_Binary, self1, {
operator: "/",
left: make_node(AST_Number, self1, {
value: 1
}),
right: make_node(AST_Number, self1, {
value: 0
})
});
}), def_optimize(AST_NaN, function(self1, compressor) {
var lhs = is_lhs(compressor.self(), compressor.parent());
return lhs && !is_atomic(lhs, self1) || find_variable(compressor, "NaN") ? make_node(AST_Binary, self1, {
operator: "/",
left: make_node(AST_Number, self1, {
value: 0
}),
right: make_node(AST_Number, self1, {
value: 0
})
}) : self1;
});
const ASSIGN_OPS = makePredicate("+ - / * % >> << >>> | ^ &"), ASSIGN_OPS_COMMUTATIVE = makePredicate("* | ^ &");
function safe_to_flatten(value, compressor) {
return value instanceof AST_SymbolRef && (value = value.fixed_value()), !!value && (!((value instanceof AST_Lambda || value instanceof AST_Class) && value instanceof AST_Lambda && value.contains_this()) || compressor.parent() instanceof AST_New);
}
function literals_in_boolean_context(self1, compressor) {
return compressor.in_boolean_context() ? best_of(compressor, self1, make_sequence(self1, [
self1,
make_node(AST_True, self1)
]).optimize(compressor)) : self1;
}
function inline_array_like_spread(elements) {
for(var i = 0; i < elements.length; i++){
var el = elements[i];
if (el instanceof AST_Expansion) {
var expr = el.expression;
expr instanceof AST_Array && !expr.elements.some((elm)=>elm instanceof AST_Hole) && (elements.splice(i, 1, ...expr.elements), // Step back one, as the element at i is now new.
i--);
// In array-like spread, spreading a non-iterable value is TypeError.
// We therefore can’t optimize anything else, unlike with object spread.
}
}
}
// ["p"]:1 ---> p:1
// [42]:1 ---> 42:1
function lift_key(self1, compressor) {
if (!compressor.option("computed_props") || !(self1.key instanceof AST_Constant)) return self1;
// allow certain acceptable props as not all AST_Constants are true constants
if (self1.key instanceof AST_String || self1.key instanceof AST_Number) {
if ("__proto__" === self1.key.value || "constructor" == self1.key.value && compressor.parent() instanceof AST_Class) return self1;
self1 instanceof AST_ObjectKeyVal ? (self1.quote = self1.key.quote, self1.key = self1.key.value) : self1 instanceof AST_ClassProperty ? (self1.quote = self1.key.quote, self1.key = make_node(AST_SymbolClassProperty, self1.key, {
name: self1.key.value
})) : (self1.quote = self1.key.quote, self1.key = make_node(AST_SymbolMethod, self1.key, {
name: self1.key.value
}));
}
return self1;
}
/***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
***********************************************************************/ // a small wrapper around fitzgen's source-map library
async function SourceMap(options) {
options = defaults(options, {
file: null,
root: null,
orig: null,
orig_line_diff: 0,
dest_line_diff: 0
});
var orig_map, generator = new MOZ_SourceMap__default.default.SourceMapGenerator({
file: options.file,
sourceRoot: options.root
});
return options.orig && (orig_map = await new MOZ_SourceMap__default.default.SourceMapConsumer(options.orig)).sources.forEach(function(source) {
var sourceContent = orig_map.sourceContentFor(source, !0);
sourceContent && generator.setSourceContent(source, sourceContent);
}), {
add: function(source, gen_line, gen_col, orig_line, orig_col, name) {
if (orig_map) {
var info = orig_map.originalPositionFor({
line: orig_line,
column: orig_col
});
if (null === info.source) return;
source = info.source, orig_line = info.line, orig_col = info.column, name = info.name || name;
}
generator.addMapping({
generated: {
line: gen_line + options.dest_line_diff,
column: gen_col
},
original: {
line: orig_line + options.orig_line_diff,
column: orig_col
},
source: source,
name: name
});
},
get: function() {
return generator;
},
toString: function() {
return generator.toString();
},
destroy: function() {
orig_map && orig_map.destroy && orig_map.destroy();
}
};
}
def_optimize(AST_Assign, function(self1, compressor) {
if (self1.logical) return self1.lift_sequences(compressor);
if (compressor.option("dead_code") && self1.left instanceof AST_SymbolRef && (def = self1.left.definition()).scope === compressor.find_parent(AST_Lambda)) {
var def, node, level = 0, parent = self1;
do if (node = parent, (parent = compressor.parent(level++)) instanceof AST_Exit) {
if (function(level, node) {
var parent, right = self1.right;
self1.right = make_node(AST_Null, right);
var may_throw = node.may_throw(compressor);
self1.right = right;
for(var scope = self1.left.definition().scope; (parent = compressor.parent(level++)) !== scope;)if (parent instanceof AST_Try && (parent.bfinally || may_throw && parent.bcatch)) return !0;
}(level, parent) || is_reachable(def.scope, [
def
])) break;
if ("=" == self1.operator) return self1.right;
return def.fixed = !1, make_node(AST_Binary, self1, {
operator: self1.operator.slice(0, -1),
left: self1.left,
right: self1.right
}).optimize(compressor);
}
while (parent instanceof AST_Binary && parent.right === node || parent instanceof AST_Sequence && parent.tail_node() === node)
}
return "=" == (self1 = self1.lift_sequences(compressor)).operator && self1.left instanceof AST_SymbolRef && self1.right instanceof AST_Binary && (self1.right.left instanceof AST_SymbolRef && self1.right.left.name == self1.left.name && ASSIGN_OPS.has(self1.right.operator) ? (// x = x - 2 ---> x -= 2
self1.operator = self1.right.operator + "=", self1.right = self1.right.right) : self1.right.right instanceof AST_SymbolRef && self1.right.right.name == self1.left.name && ASSIGN_OPS_COMMUTATIVE.has(self1.right.operator) && !self1.right.left.has_side_effects(compressor) && (// x = 2 & x ---> x &= 2
self1.operator = self1.right.operator + "=", self1.right = self1.right.left)), self1;
}), def_optimize(AST_DefaultAssign, function(self1, compressor) {
if (!compressor.option("evaluate")) return self1;
var evaluateRight = self1.right.evaluate(compressor);
return void 0 === evaluateRight ? self1 = self1.left : evaluateRight !== self1.right && (evaluateRight = make_node_from_constant(evaluateRight, self1.right), self1.right = best_of_expression(evaluateRight, self1.right)), self1;
}), def_optimize(AST_Conditional, function(self1, compressor) {
if (!compressor.option("conditionals")) return self1;
// This looks like lift_sequences(), should probably be under "sequences"
if (self1.condition instanceof AST_Sequence) {
var arg_index, expressions = self1.condition.expressions.slice();
return self1.condition = expressions.pop(), expressions.push(self1), make_sequence(self1, expressions);
}
var cond = self1.condition.evaluate(compressor);
if (cond !== self1.condition) return cond ? maintain_this_binding(compressor.parent(), compressor.self(), self1.consequent) : maintain_this_binding(compressor.parent(), compressor.self(), self1.alternative);
var negated = cond.negate(compressor, first_in_statement(compressor));
best_of(compressor, cond, negated) === negated && (self1 = make_node(AST_Conditional, self1, {
condition: negated,
consequent: self1.alternative,
alternative: self1.consequent
}));
var condition = self1.condition, consequent = self1.consequent, alternative = self1.alternative;
// x?x:y --> x||y
if (condition instanceof AST_SymbolRef && consequent instanceof AST_SymbolRef && condition.definition() === consequent.definition()) return make_node(AST_Binary, self1, {
operator: "||",
left: condition,
right: alternative
});
// if (foo) exp = something; else exp = something_else;
// |
// v
// exp = foo ? something : something_else;
if (consequent instanceof AST_Assign && alternative instanceof AST_Assign && consequent.operator === alternative.operator && consequent.logical === alternative.logical && consequent.left.equivalent_to(alternative.left) && (!self1.condition.has_side_effects(compressor) || "=" == consequent.operator && !consequent.left.has_side_effects(compressor))) return make_node(AST_Assign, self1, {
operator: consequent.operator,
left: consequent.left,
logical: consequent.logical,
right: make_node(AST_Conditional, self1, {
condition: self1.condition,
consequent: consequent.right,
alternative: alternative.right
})
});
if (consequent instanceof AST_Call && alternative.TYPE === consequent.TYPE && consequent.args.length > 0 && consequent.args.length == alternative.args.length && consequent.expression.equivalent_to(alternative.expression) && !self1.condition.has_side_effects(compressor) && !consequent.expression.has_side_effects(compressor) && "number" == typeof (arg_index = function() {
for(var a = consequent.args, b = alternative.args, i = 0, len = a.length; i < len; i++){
if (a[i] instanceof AST_Expansion) return;
if (!a[i].equivalent_to(b[i])) {
if (b[i] instanceof AST_Expansion) return;
for(var j = i + 1; j < len; j++)if (a[j] instanceof AST_Expansion || !a[j].equivalent_to(b[j])) return;
return i;
}
}
}())) {
var node = consequent.clone();
return node.args[arg_index] = make_node(AST_Conditional, self1, {
condition: self1.condition,
consequent: consequent.args[arg_index],
alternative: alternative.args[arg_index]
}), node;
}
// a ? b : c ? b : d --> (a || c) ? b : d
if (alternative instanceof AST_Conditional && consequent.equivalent_to(alternative.consequent)) return make_node(AST_Conditional, self1, {
condition: make_node(AST_Binary, self1, {
operator: "||",
left: condition,
right: alternative.condition
}),
consequent: consequent,
alternative: alternative.alternative
}).optimize(compressor);
// a == null ? b : a -> a ?? b
if (compressor.option("ecma") >= 2020 && function(check, check_subject, compressor) {
let nullish_side;
if (check_subject.may_throw(compressor)) return !1;
// foo == null
if (check instanceof AST_Binary && "==" === check.operator && ((nullish_side = is_nullish(check.left, compressor) && check.left) || (nullish_side = is_nullish(check.right, compressor) && check.right)) && (nullish_side === check.left ? check.right : check.left).equivalent_to(check_subject)) return !0;
// foo === null || foo === undefined
if (check instanceof AST_Binary && "||" === check.operator) {
let null_cmp, undefined_cmp;
const find_comparison = (cmp)=>{
let defined_side;
if (!(cmp instanceof AST_Binary && ("===" === cmp.operator || "==" === cmp.operator))) return !1;
let found = 0;
return cmp.left instanceof AST_Null && (found++, null_cmp = cmp, defined_side = cmp.right), cmp.right instanceof AST_Null && (found++, null_cmp = cmp, defined_side = cmp.left), is_undefined(cmp.left, compressor) && (found++, undefined_cmp = cmp, defined_side = cmp.right), is_undefined(cmp.right, compressor) && (found++, undefined_cmp = cmp, defined_side = cmp.left), !!(1 === found && defined_side.equivalent_to(check_subject));
};
if (!find_comparison(check.left) || !find_comparison(check.right)) return !1;
if (null_cmp && undefined_cmp && null_cmp !== undefined_cmp) return !0;
}
return !1;
}(condition, alternative, compressor)) return make_node(AST_Binary, self1, {
operator: "??",
left: alternative,
right: consequent
}).optimize(compressor);
// a ? b : (c, b) --> (a || c), b
if (alternative instanceof AST_Sequence && consequent.equivalent_to(alternative.expressions[alternative.expressions.length - 1])) return make_sequence(self1, [
make_node(AST_Binary, self1, {
operator: "||",
left: condition,
right: make_sequence(self1, alternative.expressions.slice(0, -1))
}),
consequent
]).optimize(compressor);
// a ? b : (c && b) --> (a || c) && b
if (alternative instanceof AST_Binary && "&&" == alternative.operator && consequent.equivalent_to(alternative.right)) return make_node(AST_Binary, self1, {
operator: "&&",
left: make_node(AST_Binary, self1, {
operator: "||",
left: condition,
right: alternative.left
}),
right: consequent
}).optimize(compressor);
// x?y?z:a:a --> x&&y?z:a
if (consequent instanceof AST_Conditional && consequent.alternative.equivalent_to(alternative)) return make_node(AST_Conditional, self1, {
condition: make_node(AST_Binary, self1, {
left: self1.condition,
operator: "&&",
right: consequent.condition
}),
consequent: consequent.consequent,
alternative: alternative
});
// x ? y : y --> x, y
if (consequent.equivalent_to(alternative)) return make_sequence(self1, [
self1.condition,
consequent
]).optimize(compressor);
// x ? y || z : z --> x && y || z
if (consequent instanceof AST_Binary && "||" == consequent.operator && consequent.right.equivalent_to(alternative)) return make_node(AST_Binary, self1, {
operator: "||",
left: make_node(AST_Binary, self1, {
operator: "&&",
left: self1.condition,
right: consequent.left
}),
right: alternative
}).optimize(compressor);
const in_bool = compressor.in_boolean_context();
if (is_true(self1.consequent)) return is_false(self1.alternative) ? booleanize(self1.condition) : make_node(AST_Binary, self1, {
operator: "||",
left: booleanize(self1.condition),
right: self1.alternative
});
if (is_false(self1.consequent)) return is_true(self1.alternative) ? booleanize(self1.condition.negate(compressor)) : make_node(AST_Binary, self1, {
operator: "&&",
left: booleanize(self1.condition.negate(compressor)),
right: self1.alternative
});
if (is_true(self1.alternative)) // c ? x : true ---> !c || x
return make_node(AST_Binary, self1, {
operator: "||",
left: booleanize(self1.condition.negate(compressor)),
right: self1.consequent
});
if (is_false(self1.alternative)) // c ? x : false ---> !!c && x
return make_node(AST_Binary, self1, {
operator: "&&",
left: booleanize(self1.condition),
right: self1.consequent
});
return self1;
function booleanize(node) {
return node.is_boolean() ? node : make_node(AST_UnaryPrefix, node, {
operator: "!",
expression: node.negate(compressor)
});
}
// AST_True or !0
function is_true(node) {
return node instanceof AST_True || in_bool && node instanceof AST_Constant && node.getValue() || node instanceof AST_UnaryPrefix && "!" == node.operator && node.expression instanceof AST_Constant && !node.expression.getValue();
}
// AST_False or !1
function is_false(node) {
return node instanceof AST_False || in_bool && node instanceof AST_Constant && !node.getValue() || node instanceof AST_UnaryPrefix && "!" == node.operator && node.expression instanceof AST_Constant && node.expression.getValue();
}
}), def_optimize(AST_Boolean, function(self1, compressor) {
if (compressor.in_boolean_context()) return make_node(AST_Number, self1, {
value: +self1.value
});
var p = compressor.parent();
return compressor.option("booleans_as_integers") ? (p instanceof AST_Binary && ("===" == p.operator || "!==" == p.operator) && (p.operator = p.operator.replace(/=$/, "")), make_node(AST_Number, self1, {
value: +self1.value
})) : compressor.option("booleans") ? p instanceof AST_Binary && ("==" == p.operator || "!=" == p.operator) ? make_node(AST_Number, self1, {
value: +self1.value
}) : make_node(AST_UnaryPrefix, self1, {
operator: "!",
expression: make_node(AST_Number, self1, {
value: 1 - self1.value
})
}) : self1;
}), AST_PropAccess.DEFMETHOD("flatten_object", function(key, compressor) {
if (compressor.option("properties") && "__proto__" !== key) {
var arrows = compressor.option("unsafe_arrows") && compressor.option("ecma") >= 2015, expr = this.expression;
if (expr instanceof AST_Object) for(var props = expr.properties, i = props.length; --i >= 0;){
var prop = props[i];
if ("" + (prop instanceof AST_ConciseMethod ? prop.key.name : prop.key) == key) {
if (!props.every((p)=>(p instanceof AST_ObjectKeyVal || arrows && p instanceof AST_ConciseMethod && !p.is_generator) && !p.computed_key()) || !safe_to_flatten(prop.value, compressor)) return;
return make_node(AST_Sub, this, {
expression: make_node(AST_Array, expr, {
elements: props.map(function(prop) {
var v = prop.value;
v instanceof AST_Accessor && (v = make_node(AST_Function, v, v));
var k = prop.key;
return k instanceof AST_Node && !(k instanceof AST_SymbolMethod) ? make_sequence(prop, [
k,
v
]) : v;
})
}),
property: make_node(AST_Number, this, {
value: i
})
});
}
}
}
}), def_optimize(AST_Sub, function(self1, compressor) {
var fn, expr = self1.expression, prop = self1.property;
if (compressor.option("properties")) {
var key = prop.evaluate(compressor);
if (key !== prop) {
if ("string" == typeof key) {
if ("undefined" == key) key = void 0;
else {
var value = parseFloat(key);
value.toString() == key && (key = value);
}
}
prop = self1.property = best_of_expression(prop, make_node_from_constant(key, prop).transform(compressor));
var property = "" + key;
if (is_basic_identifier_string(property) && property.length <= prop.size() + 1) return make_node(AST_Dot, self1, {
expression: expr,
optional: self1.optional,
property: property,
quote: prop.quote
}).optimize(compressor);
}
}
OPT_ARGUMENTS: if (compressor.option("arguments") && expr instanceof AST_SymbolRef && "arguments" == expr.name && 1 == expr.definition().orig.length && (fn = expr.scope) instanceof AST_Lambda && fn.uses_arguments && !(fn instanceof AST_Arrow) && prop instanceof AST_Number) {
for(var index = prop.getValue(), params = new Set(), argnames = fn.argnames, n = 0; n < argnames.length; n++){
if (!(argnames[n] instanceof AST_SymbolFunarg)) break OPT_ARGUMENTS; // destructuring parameter - bail
var param = argnames[n].name;
if (params.has(param)) break OPT_ARGUMENTS; // duplicate parameter - bail
params.add(param);
}
var argname = fn.argnames[index];
if (argname && compressor.has_directive("use strict")) {
var def = argname.definition();
(!compressor.option("reduce_vars") || def.assignments || def.orig.length > 1) && (argname = null);
} else if (!argname && !compressor.option("keep_fargs") && index < fn.argnames.length + 5) for(; index >= fn.argnames.length;)argname = fn.create_symbol(AST_SymbolFunarg, {
source: fn,
scope: fn,
tentative_name: "argument_" + fn.argnames.length
}), fn.argnames.push(argname);
if (argname) {
var sym = make_node(AST_SymbolRef, self1, argname);
return sym.reference({}), clear_flag(argname, 0b00000001), sym;
}
}
if (is_lhs(self1, compressor.parent())) return self1;
if (key !== prop) {
var sub = self1.flatten_object(property, compressor);
sub && (expr = self1.expression = sub.expression, prop = self1.property = sub.property);
}
if (compressor.option("properties") && compressor.option("side_effects") && prop instanceof AST_Number && expr instanceof AST_Array) {
var index = prop.getValue(), elements = expr.elements, retValue = elements[index];
FLATTEN: if (safe_to_flatten(retValue, compressor)) {
for(var flatten = !0, values = [], i = elements.length; --i > index;){
var value = elements[i].drop_side_effect_free(compressor);
value && (values.unshift(value), flatten && value.has_side_effects(compressor) && (flatten = !1));
}
if (retValue instanceof AST_Expansion) break FLATTEN;
for(retValue = retValue instanceof AST_Hole ? make_node(AST_Undefined, retValue) : retValue, flatten || values.unshift(retValue); --i >= 0;){
var value = elements[i];
if (value instanceof AST_Expansion) break FLATTEN;
(value = value.drop_side_effect_free(compressor)) ? values.unshift(value) : index--;
}
if (flatten) return values.push(retValue), make_sequence(self1, values).optimize(compressor);
return make_node(AST_Sub, self1, {
expression: make_node(AST_Array, expr, {
elements: values
}),
property: make_node(AST_Number, prop, {
value: index
})
});
}
}
var ev = self1.evaluate(compressor);
return ev !== self1 ? (ev = make_node_from_constant(ev, self1).optimize(compressor), best_of(compressor, ev, self1)) : self1;
}), def_optimize(AST_Chain, function(self1, compressor) {
if (is_nullish(self1.expression, compressor)) {
let parent = compressor.parent();
return(// It's valid to delete a nullish optional chain, but if we optimized
// this to `delete undefined` then it would appear to be a syntax error
// when we try to optimize the delete. Thankfully, `delete 0` is fine.
parent instanceof AST_UnaryPrefix && "delete" === parent.operator ? make_node_from_constant(0, self1) : make_node(AST_Undefined, self1));
}
return self1;
}), AST_Lambda.DEFMETHOD("contains_this", function() {
return walk(this, (node)=>node instanceof AST_This ? walk_abort : node !== this && node instanceof AST_Scope && !(node instanceof AST_Arrow) || void 0);
}), def_optimize(AST_Dot, function(self1, compressor) {
const parent = compressor.parent();
if (is_lhs(self1, parent)) return self1;
if (compressor.option("unsafe_proto") && self1.expression instanceof AST_Dot && "prototype" == self1.expression.property) {
var exp = self1.expression.expression;
if (is_undeclared_ref(exp)) switch(exp.name){
case "Array":
self1.expression = make_node(AST_Array, self1.expression, {
elements: []
});
break;
case "Function":
self1.expression = make_node(AST_Function, self1.expression, {
argnames: [],
body: []
});
break;
case "Number":
self1.expression = make_node(AST_Number, self1.expression, {
value: 0
});
break;
case "Object":
self1.expression = make_node(AST_Object, self1.expression, {
properties: []
});
break;
case "RegExp":
self1.expression = make_node(AST_RegExp, self1.expression, {
value: {
source: "t",
flags: ""
}
});
break;
case "String":
self1.expression = make_node(AST_String, self1.expression, {
value: ""
});
}
}
if (!(parent instanceof AST_Call) || !has_annotation(parent, _NOINLINE)) {
const sub = self1.flatten_object(self1.property, compressor);
if (sub) return sub.optimize(compressor);
}
let ev = self1.evaluate(compressor);
return ev !== self1 ? (ev = make_node_from_constant(ev, self1).optimize(compressor), best_of(compressor, ev, self1)) : self1;
}), def_optimize(AST_Array, function(self1, compressor) {
var optimized = literals_in_boolean_context(self1, compressor);
return optimized !== self1 ? optimized : (inline_array_like_spread(self1.elements), self1);
}), def_optimize(AST_Object, function(self1, compressor) {
var optimized = literals_in_boolean_context(self1, compressor);
return optimized !== self1 ? optimized : (function(props, compressor) {
for(var i = 0; i < props.length; i++){
var prop = props[i];
if (prop instanceof AST_Expansion) {
const expr = prop.expression;
expr instanceof AST_Object && expr.properties.every((prop)=>prop instanceof AST_ObjectKeyVal) ? (props.splice(i, 1, ...expr.properties), // Step back one, as the property at i is now new.
i--) : expr instanceof AST_Constant && !(expr instanceof AST_String) ? (// Unlike array-like spread, in object spread, spreading a
// non-iterable value silently does nothing; it is thus safe
// to remove. AST_String is the only iterable AST_Constant.
props.splice(i, 1), i--) : is_nullish(expr, compressor) && (// Likewise, null and undefined can be silently removed.
props.splice(i, 1), i--);
}
}
}(self1.properties, compressor), self1);
}), def_optimize(AST_RegExp, literals_in_boolean_context), def_optimize(AST_Return, function(self1, compressor) {
return self1.value && is_undefined(self1.value, compressor) && (self1.value = null), self1;
}), def_optimize(AST_Arrow, opt_AST_Lambda), def_optimize(AST_Function, function(self1, compressor) {
return (self1 = opt_AST_Lambda(self1, compressor), !(compressor.option("unsafe_arrows") && compressor.option("ecma") >= 2015) || self1.name || self1.is_generator || self1.uses_arguments || self1.pinned() || walk(self1, (node)=>{
if (node instanceof AST_This) return walk_abort;
})) ? self1 : make_node(AST_Arrow, self1, self1).optimize(compressor);
}), def_optimize(AST_Class, function(self1) {
// HACK to avoid compress failure.
// AST_Class is not really an AST_Scope/AST_Block as it lacks a body.
return self1;
}), def_optimize(AST_Yield, function(self1, compressor) {
return self1.expression && !self1.is_star && is_undefined(self1.expression, compressor) && (self1.expression = null), self1;
}), def_optimize(AST_TemplateString, function(self1, compressor) {
if (!compressor.option("evaluate") || compressor.parent() instanceof AST_PrefixedTemplateString) return self1;
for(var segments = [], i = 0; i < self1.segments.length; i++){
var segment = self1.segments[i];
if (segment instanceof AST_Node) {
var result = segment.evaluate(compressor);
// Evaluate to constant value
// Constant value shorter than ${segment}
if (result !== segment && (result + "").length <= segment.size() + 3) {
// There should always be a previous and next segment if segment is a node
segments[segments.length - 1].value = segments[segments.length - 1].value + result + self1.segments[++i].value;
continue;
}
// `before ${`innerBefore ${any} innerAfter`} after` => `before innerBefore ${any} innerAfter after`
// TODO:
// `before ${'test' + foo} after` => `before innerBefore ${any} innerAfter after`
// `before ${foo + 'test} after` => `before innerBefore ${any} innerAfter after`
if (segment instanceof AST_TemplateString) {
var inners = segment.segments;
segments[segments.length - 1].value += inners[0].value;
for(var j = 1; j < inners.length; j++)segment = inners[j], segments.push(segment);
continue;
}
}
segments.push(segment);
}
// `foo` => "foo"
if (self1.segments = segments, 1 == segments.length) return make_node(AST_String, self1, segments[0]);
if (3 === segments.length && segments[1] instanceof AST_Node && (segments[1].is_string(compressor) || segments[1].is_number(compressor) || is_nullish(segments[1], compressor) || compressor.option("unsafe"))) {
// `foo${bar}` => "foo" + bar
if ("" === segments[2].value) return make_node(AST_Binary, self1, {
operator: "+",
left: make_node(AST_String, self1, {
value: segments[0].value
}),
right: segments[1]
});
// `${bar}baz` => bar + "baz"
if ("" === segments[0].value) return make_node(AST_Binary, self1, {
operator: "+",
left: segments[1],
right: make_node(AST_String, self1, {
value: segments[2].value
})
});
}
return self1;
}), def_optimize(AST_PrefixedTemplateString, function(self1) {
return self1;
}), def_optimize(AST_ObjectProperty, lift_key), def_optimize(AST_ConciseMethod, function(self1, compressor) {
// p(){return x;} ---> p:()=>x
if (lift_key(self1, compressor), compressor.option("arrows") && compressor.parent() instanceof AST_Object && !self1.is_generator && !self1.value.uses_arguments && !self1.value.pinned() && 1 == self1.value.body.length && self1.value.body[0] instanceof AST_Return && self1.value.body[0].value && !self1.value.contains_this()) {
var arrow = make_node(AST_Arrow, self1.value, self1.value);
return arrow.async = self1.async, arrow.is_generator = self1.is_generator, make_node(AST_ObjectKeyVal, self1, {
key: self1.key instanceof AST_SymbolMethod ? self1.key.name : self1.key,
value: arrow,
quote: self1.quote
});
}
return self1;
}), def_optimize(AST_ObjectKeyVal, function(self1, compressor) {
lift_key(self1, compressor);
// p:function(){} ---> p(){}
// p:function*(){} ---> *p(){}
// p:async function(){} ---> async p(){}
// p:()=>{} ---> p(){}
// p:async()=>{} ---> async p(){}
var unsafe_methods = compressor.option("unsafe_methods");
if (unsafe_methods && compressor.option("ecma") >= 2015 && (!(unsafe_methods instanceof RegExp) || unsafe_methods.test(self1.key + ""))) {
var key = self1.key, value = self1.value;
if ((value instanceof AST_Arrow && Array.isArray(value.body) && !value.contains_this() || value instanceof AST_Function) && !value.name) return make_node(AST_ConciseMethod, self1, {
async: value.async,
is_generator: value.is_generator,
key: key instanceof AST_Node ? key : make_node(AST_SymbolMethod, self1, {
name: key
}),
value: make_node(AST_Accessor, value, value),
quote: self1.quote
});
}
return self1;
}), def_optimize(AST_Destructuring, function(self1, compressor) {
if (!0 == compressor.option("pure_getters") && compressor.option("unused") && !self1.is_array && Array.isArray(self1.names) && !function(compressor) {
for(var ancestors = [
/^VarDef$/,
/^(Const|Let|Var)$/,
/^Export$/
], a = 0, p = 0, len = ancestors.length; a < len; p++){
var parent = compressor.parent(p);
if (!parent) return !1;
if (0 !== a || "Destructuring" != parent.TYPE) {
if (!ancestors[a].test(parent.TYPE)) return !1;
a++;
}
}
return !0;
}(compressor) && !(self1.names[self1.names.length - 1] instanceof AST_Expansion)) {
for(var keep = [], i = 0; i < self1.names.length; i++){
var def, elem = self1.names[i];
elem instanceof AST_ObjectKeyVal && "string" == typeof elem.key && elem.value instanceof AST_SymbolDeclaration && !((def = elem.value.definition()).references.length || def.global && (!compressor.toplevel.vars || compressor.top_retain && compressor.top_retain(def))) || keep.push(elem);
}
keep.length != self1.names.length && (self1.names = keep);
}
return self1;
});
var domprops = [
"$&",
"$'",
"$*",
"$+",
"$1",
"$2",
"$3",
"$4",
"$5",
"$6",
"$7",
"$8",
"$9",
"$_",
"$`",
"$input",
"-moz-animation",
"-moz-animation-delay",
"-moz-animation-direction",
"-moz-animation-duration",
"-moz-animation-fill-mode",
"-moz-animation-iteration-count",
"-moz-animation-name",
"-moz-animation-play-state",
"-moz-animation-timing-function",
"-moz-appearance",
"-moz-backface-visibility",
"-moz-border-end",
"-moz-border-end-color",
"-moz-border-end-style",
"-moz-border-end-width",
"-moz-border-image",
"-moz-border-start",
"-moz-border-start-color",
"-moz-border-start-style",
"-moz-border-start-width",
"-moz-box-align",
"-moz-box-direction",
"-moz-box-flex",
"-moz-box-ordinal-group",
"-moz-box-orient",
"-moz-box-pack",
"-moz-box-sizing",
"-moz-float-edge",
"-moz-font-feature-settings",
"-moz-font-language-override",
"-moz-force-broken-image-icon",
"-moz-hyphens",
"-moz-image-region",
"-moz-margin-end",
"-moz-margin-start",
"-moz-orient",
"-moz-osx-font-smoothing",
"-moz-outline-radius",
"-moz-outline-radius-bottomleft",
"-moz-outline-radius-bottomright",
"-moz-outline-radius-topleft",
"-moz-outline-radius-topright",
"-moz-padding-end",
"-moz-padding-start",
"-moz-perspective",
"-moz-perspective-origin",
"-moz-tab-size",
"-moz-text-size-adjust",
"-moz-transform",
"-moz-transform-origin",
"-moz-transform-style",
"-moz-transition",
"-moz-transition-delay",
"-moz-transition-duration",
"-moz-transition-property",
"-moz-transition-timing-function",
"-moz-user-focus",
"-moz-user-input",
"-moz-user-modify",
"-moz-user-select",
"-moz-window-dragging",
"-webkit-align-content",
"-webkit-align-items",
"-webkit-align-self",
"-webkit-animation",
"-webkit-animation-delay",
"-webkit-animation-direction",
"-webkit-animation-duration",
"-webkit-animation-fill-mode",
"-webkit-animation-iteration-count",
"-webkit-animation-name",
"-webkit-animation-play-state",
"-webkit-animation-timing-function",
"-webkit-appearance",
"-webkit-backface-visibility",
"-webkit-background-clip",
"-webkit-background-origin",
"-webkit-background-size",
"-webkit-border-bottom-left-radius",
"-webkit-border-bottom-right-radius",
"-webkit-border-image",
"-webkit-border-radius",
"-webkit-border-top-left-radius",
"-webkit-border-top-right-radius",
"-webkit-box-align",
"-webkit-box-direction",
"-webkit-box-flex",
"-webkit-box-ordinal-group",
"-webkit-box-orient",
"-webkit-box-pack",
"-webkit-box-shadow",
"-webkit-box-sizing",
"-webkit-filter",
"-webkit-flex",
"-webkit-flex-basis",
"-webkit-flex-direction",
"-webkit-flex-flow",
"-webkit-flex-grow",
"-webkit-flex-shrink",
"-webkit-flex-wrap",
"-webkit-justify-content",
"-webkit-line-clamp",
"-webkit-mask",
"-webkit-mask-clip",
"-webkit-mask-composite",
"-webkit-mask-image",
"-webkit-mask-origin",
"-webkit-mask-position",
"-webkit-mask-position-x",
"-webkit-mask-position-y",
"-webkit-mask-repeat",
"-webkit-mask-size",
"-webkit-order",
"-webkit-perspective",
"-webkit-perspective-origin",
"-webkit-text-fill-color",
"-webkit-text-size-adjust",
"-webkit-text-stroke",
"-webkit-text-stroke-color",
"-webkit-text-stroke-width",
"-webkit-transform",
"-webkit-transform-origin",
"-webkit-transform-style",
"-webkit-transition",
"-webkit-transition-delay",
"-webkit-transition-duration",
"-webkit-transition-property",
"-webkit-transition-timing-function",
"-webkit-user-select",
"0",
"1",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"2",
"20",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"@@iterator",
"ABORT_ERR",
"ACTIVE",
"ACTIVE_ATTRIBUTES",
"ACTIVE_TEXTURE",
"ACTIVE_UNIFORMS",
"ACTIVE_UNIFORM_BLOCKS",
"ADDITION",
"ALIASED_LINE_WIDTH_RANGE",
"ALIASED_POINT_SIZE_RANGE",
"ALLOW_KEYBOARD_INPUT",
"ALLPASS",
"ALPHA",
"ALPHA_BITS",
"ALREADY_SIGNALED",
"ALT_MASK",
"ALWAYS",
"ANY_SAMPLES_PASSED",
"ANY_SAMPLES_PASSED_CONSERVATIVE",
"ANY_TYPE",
"ANY_UNORDERED_NODE_TYPE",
"ARRAY_BUFFER",
"ARRAY_BUFFER_BINDING",
"ATTACHED_SHADERS",
"ATTRIBUTE_NODE",
"AT_TARGET",
"AbortController",
"AbortSignal",
"AbsoluteOrientationSensor",
"AbstractRange",
"Accelerometer",
"AddSearchProvider",
"AggregateError",
"AnalyserNode",
"Animation",
"AnimationEffect",
"AnimationEvent",
"AnimationPlaybackEvent",
"AnimationTimeline",
"AnonXMLHttpRequest",
"Any",
"ApplicationCache",
"ApplicationCacheErrorEvent",
"Array",
"ArrayBuffer",
"ArrayType",
"Atomics",
"Attr",
"Audio",
"AudioBuffer",
"AudioBufferSourceNode",
"AudioContext",
"AudioDestinationNode",
"AudioListener",
"AudioNode",
"AudioParam",
"AudioParamMap",
"AudioProcessingEvent",
"AudioScheduledSourceNode",
"AudioStreamTrack",
"AudioWorklet",
"AudioWorkletNode",
"AuthenticatorAssertionResponse",
"AuthenticatorAttestationResponse",
"AuthenticatorResponse",
"AutocompleteErrorEvent",
"BACK",
"BAD_BOUNDARYPOINTS_ERR",
"BAD_REQUEST",
"BANDPASS",
"BLEND",
"BLEND_COLOR",
"BLEND_DST_ALPHA",
"BLEND_DST_RGB",
"BLEND_EQUATION",
"BLEND_EQUATION_ALPHA",
"BLEND_EQUATION_RGB",
"BLEND_SRC_ALPHA",
"BLEND_SRC_RGB",
"BLUE_BITS",
"BLUR",
"BOOL",
"BOOLEAN_TYPE",
"BOOL_VEC2",
"BOOL_VEC3",
"BOOL_VEC4",
"BOTH",
"BROWSER_DEFAULT_WEBGL",
"BUBBLING_PHASE",
"BUFFER_SIZE",
"BUFFER_USAGE",
"BYTE",
"BYTES_PER_ELEMENT",
"BackgroundFetchManager",
"BackgroundFetchRecord",
"BackgroundFetchRegistration",
"BarProp",
"BarcodeDetector",
"BaseAudioContext",
"BaseHref",
"BatteryManager",
"BeforeInstallPromptEvent",
"BeforeLoadEvent",
"BeforeUnloadEvent",
"BigInt",
"BigInt64Array",
"BigUint64Array",
"BiquadFilterNode",
"Blob",
"BlobEvent",
"Bluetooth",
"BluetoothCharacteristicProperties",
"BluetoothDevice",
"BluetoothRemoteGATTCharacteristic",
"BluetoothRemoteGATTDescriptor",
"BluetoothRemoteGATTServer",
"BluetoothRemoteGATTService",
"BluetoothUUID",
"Boolean",
"BroadcastChannel",
"ByteLengthQueuingStrategy",
"CAPTURING_PHASE",
"CCW",
"CDATASection",
"CDATA_SECTION_NODE",
"CHANGE",
"CHARSET_RULE",
"CHECKING",
"CLAMP_TO_EDGE",
"CLICK",
"CLOSED",
"CLOSING",
"COLOR",
"COLOR_ATTACHMENT0",
"COLOR_ATTACHMENT1",
"COLOR_ATTACHMENT10",
"COLOR_ATTACHMENT11",
"COLOR_ATTACHMENT12",
"COLOR_ATTACHMENT13",
"COLOR_ATTACHMENT14",
"COLOR_ATTACHMENT15",
"COLOR_ATTACHMENT2",
"COLOR_ATTACHMENT3",
"COLOR_ATTACHMENT4",
"COLOR_ATTACHMENT5",
"COLOR_ATTACHMENT6",
"COLOR_ATTACHMENT7",
"COLOR_ATTACHMENT8",
"COLOR_ATTACHMENT9",
"COLOR_BUFFER_BIT",
"COLOR_CLEAR_VALUE",
"COLOR_WRITEMASK",
"COMMENT_NODE",
"COMPARE_REF_TO_TEXTURE",
"COMPILE_STATUS",
"COMPRESSED_RGBA_S3TC_DXT1_EXT",
"COMPRESSED_RGBA_S3TC_DXT3_EXT",
"COMPRESSED_RGBA_S3TC_DXT5_EXT",
"COMPRESSED_RGB_S3TC_DXT1_EXT",
"COMPRESSED_TEXTURE_FORMATS",
"CONDITION_SATISFIED",
"CONFIGURATION_UNSUPPORTED",
"CONNECTING",
"CONSTANT_ALPHA",
"CONSTANT_COLOR",
"CONSTRAINT_ERR",
"CONTEXT_LOST_WEBGL",
"CONTROL_MASK",
"COPY_READ_BUFFER",
"COPY_READ_BUFFER_BINDING",
"COPY_WRITE_BUFFER",
"COPY_WRITE_BUFFER_BINDING",
"COUNTER_STYLE_RULE",
"CSS",
"CSS2Properties",
"CSSAnimation",
"CSSCharsetRule",
"CSSConditionRule",
"CSSCounterStyleRule",
"CSSFontFaceRule",
"CSSFontFeatureValuesRule",
"CSSGroupingRule",
"CSSImageValue",
"CSSImportRule",
"CSSKeyframeRule",
"CSSKeyframesRule",
"CSSKeywordValue",
"CSSMathInvert",
"CSSMathMax",
"CSSMathMin",
"CSSMathNegate",
"CSSMathProduct",
"CSSMathSum",
"CSSMathValue",
"CSSMatrixComponent",
"CSSMediaRule",
"CSSMozDocumentRule",
"CSSNameSpaceRule",
"CSSNamespaceRule",
"CSSNumericArray",
"CSSNumericValue",
"CSSPageRule",
"CSSPerspective",
"CSSPositionValue",
"CSSPrimitiveValue",
"CSSRotate",
"CSSRule",
"CSSRuleList",
"CSSScale",
"CSSSkew",
"CSSSkewX",
"CSSSkewY",
"CSSStyleDeclaration",
"CSSStyleRule",
"CSSStyleSheet",
"CSSStyleValue",
"CSSSupportsRule",
"CSSTransformComponent",
"CSSTransformValue",
"CSSTransition",
"CSSTranslate",
"CSSUnitValue",
"CSSUnknownRule",
"CSSUnparsedValue",
"CSSValue",
"CSSValueList",
"CSSVariableReferenceValue",
"CSSVariablesDeclaration",
"CSSVariablesRule",
"CSSViewportRule",
"CSS_ATTR",
"CSS_CM",
"CSS_COUNTER",
"CSS_CUSTOM",
"CSS_DEG",
"CSS_DIMENSION",
"CSS_EMS",
"CSS_EXS",
"CSS_FILTER_BLUR",
"CSS_FILTER_BRIGHTNESS",
"CSS_FILTER_CONTRAST",
"CSS_FILTER_CUSTOM",
"CSS_FILTER_DROP_SHADOW",
"CSS_FILTER_GRAYSCALE",
"CSS_FILTER_HUE_ROTATE",
"CSS_FILTER_INVERT",
"CSS_FILTER_OPACITY",
"CSS_FILTER_REFERENCE",
"CSS_FILTER_SATURATE",
"CSS_FILTER_SEPIA",
"CSS_GRAD",
"CSS_HZ",
"CSS_IDENT",
"CSS_IN",
"CSS_INHERIT",
"CSS_KHZ",
"CSS_MATRIX",
"CSS_MATRIX3D",
"CSS_MM",
"CSS_MS",
"CSS_NUMBER",
"CSS_PC",
"CSS_PERCENTAGE",
"CSS_PERSPECTIVE",
"CSS_PRIMITIVE_VALUE",
"CSS_PT",
"CSS_PX",
"CSS_RAD",
"CSS_RECT",
"CSS_RGBCOLOR",
"CSS_ROTATE",
"CSS_ROTATE3D",
"CSS_ROTATEX",
"CSS_ROTATEY",
"CSS_ROTATEZ",
"CSS_S",
"CSS_SCALE",
"CSS_SCALE3D",
"CSS_SCALEX",
"CSS_SCALEY",
"CSS_SCALEZ",
"CSS_SKEW",
"CSS_SKEWX",
"CSS_SKEWY",
"CSS_STRING",
"CSS_TRANSLATE",
"CSS_TRANSLATE3D",
"CSS_TRANSLATEX",
"CSS_TRANSLATEY",
"CSS_TRANSLATEZ",
"CSS_UNKNOWN",
"CSS_URI",
"CSS_VALUE_LIST",
"CSS_VH",
"CSS_VMAX",
"CSS_VMIN",
"CSS_VW",
"CULL_FACE",
"CULL_FACE_MODE",
"CURRENT_PROGRAM",
"CURRENT_QUERY",
"CURRENT_VERTEX_ATTRIB",
"CUSTOM",
"CW",
"Cache",
"CacheStorage",
"CanvasCaptureMediaStream",
"CanvasCaptureMediaStreamTrack",
"CanvasGradient",
"CanvasPattern",
"CanvasRenderingContext2D",
"CaretPosition",
"ChannelMergerNode",
"ChannelSplitterNode",
"CharacterData",
"ClientRect",
"ClientRectList",
"Clipboard",
"ClipboardEvent",
"ClipboardItem",
"CloseEvent",
"Collator",
"CommandEvent",
"Comment",
"CompileError",
"CompositionEvent",
"CompressionStream",
"Console",
"ConstantSourceNode",
"Controllers",
"ConvolverNode",
"CountQueuingStrategy",
"Counter",
"Credential",
"CredentialsContainer",
"Crypto",
"CryptoKey",
"CustomElementRegistry",
"CustomEvent",
"DATABASE_ERR",
"DATA_CLONE_ERR",
"DATA_ERR",
"DBLCLICK",
"DECR",
"DECR_WRAP",
"DELETE_STATUS",
"DEPTH",
"DEPTH24_STENCIL8",
"DEPTH32F_STENCIL8",
"DEPTH_ATTACHMENT",
"DEPTH_BITS",
"DEPTH_BUFFER_BIT",
"DEPTH_CLEAR_VALUE",
"DEPTH_COMPONENT",
"DEPTH_COMPONENT16",
"DEPTH_COMPONENT24",
"DEPTH_COMPONENT32F",
"DEPTH_FUNC",
"DEPTH_RANGE",
"DEPTH_STENCIL",
"DEPTH_STENCIL_ATTACHMENT",
"DEPTH_TEST",
"DEPTH_WRITEMASK",
"DEVICE_INELIGIBLE",
"DIRECTION_DOWN",
"DIRECTION_LEFT",
"DIRECTION_RIGHT",
"DIRECTION_UP",
"DISABLED",
"DISPATCH_REQUEST_ERR",
"DITHER",
"DOCUMENT_FRAGMENT_NODE",
"DOCUMENT_NODE",
"DOCUMENT_POSITION_CONTAINED_BY",
"DOCUMENT_POSITION_CONTAINS",
"DOCUMENT_POSITION_DISCONNECTED",
"DOCUMENT_POSITION_FOLLOWING",
"DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC",
"DOCUMENT_POSITION_PRECEDING",
"DOCUMENT_TYPE_NODE",
"DOMCursor",
"DOMError",
"DOMException",
"DOMImplementation",
"DOMImplementationLS",
"DOMMatrix",
"DOMMatrixReadOnly",
"DOMParser",
"DOMPoint",
"DOMPointReadOnly",
"DOMQuad",
"DOMRect",
"DOMRectList",
"DOMRectReadOnly",
"DOMRequest",
"DOMSTRING_SIZE_ERR",
"DOMSettableTokenList",
"DOMStringList",
"DOMStringMap",
"DOMTokenList",
"DOMTransactionEvent",
"DOM_DELTA_LINE",
"DOM_DELTA_PAGE",
"DOM_DELTA_PIXEL",
"DOM_INPUT_METHOD_DROP",
"DOM_INPUT_METHOD_HANDWRITING",
"DOM_INPUT_METHOD_IME",
"DOM_INPUT_METHOD_KEYBOARD",
"DOM_INPUT_METHOD_MULTIMODAL",
"DOM_INPUT_METHOD_OPTION",
"DOM_INPUT_METHOD_PASTE",
"DOM_INPUT_METHOD_SCRIPT",
"DOM_INPUT_METHOD_UNKNOWN",
"DOM_INPUT_METHOD_VOICE",
"DOM_KEY_LOCATION_JOYSTICK",
"DOM_KEY_LOCATION_LEFT",
"DOM_KEY_LOCATION_MOBILE",
"DOM_KEY_LOCATION_NUMPAD",
"DOM_KEY_LOCATION_RIGHT",
"DOM_KEY_LOCATION_STANDARD",
"DOM_VK_0",
"DOM_VK_1",
"DOM_VK_2",
"DOM_VK_3",
"DOM_VK_4",
"DOM_VK_5",
"DOM_VK_6",
"DOM_VK_7",
"DOM_VK_8",
"DOM_VK_9",
"DOM_VK_A",
"DOM_VK_ACCEPT",
"DOM_VK_ADD",
"DOM_VK_ALT",
"DOM_VK_ALTGR",
"DOM_VK_AMPERSAND",
"DOM_VK_ASTERISK",
"DOM_VK_AT",
"DOM_VK_ATTN",
"DOM_VK_B",
"DOM_VK_BACKSPACE",
"DOM_VK_BACK_QUOTE",
"DOM_VK_BACK_SLASH",
"DOM_VK_BACK_SPACE",
"DOM_VK_C",
"DOM_VK_CANCEL",
"DOM_VK_CAPS_LOCK",
"DOM_VK_CIRCUMFLEX",
"DOM_VK_CLEAR",
"DOM_VK_CLOSE_BRACKET",
"DOM_VK_CLOSE_CURLY_BRACKET",
"DOM_VK_CLOSE_PAREN",
"DOM_VK_COLON",
"DOM_VK_COMMA",
"DOM_VK_CONTEXT_MENU",
"DOM_VK_CONTROL",
"DOM_VK_CONVERT",
"DOM_VK_CRSEL",
"DOM_VK_CTRL",
"DOM_VK_D",
"DOM_VK_DECIMAL",
"DOM_VK_DELETE",
"DOM_VK_DIVIDE",
"DOM_VK_DOLLAR",
"DOM_VK_DOUBLE_QUOTE",
"DOM_VK_DOWN",
"DOM_VK_E",
"DOM_VK_EISU",
"DOM_VK_END",
"DOM_VK_ENTER",
"DOM_VK_EQUALS",
"DOM_VK_EREOF",
"DOM_VK_ESCAPE",
"DOM_VK_EXCLAMATION",
"DOM_VK_EXECUTE",
"DOM_VK_EXSEL",
"DOM_VK_F",
"DOM_VK_F1",
"DOM_VK_F10",
"DOM_VK_F11",
"DOM_VK_F12",
"DOM_VK_F13",
"DOM_VK_F14",
"DOM_VK_F15",
"DOM_VK_F16",
"DOM_VK_F17",
"DOM_VK_F18",
"DOM_VK_F19",
"DOM_VK_F2",
"DOM_VK_F20",
"DOM_VK_F21",
"DOM_VK_F22",
"DOM_VK_F23",
"DOM_VK_F24",
"DOM_VK_F25",
"DOM_VK_F26",
"DOM_VK_F27",
"DOM_VK_F28",
"DOM_VK_F29",
"DOM_VK_F3",
"DOM_VK_F30",
"DOM_VK_F31",
"DOM_VK_F32",
"DOM_VK_F33",
"DOM_VK_F34",
"DOM_VK_F35",
"DOM_VK_F36",
"DOM_VK_F4",
"DOM_VK_F5",
"DOM_VK_F6",
"DOM_VK_F7",
"DOM_VK_F8",
"DOM_VK_F9",
"DOM_VK_FINAL",
"DOM_VK_FRONT",
"DOM_VK_G",
"DOM_VK_GREATER_THAN",
"DOM_VK_H",
"DOM_VK_HANGUL",
"DOM_VK_HANJA",
"DOM_VK_HASH",
"DOM_VK_HELP",
"DOM_VK_HK_TOGGLE",
"DOM_VK_HOME",
"DOM_VK_HYPHEN_MINUS",
"DOM_VK_I",
"DOM_VK_INSERT",
"DOM_VK_J",
"DOM_VK_JUNJA",
"DOM_VK_K",
"DOM_VK_KANA",
"DOM_VK_KANJI",
"DOM_VK_L",
"DOM_VK_LEFT",
"DOM_VK_LEFT_TAB",
"DOM_VK_LESS_THAN",
"DOM_VK_M",
"DOM_VK_META",
"DOM_VK_MODECHANGE",
"DOM_VK_MULTIPLY",
"DOM_VK_N",
"DOM_VK_NONCONVERT",
"DOM_VK_NUMPAD0",
"DOM_VK_NUMPAD1",
"DOM_VK_NUMPAD2",
"DOM_VK_NUMPAD3",
"DOM_VK_NUMPAD4",
"DOM_VK_NUMPAD5",
"DOM_VK_NUMPAD6",
"DOM_VK_NUMPAD7",
"DOM_VK_NUMPAD8",
"DOM_VK_NUMPAD9",
"DOM_VK_NUM_LOCK",
"DOM_VK_O",
"DOM_VK_OEM_1",
"DOM_VK_OEM_102",
"DOM_VK_OEM_2",
"DOM_VK_OEM_3",
"DOM_VK_OEM_4",
"DOM_VK_OEM_5",
"DOM_VK_OEM_6",
"DOM_VK_OEM_7",
"DOM_VK_OEM_8",
"DOM_VK_OEM_COMMA",
"DOM_VK_OEM_MINUS",
"DOM_VK_OEM_PERIOD",
"DOM_VK_OEM_PLUS",
"DOM_VK_OPEN_BRACKET",
"DOM_VK_OPEN_CURLY_BRACKET",
"DOM_VK_OPEN_PAREN",
"DOM_VK_P",
"DOM_VK_PA1",
"DOM_VK_PAGEDOWN",
"DOM_VK_PAGEUP",
"DOM_VK_PAGE_DOWN",
"DOM_VK_PAGE_UP",
"DOM_VK_PAUSE",
"DOM_VK_PERCENT",
"DOM_VK_PERIOD",
"DOM_VK_PIPE",
"DOM_VK_PLAY",
"DOM_VK_PLUS",
"DOM_VK_PRINT",
"DOM_VK_PRINTSCREEN",
"DOM_VK_PROCESSKEY",
"DOM_VK_PROPERITES",
"DOM_VK_Q",
"DOM_VK_QUESTION_MARK",
"DOM_VK_QUOTE",
"DOM_VK_R",
"DOM_VK_REDO",
"DOM_VK_RETURN",
"DOM_VK_RIGHT",
"DOM_VK_S",
"DOM_VK_SCROLL_LOCK",
"DOM_VK_SELECT",
"DOM_VK_SEMICOLON",
"DOM_VK_SEPARATOR",
"DOM_VK_SHIFT",
"DOM_VK_SLASH",
"DOM_VK_SLEEP",
"DOM_VK_SPACE",
"DOM_VK_SUBTRACT",
"DOM_VK_T",
"DOM_VK_TAB",
"DOM_VK_TILDE",
"DOM_VK_U",
"DOM_VK_UNDERSCORE",
"DOM_VK_UNDO",
"DOM_VK_UNICODE",
"DOM_VK_UP",
"DOM_VK_V",
"DOM_VK_VOLUME_DOWN",
"DOM_VK_VOLUME_MUTE",
"DOM_VK_VOLUME_UP",
"DOM_VK_W",
"DOM_VK_WIN",
"DOM_VK_WINDOW",
"DOM_VK_WIN_ICO_00",
"DOM_VK_WIN_ICO_CLEAR",
"DOM_VK_WIN_ICO_HELP",
"DOM_VK_WIN_OEM_ATTN",
"DOM_VK_WIN_OEM_AUTO",
"DOM_VK_WIN_OEM_BACKTAB",
"DOM_VK_WIN_OEM_CLEAR",
"DOM_VK_WIN_OEM_COPY",
"DOM_VK_WIN_OEM_CUSEL",
"DOM_VK_WIN_OEM_ENLW",
"DOM_VK_WIN_OEM_FINISH",
"DOM_VK_WIN_OEM_FJ_JISHO",
"DOM_VK_WIN_OEM_FJ_LOYA",
"DOM_VK_WIN_OEM_FJ_MASSHOU",
"DOM_VK_WIN_OEM_FJ_ROYA",
"DOM_VK_WIN_OEM_FJ_TOUROKU",
"DOM_VK_WIN_OEM_JUMP",
"DOM_VK_WIN_OEM_PA1",
"DOM_VK_WIN_OEM_PA2",
"DOM_VK_WIN_OEM_PA3",
"DOM_VK_WIN_OEM_RESET",
"DOM_VK_WIN_OEM_WSCTRL",
"DOM_VK_X",
"DOM_VK_XF86XK_ADD_FAVORITE",
"DOM_VK_XF86XK_APPLICATION_LEFT",
"DOM_VK_XF86XK_APPLICATION_RIGHT",
"DOM_VK_XF86XK_AUDIO_CYCLE_TRACK",
"DOM_VK_XF86XK_AUDIO_FORWARD",
"DOM_VK_XF86XK_AUDIO_LOWER_VOLUME",
"DOM_VK_XF86XK_AUDIO_MEDIA",
"DOM_VK_XF86XK_AUDIO_MUTE",
"DOM_VK_XF86XK_AUDIO_NEXT",
"DOM_VK_XF86XK_AUDIO_PAUSE",
"DOM_VK_XF86XK_AUDIO_PLAY",
"DOM_VK_XF86XK_AUDIO_PREV",
"DOM_VK_XF86XK_AUDIO_RAISE_VOLUME",
"DOM_VK_XF86XK_AUDIO_RANDOM_PLAY",
"DOM_VK_XF86XK_AUDIO_RECORD",
"DOM_VK_XF86XK_AUDIO_REPEAT",
"DOM_VK_XF86XK_AUDIO_REWIND",
"DOM_VK_XF86XK_AUDIO_STOP",
"DOM_VK_XF86XK_AWAY",
"DOM_VK_XF86XK_BACK",
"DOM_VK_XF86XK_BACK_FORWARD",
"DOM_VK_XF86XK_BATTERY",
"DOM_VK_XF86XK_BLUE",
"DOM_VK_XF86XK_BLUETOOTH",
"DOM_VK_XF86XK_BOOK",
"DOM_VK_XF86XK_BRIGHTNESS_ADJUST",
"DOM_VK_XF86XK_CALCULATOR",
"DOM_VK_XF86XK_CALENDAR",
"DOM_VK_XF86XK_CD",
"DOM_VK_XF86XK_CLOSE",
"DOM_VK_XF86XK_COMMUNITY",
"DOM_VK_XF86XK_CONTRAST_ADJUST",
"DOM_VK_XF86XK_COPY",
"DOM_VK_XF86XK_CUT",
"DOM_VK_XF86XK_CYCLE_ANGLE",
"DOM_VK_XF86XK_DISPLAY",
"DOM_VK_XF86XK_DOCUMENTS",
"DOM_VK_XF86XK_DOS",
"DOM_VK_XF86XK_EJECT",
"DOM_VK_XF86XK_EXCEL",
"DOM_VK_XF86XK_EXPLORER",
"DOM_VK_XF86XK_FAVORITES",
"DOM_VK_XF86XK_FINANCE",
"DOM_VK_XF86XK_FORWARD",
"DOM_VK_XF86XK_FRAME_BACK",
"DOM_VK_XF86XK_FRAME_FORWARD",
"DOM_VK_XF86XK_GAME",
"DOM_VK_XF86XK_GO",
"DOM_VK_XF86XK_GREEN",
"DOM_VK_XF86XK_HIBERNATE",
"DOM_VK_XF86XK_HISTORY",
"DOM_VK_XF86XK_HOME_PAGE",
"DOM_VK_XF86XK_HOT_LINKS",
"DOM_VK_XF86XK_I_TOUCH",
"DOM_VK_XF86XK_KBD_BRIGHTNESS_DOWN",
"DOM_VK_XF86XK_KBD_BRIGHTNESS_UP",
"DOM_VK_XF86XK_KBD_LIGHT_ON_OFF",
"DOM_VK_XF86XK_LAUNCH0",
"DOM_VK_XF86XK_LAUNCH1",
"DOM_VK_XF86XK_LAUNCH2",
"DOM_VK_XF86XK_LAUNCH3",
"DOM_VK_XF86XK_LAUNCH4",
"DOM_VK_XF86XK_LAUNCH5",
"DOM_VK_XF86XK_LAUNCH6",
"DOM_VK_XF86XK_LAUNCH7",
"DOM_VK_XF86XK_LAUNCH8",
"DOM_VK_XF86XK_LAUNCH9",
"DOM_VK_XF86XK_LAUNCH_A",
"DOM_VK_XF86XK_LAUNCH_B",
"DOM_VK_XF86XK_LAUNCH_C",
"DOM_VK_XF86XK_LAUNCH_D",
"DOM_VK_XF86XK_LAUNCH_E",
"DOM_VK_XF86XK_LAUNCH_F",
"DOM_VK_XF86XK_LIGHT_BULB",
"DOM_VK_XF86XK_LOG_OFF",
"DOM_VK_XF86XK_MAIL",
"DOM_VK_XF86XK_MAIL_FORWARD",
"DOM_VK_XF86XK_MARKET",
"DOM_VK_XF86XK_MEETING",
"DOM_VK_XF86XK_MEMO",
"DOM_VK_XF86XK_MENU_KB",
"DOM_VK_XF86XK_MENU_PB",
"DOM_VK_XF86XK_MESSENGER",
"DOM_VK_XF86XK_MON_BRIGHTNESS_DOWN",
"DOM_VK_XF86XK_MON_BRIGHTNESS_UP",
"DOM_VK_XF86XK_MUSIC",
"DOM_VK_XF86XK_MY_COMPUTER",
"DOM_VK_XF86XK_MY_SITES",
"DOM_VK_XF86XK_NEW",
"DOM_VK_XF86XK_NEWS",
"DOM_VK_XF86XK_OFFICE_HOME",
"DOM_VK_XF86XK_OPEN",
"DOM_VK_XF86XK_OPEN_URL",
"DOM_VK_XF86XK_OPTION",
"DOM_VK_XF86XK_PASTE",
"DOM_VK_XF86XK_PHONE",
"DOM_VK_XF86XK_PICTURES",
"DOM_VK_XF86XK_POWER_DOWN",
"DOM_VK_XF86XK_POWER_OFF",
"DOM_VK_XF86XK_RED",
"DOM_VK_XF86XK_REFRESH",
"DOM_VK_XF86XK_RELOAD",
"DOM_VK_XF86XK_REPLY",
"DOM_VK_XF86XK_ROCKER_DOWN",
"DOM_VK_XF86XK_ROCKER_ENTER",
"DOM_VK_XF86XK_ROCKER_UP",
"DOM_VK_XF86XK_ROTATE_WINDOWS",
"DOM_VK_XF86XK_ROTATION_KB",
"DOM_VK_XF86XK_ROTATION_PB",
"DOM_VK_XF86XK_SAVE",
"DOM_VK_XF86XK_SCREEN_SAVER",
"DOM_VK_XF86XK_SCROLL_CLICK",
"DOM_VK_XF86XK_SCROLL_DOWN",
"DOM_VK_XF86XK_SCROLL_UP",
"DOM_VK_XF86XK_SEARCH",
"DOM_VK_XF86XK_SEND",
"DOM_VK_XF86XK_SHOP",
"DOM_VK_XF86XK_SPELL",
"DOM_VK_XF86XK_SPLIT_SCREEN",
"DOM_VK_XF86XK_STANDBY",
"DOM_VK_XF86XK_START",
"DOM_VK_XF86XK_STOP",
"DOM_VK_XF86XK_SUBTITLE",
"DOM_VK_XF86XK_SUPPORT",
"DOM_VK_XF86XK_SUSPEND",
"DOM_VK_XF86XK_TASK_PANE",
"DOM_VK_XF86XK_TERMINAL",
"DOM_VK_XF86XK_TIME",
"DOM_VK_XF86XK_TOOLS",
"DOM_VK_XF86XK_TOP_MENU",
"DOM_VK_XF86XK_TO_DO_LIST",
"DOM_VK_XF86XK_TRAVEL",
"DOM_VK_XF86XK_USER1KB",
"DOM_VK_XF86XK_USER2KB",
"DOM_VK_XF86XK_USER_PB",
"DOM_VK_XF86XK_UWB",
"DOM_VK_XF86XK_VENDOR_HOME",
"DOM_VK_XF86XK_VIDEO",
"DOM_VK_XF86XK_VIEW",
"DOM_VK_XF86XK_WAKE_UP",
"DOM_VK_XF86XK_WEB_CAM",
"DOM_VK_XF86XK_WHEEL_BUTTON",
"DOM_VK_XF86XK_WLAN",
"DOM_VK_XF86XK_WORD",
"DOM_VK_XF86XK_WWW",
"DOM_VK_XF86XK_XFER",
"DOM_VK_XF86XK_YELLOW",
"DOM_VK_XF86XK_ZOOM_IN",
"DOM_VK_XF86XK_ZOOM_OUT",
"DOM_VK_Y",
"DOM_VK_Z",
"DOM_VK_ZOOM",
"DONE",
"DONT_CARE",
"DOWNLOADING",
"DRAGDROP",
"DRAW_BUFFER0",
"DRAW_BUFFER1",
"DRAW_BUFFER10",
"DRAW_BUFFER11",
"DRAW_BUFFER12",
"DRAW_BUFFER13",
"DRAW_BUFFER14",
"DRAW_BUFFER15",
"DRAW_BUFFER2",
"DRAW_BUFFER3",
"DRAW_BUFFER4",
"DRAW_BUFFER5",
"DRAW_BUFFER6",
"DRAW_BUFFER7",
"DRAW_BUFFER8",
"DRAW_BUFFER9",
"DRAW_FRAMEBUFFER",
"DRAW_FRAMEBUFFER_BINDING",
"DST_ALPHA",
"DST_COLOR",
"DYNAMIC_COPY",
"DYNAMIC_DRAW",
"DYNAMIC_READ",
"DataChannel",
"DataTransfer",
"DataTransferItem",
"DataTransferItemList",
"DataView",
"Date",
"DateTimeFormat",
"DecompressionStream",
"DelayNode",
"DeprecationReportBody",
"DesktopNotification",
"DesktopNotificationCenter",
"DeviceLightEvent",
"DeviceMotionEvent",
"DeviceMotionEventAcceleration",
"DeviceMotionEventRotationRate",
"DeviceOrientationEvent",
"DeviceProximityEvent",
"DeviceStorage",
"DeviceStorageChangeEvent",
"Directory",
"DisplayNames",
"Document",
"DocumentFragment",
"DocumentTimeline",
"DocumentType",
"DragEvent",
"DynamicsCompressorNode",
"E",
"ELEMENT_ARRAY_BUFFER",
"ELEMENT_ARRAY_BUFFER_BINDING",
"ELEMENT_NODE",
"EMPTY",
"ENCODING_ERR",
"ENDED",
"END_TO_END",
"END_TO_START",
"ENTITY_NODE",
"ENTITY_REFERENCE_NODE",
"EPSILON",
"EQUAL",
"EQUALPOWER",
"ERROR",
"EXPONENTIAL_DISTANCE",
"Element",
"ElementInternals",
"ElementQuery",
"EnterPictureInPictureEvent",
"Entity",
"EntityReference",
"Error",
"ErrorEvent",
"EvalError",
"Event",
"EventException",
"EventSource",
"EventTarget",
"External",
"FASTEST",
"FIDOSDK",
"FILTER_ACCEPT",
"FILTER_INTERRUPT",
"FILTER_REJECT",
"FILTER_SKIP",
"FINISHED_STATE",
"FIRST_ORDERED_NODE_TYPE",
"FLOAT",
"FLOAT_32_UNSIGNED_INT_24_8_REV",
"FLOAT_MAT2",
"FLOAT_MAT2x3",
"FLOAT_MAT2x4",
"FLOAT_MAT3",
"FLOAT_MAT3x2",
"FLOAT_MAT3x4",
"FLOAT_MAT4",
"FLOAT_MAT4x2",
"FLOAT_MAT4x3",
"FLOAT_VEC2",
"FLOAT_VEC3",
"FLOAT_VEC4",
"FOCUS",
"FONT_FACE_RULE",
"FONT_FEATURE_VALUES_RULE",
"FRAGMENT_SHADER",
"FRAGMENT_SHADER_DERIVATIVE_HINT",
"FRAGMENT_SHADER_DERIVATIVE_HINT_OES",
"FRAMEBUFFER",
"FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE",
"FRAMEBUFFER_ATTACHMENT_BLUE_SIZE",
"FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING",
"FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE",
"FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE",
"FRAMEBUFFER_ATTACHMENT_GREEN_SIZE",
"FRAMEBUFFER_ATTACHMENT_OBJECT_NAME",
"FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE",
"FRAMEBUFFER_ATTACHMENT_RED_SIZE",
"FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE",
"FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE",
"FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER",
"FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL",
"FRAMEBUFFER_BINDING",
"FRAMEBUFFER_COMPLETE",
"FRAMEBUFFER_DEFAULT",
"FRAMEBUFFER_INCOMPLETE_ATTACHMENT",
"FRAMEBUFFER_INCOMPLETE_DIMENSIONS",
"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT",
"FRAMEBUFFER_INCOMPLETE_MULTISAMPLE",
"FRAMEBUFFER_UNSUPPORTED",
"FRONT",
"FRONT_AND_BACK",
"FRONT_FACE",
"FUNC_ADD",
"FUNC_REVERSE_SUBTRACT",
"FUNC_SUBTRACT",
"FeaturePolicy",
"FeaturePolicyViolationReportBody",
"FederatedCredential",
"Feed",
"FeedEntry",
"File",
"FileError",
"FileList",
"FileReader",
"FileSystem",
"FileSystemDirectoryEntry",
"FileSystemDirectoryReader",
"FileSystemEntry",
"FileSystemFileEntry",
"FinalizationRegistry",
"FindInPage",
"Float32Array",
"Float64Array",
"FocusEvent",
"FontFace",
"FontFaceSet",
"FontFaceSetLoadEvent",
"FormData",
"FormDataEvent",
"FragmentDirective",
"Function",
"GENERATE_MIPMAP_HINT",
"GEQUAL",
"GREATER",
"GREEN_BITS",
"GainNode",
"Gamepad",
"GamepadAxisMoveEvent",
"GamepadButton",
"GamepadButtonEvent",
"GamepadEvent",
"GamepadHapticActuator",
"GamepadPose",
"Geolocation",
"GeolocationCoordinates",
"GeolocationPosition",
"GeolocationPositionError",
"GestureEvent",
"Global",
"Gyroscope",
"HALF_FLOAT",
"HAVE_CURRENT_DATA",
"HAVE_ENOUGH_DATA",
"HAVE_FUTURE_DATA",
"HAVE_METADATA",
"HAVE_NOTHING",
"HEADERS_RECEIVED",
"HIDDEN",
"HIERARCHY_REQUEST_ERR",
"HIGHPASS",
"HIGHSHELF",
"HIGH_FLOAT",
"HIGH_INT",
"HORIZONTAL",
"HORIZONTAL_AXIS",
"HRTF",
"HTMLAllCollection",
"HTMLAnchorElement",
"HTMLAppletElement",
"HTMLAreaElement",
"HTMLAudioElement",
"HTMLBRElement",
"HTMLBaseElement",
"HTMLBaseFontElement",
"HTMLBlockquoteElement",
"HTMLBodyElement",
"HTMLButtonElement",
"HTMLCanvasElement",
"HTMLCollection",
"HTMLCommandElement",
"HTMLContentElement",
"HTMLDListElement",
"HTMLDataElement",
"HTMLDataListElement",
"HTMLDetailsElement",
"HTMLDialogElement",
"HTMLDirectoryElement",
"HTMLDivElement",
"HTMLDocument",
"HTMLElement",
"HTMLEmbedElement",
"HTMLFieldSetElement",
"HTMLFontElement",
"HTMLFormControlsCollection",
"HTMLFormElement",
"HTMLFrameElement",
"HTMLFrameSetElement",
"HTMLHRElement",
"HTMLHeadElement",
"HTMLHeadingElement",
"HTMLHtmlElement",
"HTMLIFrameElement",
"HTMLImageElement",
"HTMLInputElement",
"HTMLIsIndexElement",
"HTMLKeygenElement",
"HTMLLIElement",
"HTMLLabelElement",
"HTMLLegendElement",
"HTMLLinkElement",
"HTMLMapElement",
"HTMLMarqueeElement",
"HTMLMediaElement",
"HTMLMenuElement",
"HTMLMenuItemElement",
"HTMLMetaElement",
"HTMLMeterElement",
"HTMLModElement",
"HTMLOListElement",
"HTMLObjectElement",
"HTMLOptGroupElement",
"HTMLOptionElement",
"HTMLOptionsCollection",
"HTMLOutputElement",
"HTMLParagraphElement",
"HTMLParamElement",
"HTMLPictureElement",
"HTMLPreElement",
"HTMLProgressElement",
"HTMLPropertiesCollection",
"HTMLQuoteElement",
"HTMLScriptElement",
"HTMLSelectElement",
"HTMLShadowElement",
"HTMLSlotElement",
"HTMLSourceElement",
"HTMLSpanElement",
"HTMLStyleElement",
"HTMLTableCaptionElement",
"HTMLTableCellElement",
"HTMLTableColElement",
"HTMLTableElement",
"HTMLTableRowElement",
"HTMLTableSectionElement",
"HTMLTemplateElement",
"HTMLTextAreaElement",
"HTMLTimeElement",
"HTMLTitleElement",
"HTMLTrackElement",
"HTMLUListElement",
"HTMLUnknownElement",
"HTMLVideoElement",
"HashChangeEvent",
"Headers",
"History",
"Hz",
"ICE_CHECKING",
"ICE_CLOSED",
"ICE_COMPLETED",
"ICE_CONNECTED",
"ICE_FAILED",
"ICE_GATHERING",
"ICE_WAITING",
"IDBCursor",
"IDBCursorWithValue",
"IDBDatabase",
"IDBDatabaseException",
"IDBFactory",
"IDBFileHandle",
"IDBFileRequest",
"IDBIndex",
"IDBKeyRange",
"IDBMutableFile",
"IDBObjectStore",
"IDBOpenDBRequest",
"IDBRequest",
"IDBTransaction",
"IDBVersionChangeEvent",
"IDLE",
"IIRFilterNode",
"IMPLEMENTATION_COLOR_READ_FORMAT",
"IMPLEMENTATION_COLOR_READ_TYPE",
"IMPORT_RULE",
"INCR",
"INCR_WRAP",
"INDEX_SIZE_ERR",
"INT",
"INTERLEAVED_ATTRIBS",
"INT_2_10_10_10_REV",
"INT_SAMPLER_2D",
"INT_SAMPLER_2D_ARRAY",
"INT_SAMPLER_3D",
"INT_SAMPLER_CUBE",
"INT_VEC2",
"INT_VEC3",
"INT_VEC4",
"INUSE_ATTRIBUTE_ERR",
"INVALID_ACCESS_ERR",
"INVALID_CHARACTER_ERR",
"INVALID_ENUM",
"INVALID_EXPRESSION_ERR",
"INVALID_FRAMEBUFFER_OPERATION",
"INVALID_INDEX",
"INVALID_MODIFICATION_ERR",
"INVALID_NODE_TYPE_ERR",
"INVALID_OPERATION",
"INVALID_STATE_ERR",
"INVALID_VALUE",
"INVERSE_DISTANCE",
"INVERT",
"IceCandidate",
"IdleDeadline",
"Image",
"ImageBitmap",
"ImageBitmapRenderingContext",
"ImageCapture",
"ImageData",
"Infinity",
"InputDeviceCapabilities",
"InputDeviceInfo",
"InputEvent",
"InputMethodContext",
"InstallTrigger",
"InstallTriggerImpl",
"Instance",
"Int16Array",
"Int32Array",
"Int8Array",
"Intent",
"InternalError",
"IntersectionObserver",
"IntersectionObserverEntry",
"Intl",
"IsSearchProviderInstalled",
"Iterator",
"JSON",
"KEEP",
"KEYDOWN",
"KEYFRAMES_RULE",
"KEYFRAME_RULE",
"KEYPRESS",
"KEYUP",
"KeyEvent",
"Keyboard",
"KeyboardEvent",
"KeyboardLayoutMap",
"KeyframeEffect",
"LENGTHADJUST_SPACING",
"LENGTHADJUST_SPACINGANDGLYPHS",
"LENGTHADJUST_UNKNOWN",
"LEQUAL",
"LESS",
"LINEAR",
"LINEAR_DISTANCE",
"LINEAR_MIPMAP_LINEAR",
"LINEAR_MIPMAP_NEAREST",
"LINES",
"LINE_LOOP",
"LINE_STRIP",
"LINE_WIDTH",
"LINK_STATUS",
"LIVE",
"LN10",
"LN2",
"LOADED",
"LOADING",
"LOG10E",
"LOG2E",
"LOWPASS",
"LOWSHELF",
"LOW_FLOAT",
"LOW_INT",
"LSException",
"LSParserFilter",
"LUMINANCE",
"LUMINANCE_ALPHA",
"LargestContentfulPaint",
"LayoutShift",
"LayoutShiftAttribution",
"LinearAccelerationSensor",
"LinkError",
"ListFormat",
"LocalMediaStream",
"Locale",
"Location",
"Lock",
"LockManager",
"MAX",
"MAX_3D_TEXTURE_SIZE",
"MAX_ARRAY_TEXTURE_LAYERS",
"MAX_CLIENT_WAIT_TIMEOUT_WEBGL",
"MAX_COLOR_ATTACHMENTS",
"MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS",
"MAX_COMBINED_TEXTURE_IMAGE_UNITS",
"MAX_COMBINED_UNIFORM_BLOCKS",
"MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS",
"MAX_CUBE_MAP_TEXTURE_SIZE",
"MAX_DRAW_BUFFERS",
"MAX_ELEMENTS_INDICES",
"MAX_ELEMENTS_VERTICES",
"MAX_ELEMENT_INDEX",
"MAX_FRAGMENT_INPUT_COMPONENTS",
"MAX_FRAGMENT_UNIFORM_BLOCKS",
"MAX_FRAGMENT_UNIFORM_COMPONENTS",
"MAX_FRAGMENT_UNIFORM_VECTORS",
"MAX_PROGRAM_TEXEL_OFFSET",
"MAX_RENDERBUFFER_SIZE",
"MAX_SAFE_INTEGER",
"MAX_SAMPLES",
"MAX_SERVER_WAIT_TIMEOUT",
"MAX_TEXTURE_IMAGE_UNITS",
"MAX_TEXTURE_LOD_BIAS",
"MAX_TEXTURE_MAX_ANISOTROPY_EXT",
"MAX_TEXTURE_SIZE",
"MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS",
"MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS",
"MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS",
"MAX_UNIFORM_BLOCK_SIZE",
"MAX_UNIFORM_BUFFER_BINDINGS",
"MAX_VALUE",
"MAX_VARYING_COMPONENTS",
"MAX_VARYING_VECTORS",
"MAX_VERTEX_ATTRIBS",
"MAX_VERTEX_OUTPUT_COMPONENTS",
"MAX_VERTEX_TEXTURE_IMAGE_UNITS",
"MAX_VERTEX_UNIFORM_BLOCKS",
"MAX_VERTEX_UNIFORM_COMPONENTS",
"MAX_VERTEX_UNIFORM_VECTORS",
"MAX_VIEWPORT_DIMS",
"MEDIA_ERR_ABORTED",
"MEDIA_ERR_DECODE",
"MEDIA_ERR_ENCRYPTED",
"MEDIA_ERR_NETWORK",
"MEDIA_ERR_SRC_NOT_SUPPORTED",
"MEDIA_KEYERR_CLIENT",
"MEDIA_KEYERR_DOMAIN",
"MEDIA_KEYERR_HARDWARECHANGE",
"MEDIA_KEYERR_OUTPUT",
"MEDIA_KEYERR_SERVICE",
"MEDIA_KEYERR_UNKNOWN",
"MEDIA_RULE",
"MEDIUM_FLOAT",
"MEDIUM_INT",
"META_MASK",
"MIDIAccess",
"MIDIConnectionEvent",
"MIDIInput",
"MIDIInputMap",
"MIDIMessageEvent",
"MIDIOutput",
"MIDIOutputMap",
"MIDIPort",
"MIN",
"MIN_PROGRAM_TEXEL_OFFSET",
"MIN_SAFE_INTEGER",
"MIN_VALUE",
"MIRRORED_REPEAT",
"MODE_ASYNCHRONOUS",
"MODE_SYNCHRONOUS",
"MODIFICATION",
"MOUSEDOWN",
"MOUSEDRAG",
"MOUSEMOVE",
"MOUSEOUT",
"MOUSEOVER",
"MOUSEUP",
"MOZ_KEYFRAMES_RULE",
"MOZ_KEYFRAME_RULE",
"MOZ_SOURCE_CURSOR",
"MOZ_SOURCE_ERASER",
"MOZ_SOURCE_KEYBOARD",
"MOZ_SOURCE_MOUSE",
"MOZ_SOURCE_PEN",
"MOZ_SOURCE_TOUCH",
"MOZ_SOURCE_UNKNOWN",
"MSGESTURE_FLAG_BEGIN",
"MSGESTURE_FLAG_CANCEL",
"MSGESTURE_FLAG_END",
"MSGESTURE_FLAG_INERTIA",
"MSGESTURE_FLAG_NONE",
"MSPOINTER_TYPE_MOUSE",
"MSPOINTER_TYPE_PEN",
"MSPOINTER_TYPE_TOUCH",
"MS_ASYNC_CALLBACK_STATUS_ASSIGN_DELEGATE",
"MS_ASYNC_CALLBACK_STATUS_CANCEL",
"MS_ASYNC_CALLBACK_STATUS_CHOOSEANY",
"MS_ASYNC_CALLBACK_STATUS_ERROR",
"MS_ASYNC_CALLBACK_STATUS_JOIN",
"MS_ASYNC_OP_STATUS_CANCELED",
"MS_ASYNC_OP_STATUS_ERROR",
"MS_ASYNC_OP_STATUS_SUCCESS",
"MS_MANIPULATION_STATE_ACTIVE",
"MS_MANIPULATION_STATE_CANCELLED",
"MS_MANIPULATION_STATE_COMMITTED",
"MS_MANIPULATION_STATE_DRAGGING",
"MS_MANIPULATION_STATE_INERTIA",
"MS_MANIPULATION_STATE_PRESELECT",
"MS_MANIPULATION_STATE_SELECTING",
"MS_MANIPULATION_STATE_STOPPED",
"MS_MEDIA_ERR_ENCRYPTED",
"MS_MEDIA_KEYERR_CLIENT",
"MS_MEDIA_KEYERR_DOMAIN",
"MS_MEDIA_KEYERR_HARDWARECHANGE",
"MS_MEDIA_KEYERR_OUTPUT",
"MS_MEDIA_KEYERR_SERVICE",
"MS_MEDIA_KEYERR_UNKNOWN",
"Map",
"Math",
"MathMLElement",
"MediaCapabilities",
"MediaCapabilitiesInfo",
"MediaController",
"MediaDeviceInfo",
"MediaDevices",
"MediaElementAudioSourceNode",
"MediaEncryptedEvent",
"MediaError",
"MediaKeyError",
"MediaKeyEvent",
"MediaKeyMessageEvent",
"MediaKeyNeededEvent",
"MediaKeySession",
"MediaKeyStatusMap",
"MediaKeySystemAccess",
"MediaKeys",
"MediaList",
"MediaMetadata",
"MediaQueryList",
"MediaQueryListEvent",
"MediaRecorder",
"MediaRecorderErrorEvent",
"MediaSession",
"MediaSettingsRange",
"MediaSource",
"MediaStream",
"MediaStreamAudioDestinationNode",
"MediaStreamAudioSourceNode",
"MediaStreamEvent",
"MediaStreamTrack",
"MediaStreamTrackAudioSourceNode",
"MediaStreamTrackEvent",
"Memory",
"MessageChannel",
"MessageEvent",
"MessagePort",
"Methods",
"MimeType",
"MimeTypeArray",
"Module",
"MouseEvent",
"MouseScrollEvent",
"MozAnimation",
"MozAnimationDelay",
"MozAnimationDirection",
"MozAnimationDuration",
"MozAnimationFillMode",
"MozAnimationIterationCount",
"MozAnimationName",
"MozAnimationPlayState",
"MozAnimationTimingFunction",
"MozAppearance",
"MozBackfaceVisibility",
"MozBinding",
"MozBorderBottomColors",
"MozBorderEnd",
"MozBorderEndColor",
"MozBorderEndStyle",
"MozBorderEndWidth",
"MozBorderImage",
"MozBorderLeftColors",
"MozBorderRightColors",
"MozBorderStart",
"MozBorderStartColor",
"MozBorderStartStyle",
"MozBorderStartWidth",
"MozBorderTopColors",
"MozBoxAlign",
"MozBoxDirection",
"MozBoxFlex",
"MozBoxOrdinalGroup",
"MozBoxOrient",
"MozBoxPack",
"MozBoxSizing",
"MozCSSKeyframeRule",
"MozCSSKeyframesRule",
"MozColumnCount",
"MozColumnFill",
"MozColumnGap",
"MozColumnRule",
"MozColumnRuleColor",
"MozColumnRuleStyle",
"MozColumnRuleWidth",
"MozColumnWidth",
"MozColumns",
"MozContactChangeEvent",
"MozFloatEdge",
"MozFontFeatureSettings",
"MozFontLanguageOverride",
"MozForceBrokenImageIcon",
"MozHyphens",
"MozImageRegion",
"MozMarginEnd",
"MozMarginStart",
"MozMmsEvent",
"MozMmsMessage",
"MozMobileMessageThread",
"MozOSXFontSmoothing",
"MozOrient",
"MozOsxFontSmoothing",
"MozOutlineRadius",
"MozOutlineRadiusBottomleft",
"MozOutlineRadiusBottomright",
"MozOutlineRadiusTopleft",
"MozOutlineRadiusTopright",
"MozPaddingEnd",
"MozPaddingStart",
"MozPerspective",
"MozPerspectiveOrigin",
"MozPowerManager",
"MozSettingsEvent",
"MozSmsEvent",
"MozSmsMessage",
"MozStackSizing",
"MozTabSize",
"MozTextAlignLast",
"MozTextDecorationColor",
"MozTextDecorationLine",
"MozTextDecorationStyle",
"MozTextSizeAdjust",
"MozTransform",
"MozTransformOrigin",
"MozTransformStyle",
"MozTransition",
"MozTransitionDelay",
"MozTransitionDuration",
"MozTransitionProperty",
"MozTransitionTimingFunction",
"MozUserFocus",
"MozUserInput",
"MozUserModify",
"MozUserSelect",
"MozWindowDragging",
"MozWindowShadow",
"MutationEvent",
"MutationObserver",
"MutationRecord",
"NAMESPACE_ERR",
"NAMESPACE_RULE",
"NEAREST",
"NEAREST_MIPMAP_LINEAR",
"NEAREST_MIPMAP_NEAREST",
"NEGATIVE_INFINITY",
"NETWORK_EMPTY",
"NETWORK_ERR",
"NETWORK_IDLE",
"NETWORK_LOADED",
"NETWORK_LOADING",
"NETWORK_NO_SOURCE",
"NEVER",
"NEW",
"NEXT",
"NEXT_NO_DUPLICATE",
"NICEST",
"NODE_AFTER",
"NODE_BEFORE",
"NODE_BEFORE_AND_AFTER",
"NODE_INSIDE",
"NONE",
"NON_TRANSIENT_ERR",
"NOTATION_NODE",
"NOTCH",
"NOTEQUAL",
"NOT_ALLOWED_ERR",
"NOT_FOUND_ERR",
"NOT_READABLE_ERR",
"NOT_SUPPORTED_ERR",
"NO_DATA_ALLOWED_ERR",
"NO_ERR",
"NO_ERROR",
"NO_MODIFICATION_ALLOWED_ERR",
"NUMBER_TYPE",
"NUM_COMPRESSED_TEXTURE_FORMATS",
"NaN",
"NamedNodeMap",
"NavigationPreloadManager",
"Navigator",
"NearbyLinks",
"NetworkInformation",
"Node",
"NodeFilter",
"NodeIterator",
"NodeList",
"Notation",
"Notification",
"NotifyPaintEvent",
"Number",
"NumberFormat",
"OBJECT_TYPE",
"OBSOLETE",
"OK",
"ONE",
"ONE_MINUS_CONSTANT_ALPHA",
"ONE_MINUS_CONSTANT_COLOR",
"ONE_MINUS_DST_ALPHA",
"ONE_MINUS_DST_COLOR",
"ONE_MINUS_SRC_ALPHA",
"ONE_MINUS_SRC_COLOR",
"OPEN",
"OPENED",
"OPENING",
"ORDERED_NODE_ITERATOR_TYPE",
"ORDERED_NODE_SNAPSHOT_TYPE",
"OTHER_ERROR",
"OUT_OF_MEMORY",
"Object",
"OfflineAudioCompletionEvent",
"OfflineAudioContext",
"OfflineResourceList",
"OffscreenCanvas",
"OffscreenCanvasRenderingContext2D",
"Option",
"OrientationSensor",
"OscillatorNode",
"OverconstrainedError",
"OverflowEvent",
"PACK_ALIGNMENT",
"PACK_ROW_LENGTH",
"PACK_SKIP_PIXELS",
"PACK_SKIP_ROWS",
"PAGE_RULE",
"PARSE_ERR",
"PATHSEG_ARC_ABS",
"PATHSEG_ARC_REL",
"PATHSEG_CLOSEPATH",
"PATHSEG_CURVETO_CUBIC_ABS",
"PATHSEG_CURVETO_CUBIC_REL",
"PATHSEG_CURVETO_CUBIC_SMOOTH_ABS",
"PATHSEG_CURVETO_CUBIC_SMOOTH_REL",
"PATHSEG_CURVETO_QUADRATIC_ABS",
"PATHSEG_CURVETO_QUADRATIC_REL",
"PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS",
"PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL",
"PATHSEG_LINETO_ABS",
"PATHSEG_LINETO_HORIZONTAL_ABS",
"PATHSEG_LINETO_HORIZONTAL_REL",
"PATHSEG_LINETO_REL",
"PATHSEG_LINETO_VERTICAL_ABS",
"PATHSEG_LINETO_VERTICAL_REL",
"PATHSEG_MOVETO_ABS",
"PATHSEG_MOVETO_REL",
"PATHSEG_UNKNOWN",
"PATH_EXISTS_ERR",
"PEAKING",
"PERMISSION_DENIED",
"PERSISTENT",
"PI",
"PIXEL_PACK_BUFFER",
"PIXEL_PACK_BUFFER_BINDING",
"PIXEL_UNPACK_BUFFER",
"PIXEL_UNPACK_BUFFER_BINDING",
"PLAYING_STATE",
"POINTS",
"POLYGON_OFFSET_FACTOR",
"POLYGON_OFFSET_FILL",
"POLYGON_OFFSET_UNITS",
"POSITION_UNAVAILABLE",
"POSITIVE_INFINITY",
"PREV",
"PREV_NO_DUPLICATE",
"PROCESSING_INSTRUCTION_NODE",
"PageChangeEvent",
"PageTransitionEvent",
"PaintRequest",
"PaintRequestList",
"PannerNode",
"PasswordCredential",
"Path2D",
"PaymentAddress",
"PaymentInstruments",
"PaymentManager",
"PaymentMethodChangeEvent",
"PaymentRequest",
"PaymentRequestUpdateEvent",
"PaymentResponse",
"Performance",
"PerformanceElementTiming",
"PerformanceEntry",
"PerformanceEventTiming",
"PerformanceLongTaskTiming",
"PerformanceMark",
"PerformanceMeasure",
"PerformanceNavigation",
"PerformanceNavigationTiming",
"PerformanceObserver",
"PerformanceObserverEntryList",
"PerformancePaintTiming",
"PerformanceResourceTiming",
"PerformanceServerTiming",
"PerformanceTiming",
"PeriodicSyncManager",
"PeriodicWave",
"PermissionStatus",
"Permissions",
"PhotoCapabilities",
"PictureInPictureWindow",
"Plugin",
"PluginArray",
"PluralRules",
"PointerEvent",
"PopStateEvent",
"PopupBlockedEvent",
"Presentation",
"PresentationAvailability",
"PresentationConnection",
"PresentationConnectionAvailableEvent",
"PresentationConnectionCloseEvent",
"PresentationConnectionList",
"PresentationReceiver",
"PresentationRequest",
"ProcessingInstruction",
"ProgressEvent",
"Promise",
"PromiseRejectionEvent",
"PropertyNodeList",
"Proxy",
"PublicKeyCredential",
"PushManager",
"PushSubscription",
"PushSubscriptionOptions",
"Q",
"QUERY_RESULT",
"QUERY_RESULT_AVAILABLE",
"QUOTA_ERR",
"QUOTA_EXCEEDED_ERR",
"QueryInterface",
"R11F_G11F_B10F",
"R16F",
"R16I",
"R16UI",
"R32F",
"R32I",
"R32UI",
"R8",
"R8I",
"R8UI",
"R8_SNORM",
"RASTERIZER_DISCARD",
"READ_BUFFER",
"READ_FRAMEBUFFER",
"READ_FRAMEBUFFER_BINDING",
"READ_ONLY",
"READ_ONLY_ERR",
"READ_WRITE",
"RED",
"RED_BITS",
"RED_INTEGER",
"REMOVAL",
"RENDERBUFFER",
"RENDERBUFFER_ALPHA_SIZE",
"RENDERBUFFER_BINDING",
"RENDERBUFFER_BLUE_SIZE",
"RENDERBUFFER_DEPTH_SIZE",
"RENDERBUFFER_GREEN_SIZE",
"RENDERBUFFER_HEIGHT",
"RENDERBUFFER_INTERNAL_FORMAT",
"RENDERBUFFER_RED_SIZE",
"RENDERBUFFER_SAMPLES",
"RENDERBUFFER_STENCIL_SIZE",
"RENDERBUFFER_WIDTH",
"RENDERER",
"RENDERING_INTENT_ABSOLUTE_COLORIMETRIC",
"RENDERING_INTENT_AUTO",
"RENDERING_INTENT_PERCEPTUAL",
"RENDERING_INTENT_RELATIVE_COLORIMETRIC",
"RENDERING_INTENT_SATURATION",
"RENDERING_INTENT_UNKNOWN",
"REPEAT",
"REPLACE",
"RG",
"RG16F",
"RG16I",
"RG16UI",
"RG32F",
"RG32I",
"RG32UI",
"RG8",
"RG8I",
"RG8UI",
"RG8_SNORM",
"RGB",
"RGB10_A2",
"RGB10_A2UI",
"RGB16F",
"RGB16I",
"RGB16UI",
"RGB32F",
"RGB32I",
"RGB32UI",
"RGB565",
"RGB5_A1",
"RGB8",
"RGB8I",
"RGB8UI",
"RGB8_SNORM",
"RGB9_E5",
"RGBA",
"RGBA16F",
"RGBA16I",
"RGBA16UI",
"RGBA32F",
"RGBA32I",
"RGBA32UI",
"RGBA4",
"RGBA8",
"RGBA8I",
"RGBA8UI",
"RGBA8_SNORM",
"RGBA_INTEGER",
"RGBColor",
"RGB_INTEGER",
"RG_INTEGER",
"ROTATION_CLOCKWISE",
"ROTATION_COUNTERCLOCKWISE",
"RTCCertificate",
"RTCDTMFSender",
"RTCDTMFToneChangeEvent",
"RTCDataChannel",
"RTCDataChannelEvent",
"RTCDtlsTransport",
"RTCError",
"RTCErrorEvent",
"RTCIceCandidate",
"RTCIceTransport",
"RTCPeerConnection",
"RTCPeerConnectionIceErrorEvent",
"RTCPeerConnectionIceEvent",
"RTCRtpReceiver",
"RTCRtpSender",
"RTCRtpTransceiver",
"RTCSctpTransport",
"RTCSessionDescription",
"RTCStatsReport",
"RTCTrackEvent",
"RadioNodeList",
"Range",
"RangeError",
"RangeException",
"ReadableStream",
"ReadableStreamDefaultReader",
"RecordErrorEvent",
"Rect",
"ReferenceError",
"Reflect",
"RegExp",
"RelativeOrientationSensor",
"RelativeTimeFormat",
"RemotePlayback",
"Report",
"ReportBody",
"ReportingObserver",
"Request",
"ResizeObserver",
"ResizeObserverEntry",
"ResizeObserverSize",
"Response",
"RuntimeError",
"SAMPLER_2D",
"SAMPLER_2D_ARRAY",
"SAMPLER_2D_ARRAY_SHADOW",
"SAMPLER_2D_SHADOW",
"SAMPLER_3D",
"SAMPLER_BINDING",
"SAMPLER_CUBE",
"SAMPLER_CUBE_SHADOW",
"SAMPLES",
"SAMPLE_ALPHA_TO_COVERAGE",
"SAMPLE_BUFFERS",
"SAMPLE_COVERAGE",
"SAMPLE_COVERAGE_INVERT",
"SAMPLE_COVERAGE_VALUE",
"SAWTOOTH",
"SCHEDULED_STATE",
"SCISSOR_BOX",
"SCISSOR_TEST",
"SCROLL_PAGE_DOWN",
"SCROLL_PAGE_UP",
"SDP_ANSWER",
"SDP_OFFER",
"SDP_PRANSWER",
"SECURITY_ERR",
"SELECT",
"SEPARATE_ATTRIBS",
"SERIALIZE_ERR",
"SEVERITY_ERROR",
"SEVERITY_FATAL_ERROR",
"SEVERITY_WARNING",
"SHADER_COMPILER",
"SHADER_TYPE",
"SHADING_LANGUAGE_VERSION",
"SHIFT_MASK",
"SHORT",
"SHOWING",
"SHOW_ALL",
"SHOW_ATTRIBUTE",
"SHOW_CDATA_SECTION",
"SHOW_COMMENT",
"SHOW_DOCUMENT",
"SHOW_DOCUMENT_FRAGMENT",
"SHOW_DOCUMENT_TYPE",
"SHOW_ELEMENT",
"SHOW_ENTITY",
"SHOW_ENTITY_REFERENCE",
"SHOW_NOTATION",
"SHOW_PROCESSING_INSTRUCTION",
"SHOW_TEXT",
"SIGNALED",
"SIGNED_NORMALIZED",
"SINE",
"SOUNDFIELD",
"SQLException",
"SQRT1_2",
"SQRT2",
"SQUARE",
"SRC_ALPHA",
"SRC_ALPHA_SATURATE",
"SRC_COLOR",
"SRGB",
"SRGB8",
"SRGB8_ALPHA8",
"START_TO_END",
"START_TO_START",
"STATIC_COPY",
"STATIC_DRAW",
"STATIC_READ",
"STENCIL",
"STENCIL_ATTACHMENT",
"STENCIL_BACK_FAIL",
"STENCIL_BACK_FUNC",
"STENCIL_BACK_PASS_DEPTH_FAIL",
"STENCIL_BACK_PASS_DEPTH_PASS",
"STENCIL_BACK_REF",
"STENCIL_BACK_VALUE_MASK",
"STENCIL_BACK_WRITEMASK",
"STENCIL_BITS",
"STENCIL_BUFFER_BIT",
"STENCIL_CLEAR_VALUE",
"STENCIL_FAIL",
"STENCIL_FUNC",
"STENCIL_INDEX",
"STENCIL_INDEX8",
"STENCIL_PASS_DEPTH_FAIL",
"STENCIL_PASS_DEPTH_PASS",
"STENCIL_REF",
"STENCIL_TEST",
"STENCIL_VALUE_MASK",
"STENCIL_WRITEMASK",
"STREAM_COPY",
"STREAM_DRAW",
"STREAM_READ",
"STRING_TYPE",
"STYLE_RULE",
"SUBPIXEL_BITS",
"SUPPORTS_RULE",
"SVGAElement",
"SVGAltGlyphDefElement",
"SVGAltGlyphElement",
"SVGAltGlyphItemElement",
"SVGAngle",
"SVGAnimateColorElement",
"SVGAnimateElement",
"SVGAnimateMotionElement",
"SVGAnimateTransformElement",
"SVGAnimatedAngle",
"SVGAnimatedBoolean",
"SVGAnimatedEnumeration",
"SVGAnimatedInteger",
"SVGAnimatedLength",
"SVGAnimatedLengthList",
"SVGAnimatedNumber",
"SVGAnimatedNumberList",
"SVGAnimatedPreserveAspectRatio",
"SVGAnimatedRect",
"SVGAnimatedString",
"SVGAnimatedTransformList",
"SVGAnimationElement",
"SVGCircleElement",
"SVGClipPathElement",
"SVGColor",
"SVGComponentTransferFunctionElement",
"SVGCursorElement",
"SVGDefsElement",
"SVGDescElement",
"SVGDiscardElement",
"SVGDocument",
"SVGElement",
"SVGElementInstance",
"SVGElementInstanceList",
"SVGEllipseElement",
"SVGException",
"SVGFEBlendElement",
"SVGFEColorMatrixElement",
"SVGFEComponentTransferElement",
"SVGFECompositeElement",
"SVGFEConvolveMatrixElement",
"SVGFEDiffuseLightingElement",
"SVGFEDisplacementMapElement",
"SVGFEDistantLightElement",
"SVGFEDropShadowElement",
"SVGFEFloodElement",
"SVGFEFuncAElement",
"SVGFEFuncBElement",
"SVGFEFuncGElement",
"SVGFEFuncRElement",
"SVGFEGaussianBlurElement",
"SVGFEImageElement",
"SVGFEMergeElement",
"SVGFEMergeNodeElement",
"SVGFEMorphologyElement",
"SVGFEOffsetElement",
"SVGFEPointLightElement",
"SVGFESpecularLightingElement",
"SVGFESpotLightElement",
"SVGFETileElement",
"SVGFETurbulenceElement",
"SVGFilterElement",
"SVGFontElement",
"SVGFontFaceElement",
"SVGFontFaceFormatElement",
"SVGFontFaceNameElement",
"SVGFontFaceSrcElement",
"SVGFontFaceUriElement",
"SVGForeignObjectElement",
"SVGGElement",
"SVGGeometryElement",
"SVGGlyphElement",
"SVGGlyphRefElement",
"SVGGradientElement",
"SVGGraphicsElement",
"SVGHKernElement",
"SVGImageElement",
"SVGLength",
"SVGLengthList",
"SVGLineElement",
"SVGLinearGradientElement",
"SVGMPathElement",
"SVGMarkerElement",
"SVGMaskElement",
"SVGMatrix",
"SVGMetadataElement",
"SVGMissingGlyphElement",
"SVGNumber",
"SVGNumberList",
"SVGPaint",
"SVGPathElement",
"SVGPathSeg",
"SVGPathSegArcAbs",
"SVGPathSegArcRel",
"SVGPathSegClosePath",
"SVGPathSegCurvetoCubicAbs",
"SVGPathSegCurvetoCubicRel",
"SVGPathSegCurvetoCubicSmoothAbs",
"SVGPathSegCurvetoCubicSmoothRel",
"SVGPathSegCurvetoQuadraticAbs",
"SVGPathSegCurvetoQuadraticRel",
"SVGPathSegCurvetoQuadraticSmoothAbs",
"SVGPathSegCurvetoQuadraticSmoothRel",
"SVGPathSegLinetoAbs",
"SVGPathSegLinetoHorizontalAbs",
"SVGPathSegLinetoHorizontalRel",
"SVGPathSegLinetoRel",
"SVGPathSegLinetoVerticalAbs",
"SVGPathSegLinetoVerticalRel",
"SVGPathSegList",
"SVGPathSegMovetoAbs",
"SVGPathSegMovetoRel",
"SVGPatternElement",
"SVGPoint",
"SVGPointList",
"SVGPolygonElement",
"SVGPolylineElement",
"SVGPreserveAspectRatio",
"SVGRadialGradientElement",
"SVGRect",
"SVGRectElement",
"SVGRenderingIntent",
"SVGSVGElement",
"SVGScriptElement",
"SVGSetElement",
"SVGStopElement",
"SVGStringList",
"SVGStyleElement",
"SVGSwitchElement",
"SVGSymbolElement",
"SVGTRefElement",
"SVGTSpanElement",
"SVGTextContentElement",
"SVGTextElement",
"SVGTextPathElement",
"SVGTextPositioningElement",
"SVGTitleElement",
"SVGTransform",
"SVGTransformList",
"SVGUnitTypes",
"SVGUseElement",
"SVGVKernElement",
"SVGViewElement",
"SVGViewSpec",
"SVGZoomAndPan",
"SVGZoomEvent",
"SVG_ANGLETYPE_DEG",
"SVG_ANGLETYPE_GRAD",
"SVG_ANGLETYPE_RAD",
"SVG_ANGLETYPE_UNKNOWN",
"SVG_ANGLETYPE_UNSPECIFIED",
"SVG_CHANNEL_A",
"SVG_CHANNEL_B",
"SVG_CHANNEL_G",
"SVG_CHANNEL_R",
"SVG_CHANNEL_UNKNOWN",
"SVG_COLORTYPE_CURRENTCOLOR",
"SVG_COLORTYPE_RGBCOLOR",
"SVG_COLORTYPE_RGBCOLOR_ICCCOLOR",
"SVG_COLORTYPE_UNKNOWN",
"SVG_EDGEMODE_DUPLICATE",
"SVG_EDGEMODE_NONE",
"SVG_EDGEMODE_UNKNOWN",
"SVG_EDGEMODE_WRAP",
"SVG_FEBLEND_MODE_COLOR",
"SVG_FEBLEND_MODE_COLOR_BURN",
"SVG_FEBLEND_MODE_COLOR_DODGE",
"SVG_FEBLEND_MODE_DARKEN",
"SVG_FEBLEND_MODE_DIFFERENCE",
"SVG_FEBLEND_MODE_EXCLUSION",
"SVG_FEBLEND_MODE_HARD_LIGHT",
"SVG_FEBLEND_MODE_HUE",
"SVG_FEBLEND_MODE_LIGHTEN",
"SVG_FEBLEND_MODE_LUMINOSITY",
"SVG_FEBLEND_MODE_MULTIPLY",
"SVG_FEBLEND_MODE_NORMAL",
"SVG_FEBLEND_MODE_OVERLAY",
"SVG_FEBLEND_MODE_SATURATION",
"SVG_FEBLEND_MODE_SCREEN",
"SVG_FEBLEND_MODE_SOFT_LIGHT",
"SVG_FEBLEND_MODE_UNKNOWN",
"SVG_FECOLORMATRIX_TYPE_HUEROTATE",
"SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA",
"SVG_FECOLORMATRIX_TYPE_MATRIX",
"SVG_FECOLORMATRIX_TYPE_SATURATE",
"SVG_FECOLORMATRIX_TYPE_UNKNOWN",
"SVG_FECOMPONENTTRANSFER_TYPE_DISCRETE",
"SVG_FECOMPONENTTRANSFER_TYPE_GAMMA",
"SVG_FECOMPONENTTRANSFER_TYPE_IDENTITY",
"SVG_FECOMPONENTTRANSFER_TYPE_LINEAR",
"SVG_FECOMPONENTTRANSFER_TYPE_TABLE",
"SVG_FECOMPONENTTRANSFER_TYPE_UNKNOWN",
"SVG_FECOMPOSITE_OPERATOR_ARITHMETIC",
"SVG_FECOMPOSITE_OPERATOR_ATOP",
"SVG_FECOMPOSITE_OPERATOR_IN",
"SVG_FECOMPOSITE_OPERATOR_OUT",
"SVG_FECOMPOSITE_OPERATOR_OVER",
"SVG_FECOMPOSITE_OPERATOR_UNKNOWN",
"SVG_FECOMPOSITE_OPERATOR_XOR",
"SVG_INVALID_VALUE_ERR",
"SVG_LENGTHTYPE_CM",
"SVG_LENGTHTYPE_EMS",
"SVG_LENGTHTYPE_EXS",
"SVG_LENGTHTYPE_IN",
"SVG_LENGTHTYPE_MM",
"SVG_LENGTHTYPE_NUMBER",
"SVG_LENGTHTYPE_PC",
"SVG_LENGTHTYPE_PERCENTAGE",
"SVG_LENGTHTYPE_PT",
"SVG_LENGTHTYPE_PX",
"SVG_LENGTHTYPE_UNKNOWN",
"SVG_MARKERUNITS_STROKEWIDTH",
"SVG_MARKERUNITS_UNKNOWN",
"SVG_MARKERUNITS_USERSPACEONUSE",
"SVG_MARKER_ORIENT_ANGLE",
"SVG_MARKER_ORIENT_AUTO",
"SVG_MARKER_ORIENT_UNKNOWN",
"SVG_MASKTYPE_ALPHA",
"SVG_MASKTYPE_LUMINANCE",
"SVG_MATRIX_NOT_INVERTABLE",
"SVG_MEETORSLICE_MEET",
"SVG_MEETORSLICE_SLICE",
"SVG_MEETORSLICE_UNKNOWN",
"SVG_MORPHOLOGY_OPERATOR_DILATE",
"SVG_MORPHOLOGY_OPERATOR_ERODE",
"SVG_MORPHOLOGY_OPERATOR_UNKNOWN",
"SVG_PAINTTYPE_CURRENTCOLOR",
"SVG_PAINTTYPE_NONE",
"SVG_PAINTTYPE_RGBCOLOR",
"SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR",
"SVG_PAINTTYPE_UNKNOWN",
"SVG_PAINTTYPE_URI",
"SVG_PAINTTYPE_URI_CURRENTCOLOR",
"SVG_PAINTTYPE_URI_NONE",
"SVG_PAINTTYPE_URI_RGBCOLOR",
"SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR",
"SVG_PRESERVEASPECTRATIO_NONE",
"SVG_PRESERVEASPECTRATIO_UNKNOWN",
"SVG_PRESERVEASPECTRATIO_XMAXYMAX",
"SVG_PRESERVEASPECTRATIO_XMAXYMID",
"SVG_PRESERVEASPECTRATIO_XMAXYMIN",
"SVG_PRESERVEASPECTRATIO_XMIDYMAX",
"SVG_PRESERVEASPECTRATIO_XMIDYMID",
"SVG_PRESERVEASPECTRATIO_XMIDYMIN",
"SVG_PRESERVEASPECTRATIO_XMINYMAX",
"SVG_PRESERVEASPECTRATIO_XMINYMID",
"SVG_PRESERVEASPECTRATIO_XMINYMIN",
"SVG_SPREADMETHOD_PAD",
"SVG_SPREADMETHOD_REFLECT",
"SVG_SPREADMETHOD_REPEAT",
"SVG_SPREADMETHOD_UNKNOWN",
"SVG_STITCHTYPE_NOSTITCH",
"SVG_STITCHTYPE_STITCH",
"SVG_STITCHTYPE_UNKNOWN",
"SVG_TRANSFORM_MATRIX",
"SVG_TRANSFORM_ROTATE",
"SVG_TRANSFORM_SCALE",
"SVG_TRANSFORM_SKEWX",
"SVG_TRANSFORM_SKEWY",
"SVG_TRANSFORM_TRANSLATE",
"SVG_TRANSFORM_UNKNOWN",
"SVG_TURBULENCE_TYPE_FRACTALNOISE",
"SVG_TURBULENCE_TYPE_TURBULENCE",
"SVG_TURBULENCE_TYPE_UNKNOWN",
"SVG_UNIT_TYPE_OBJECTBOUNDINGBOX",
"SVG_UNIT_TYPE_UNKNOWN",
"SVG_UNIT_TYPE_USERSPACEONUSE",
"SVG_WRONG_TYPE_ERR",
"SVG_ZOOMANDPAN_DISABLE",
"SVG_ZOOMANDPAN_MAGNIFY",
"SVG_ZOOMANDPAN_UNKNOWN",
"SYNC_CONDITION",
"SYNC_FENCE",
"SYNC_FLAGS",
"SYNC_FLUSH_COMMANDS_BIT",
"SYNC_GPU_COMMANDS_COMPLETE",
"SYNC_STATUS",
"SYNTAX_ERR",
"SavedPages",
"Screen",
"ScreenOrientation",
"Script",
"ScriptProcessorNode",
"ScrollAreaEvent",
"SecurityPolicyViolationEvent",
"Selection",
"Sensor",
"SensorErrorEvent",
"ServiceWorker",
"ServiceWorkerContainer",
"ServiceWorkerRegistration",
"SessionDescription",
"Set",
"ShadowRoot",
"SharedArrayBuffer",
"SharedWorker",
"SimpleGestureEvent",
"SourceBuffer",
"SourceBufferList",
"SpeechSynthesis",
"SpeechSynthesisErrorEvent",
"SpeechSynthesisEvent",
"SpeechSynthesisUtterance",
"SpeechSynthesisVoice",
"StaticRange",
"StereoPannerNode",
"StopIteration",
"Storage",
"StorageEvent",
"StorageManager",
"String",
"StructType",
"StylePropertyMap",
"StylePropertyMapReadOnly",
"StyleSheet",
"StyleSheetList",
"SubmitEvent",
"SubtleCrypto",
"Symbol",
"SyncManager",
"SyntaxError",
"TEMPORARY",
"TEXTPATH_METHODTYPE_ALIGN",
"TEXTPATH_METHODTYPE_STRETCH",
"TEXTPATH_METHODTYPE_UNKNOWN",
"TEXTPATH_SPACINGTYPE_AUTO",
"TEXTPATH_SPACINGTYPE_EXACT",
"TEXTPATH_SPACINGTYPE_UNKNOWN",
"TEXTURE",
"TEXTURE0",
"TEXTURE1",
"TEXTURE10",
"TEXTURE11",
"TEXTURE12",
"TEXTURE13",
"TEXTURE14",
"TEXTURE15",
"TEXTURE16",
"TEXTURE17",
"TEXTURE18",
"TEXTURE19",
"TEXTURE2",
"TEXTURE20",
"TEXTURE21",
"TEXTURE22",
"TEXTURE23",
"TEXTURE24",
"TEXTURE25",
"TEXTURE26",
"TEXTURE27",
"TEXTURE28",
"TEXTURE29",
"TEXTURE3",
"TEXTURE30",
"TEXTURE31",
"TEXTURE4",
"TEXTURE5",
"TEXTURE6",
"TEXTURE7",
"TEXTURE8",
"TEXTURE9",
"TEXTURE_2D",
"TEXTURE_2D_ARRAY",
"TEXTURE_3D",
"TEXTURE_BASE_LEVEL",
"TEXTURE_BINDING_2D",
"TEXTURE_BINDING_2D_ARRAY",
"TEXTURE_BINDING_3D",
"TEXTURE_BINDING_CUBE_MAP",
"TEXTURE_COMPARE_FUNC",
"TEXTURE_COMPARE_MODE",
"TEXTURE_CUBE_MAP",
"TEXTURE_CUBE_MAP_NEGATIVE_X",
"TEXTURE_CUBE_MAP_NEGATIVE_Y",
"TEXTURE_CUBE_MAP_NEGATIVE_Z",
"TEXTURE_CUBE_MAP_POSITIVE_X",
"TEXTURE_CUBE_MAP_POSITIVE_Y",
"TEXTURE_CUBE_MAP_POSITIVE_Z",
"TEXTURE_IMMUTABLE_FORMAT",
"TEXTURE_IMMUTABLE_LEVELS",
"TEXTURE_MAG_FILTER",
"TEXTURE_MAX_ANISOTROPY_EXT",
"TEXTURE_MAX_LEVEL",
"TEXTURE_MAX_LOD",
"TEXTURE_MIN_FILTER",
"TEXTURE_MIN_LOD",
"TEXTURE_WRAP_R",
"TEXTURE_WRAP_S",
"TEXTURE_WRAP_T",
"TEXT_NODE",
"TIMEOUT",
"TIMEOUT_ERR",
"TIMEOUT_EXPIRED",
"TIMEOUT_IGNORED",
"TOO_LARGE_ERR",
"TRANSACTION_INACTIVE_ERR",
"TRANSFORM_FEEDBACK",
"TRANSFORM_FEEDBACK_ACTIVE",
"TRANSFORM_FEEDBACK_BINDING",
"TRANSFORM_FEEDBACK_BUFFER",
"TRANSFORM_FEEDBACK_BUFFER_BINDING",
"TRANSFORM_FEEDBACK_BUFFER_MODE",
"TRANSFORM_FEEDBACK_BUFFER_SIZE",
"TRANSFORM_FEEDBACK_BUFFER_START",
"TRANSFORM_FEEDBACK_PAUSED",
"TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN",
"TRANSFORM_FEEDBACK_VARYINGS",
"TRIANGLE",
"TRIANGLES",
"TRIANGLE_FAN",
"TRIANGLE_STRIP",
"TYPE_BACK_FORWARD",
"TYPE_ERR",
"TYPE_MISMATCH_ERR",
"TYPE_NAVIGATE",
"TYPE_RELOAD",
"TYPE_RESERVED",
"Table",
"TaskAttributionTiming",
"Text",
"TextDecoder",
"TextDecoderStream",
"TextEncoder",
"TextEncoderStream",
"TextEvent",
"TextMetrics",
"TextTrack",
"TextTrackCue",
"TextTrackCueList",
"TextTrackList",
"TimeEvent",
"TimeRanges",
"Touch",
"TouchEvent",
"TouchList",
"TrackEvent",
"TransformStream",
"TransitionEvent",
"TreeWalker",
"TrustedHTML",
"TrustedScript",
"TrustedScriptURL",
"TrustedTypePolicy",
"TrustedTypePolicyFactory",
"TypeError",
"TypedObject",
"U2F",
"UIEvent",
"UNCACHED",
"UNIFORM_ARRAY_STRIDE",
"UNIFORM_BLOCK_ACTIVE_UNIFORMS",
"UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES",
"UNIFORM_BLOCK_BINDING",
"UNIFORM_BLOCK_DATA_SIZE",
"UNIFORM_BLOCK_INDEX",
"UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER",
"UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER",
"UNIFORM_BUFFER",
"UNIFORM_BUFFER_BINDING",
"UNIFORM_BUFFER_OFFSET_ALIGNMENT",
"UNIFORM_BUFFER_SIZE",
"UNIFORM_BUFFER_START",
"UNIFORM_IS_ROW_MAJOR",
"UNIFORM_MATRIX_STRIDE",
"UNIFORM_OFFSET",
"UNIFORM_SIZE",
"UNIFORM_TYPE",
"UNKNOWN_ERR",
"UNKNOWN_RULE",
"UNMASKED_RENDERER_WEBGL",
"UNMASKED_VENDOR_WEBGL",
"UNORDERED_NODE_ITERATOR_TYPE",
"UNORDERED_NODE_SNAPSHOT_TYPE",
"UNPACK_ALIGNMENT",
"UNPACK_COLORSPACE_CONVERSION_WEBGL",
"UNPACK_FLIP_Y_WEBGL",
"UNPACK_IMAGE_HEIGHT",
"UNPACK_PREMULTIPLY_ALPHA_WEBGL",
"UNPACK_ROW_LENGTH",
"UNPACK_SKIP_IMAGES",
"UNPACK_SKIP_PIXELS",
"UNPACK_SKIP_ROWS",
"UNSCHEDULED_STATE",
"UNSENT",
"UNSIGNALED",
"UNSIGNED_BYTE",
"UNSIGNED_INT",
"UNSIGNED_INT_10F_11F_11F_REV",
"UNSIGNED_INT_24_8",
"UNSIGNED_INT_2_10_10_10_REV",
"UNSIGNED_INT_5_9_9_9_REV",
"UNSIGNED_INT_SAMPLER_2D",
"UNSIGNED_INT_SAMPLER_2D_ARRAY",
"UNSIGNED_INT_SAMPLER_3D",
"UNSIGNED_INT_SAMPLER_CUBE",
"UNSIGNED_INT_VEC2",
"UNSIGNED_INT_VEC3",
"UNSIGNED_INT_VEC4",
"UNSIGNED_NORMALIZED",
"UNSIGNED_SHORT",
"UNSIGNED_SHORT_4_4_4_4",
"UNSIGNED_SHORT_5_5_5_1",
"UNSIGNED_SHORT_5_6_5",
"UNSPECIFIED_EVENT_TYPE_ERR",
"UPDATEREADY",
"URIError",
"URL",
"URLSearchParams",
"URLUnencoded",
"URL_MISMATCH_ERR",
"USB",
"USBAlternateInterface",
"USBConfiguration",
"USBConnectionEvent",
"USBDevice",
"USBEndpoint",
"USBInTransferResult",
"USBInterface",
"USBIsochronousInTransferPacket",
"USBIsochronousInTransferResult",
"USBIsochronousOutTransferPacket",
"USBIsochronousOutTransferResult",
"USBOutTransferResult",
"UTC",
"Uint16Array",
"Uint32Array",
"Uint8Array",
"Uint8ClampedArray",
"UserActivation",
"UserMessageHandler",
"UserMessageHandlersNamespace",
"UserProximityEvent",
"VALIDATE_STATUS",
"VALIDATION_ERR",
"VARIABLES_RULE",
"VENDOR",
"VERSION",
"VERSION_CHANGE",
"VERSION_ERR",
"VERTEX_ARRAY_BINDING",
"VERTEX_ATTRIB_ARRAY_BUFFER_BINDING",
"VERTEX_ATTRIB_ARRAY_DIVISOR",
"VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE",
"VERTEX_ATTRIB_ARRAY_ENABLED",
"VERTEX_ATTRIB_ARRAY_INTEGER",
"VERTEX_ATTRIB_ARRAY_NORMALIZED",
"VERTEX_ATTRIB_ARRAY_POINTER",
"VERTEX_ATTRIB_ARRAY_SIZE",
"VERTEX_ATTRIB_ARRAY_STRIDE",
"VERTEX_ATTRIB_ARRAY_TYPE",
"VERTEX_SHADER",
"VERTICAL",
"VERTICAL_AXIS",
"VER_ERR",
"VIEWPORT",
"VIEWPORT_RULE",
"VRDisplay",
"VRDisplayCapabilities",
"VRDisplayEvent",
"VREyeParameters",
"VRFieldOfView",
"VRFrameData",
"VRPose",
"VRStageParameters",
"VTTCue",
"VTTRegion",
"ValidityState",
"VideoPlaybackQuality",
"VideoStreamTrack",
"VisualViewport",
"WAIT_FAILED",
"WEBKIT_FILTER_RULE",
"WEBKIT_KEYFRAMES_RULE",
"WEBKIT_KEYFRAME_RULE",
"WEBKIT_REGION_RULE",
"WRONG_DOCUMENT_ERR",
"WakeLock",
"WakeLockSentinel",
"WasmAnyRef",
"WaveShaperNode",
"WeakMap",
"WeakRef",
"WeakSet",
"WebAssembly",
"WebGL2RenderingContext",
"WebGLActiveInfo",
"WebGLBuffer",
"WebGLContextEvent",
"WebGLFramebuffer",
"WebGLProgram",
"WebGLQuery",
"WebGLRenderbuffer",
"WebGLRenderingContext",
"WebGLSampler",
"WebGLShader",
"WebGLShaderPrecisionFormat",
"WebGLSync",
"WebGLTexture",
"WebGLTransformFeedback",
"WebGLUniformLocation",
"WebGLVertexArray",
"WebGLVertexArrayObject",
"WebKitAnimationEvent",
"WebKitBlobBuilder",
"WebKitCSSFilterRule",
"WebKitCSSFilterValue",
"WebKitCSSKeyframeRule",
"WebKitCSSKeyframesRule",
"WebKitCSSMatrix",
"WebKitCSSRegionRule",
"WebKitCSSTransformValue",
"WebKitDataCue",
"WebKitGamepad",
"WebKitMediaKeyError",
"WebKitMediaKeyMessageEvent",
"WebKitMediaKeySession",
"WebKitMediaKeys",
"WebKitMediaSource",
"WebKitMutationObserver",
"WebKitNamespace",
"WebKitPlaybackTargetAvailabilityEvent",
"WebKitPoint",
"WebKitShadowRoot",
"WebKitSourceBuffer",
"WebKitSourceBufferList",
"WebKitTransitionEvent",
"WebSocket",
"WebkitAlignContent",
"WebkitAlignItems",
"WebkitAlignSelf",
"WebkitAnimation",
"WebkitAnimationDelay",
"WebkitAnimationDirection",
"WebkitAnimationDuration",
"WebkitAnimationFillMode",
"WebkitAnimationIterationCount",
"WebkitAnimationName",
"WebkitAnimationPlayState",
"WebkitAnimationTimingFunction",
"WebkitAppearance",
"WebkitBackfaceVisibility",
"WebkitBackgroundClip",
"WebkitBackgroundOrigin",
"WebkitBackgroundSize",
"WebkitBorderBottomLeftRadius",
"WebkitBorderBottomRightRadius",
"WebkitBorderImage",
"WebkitBorderRadius",
"WebkitBorderTopLeftRadius",
"WebkitBorderTopRightRadius",
"WebkitBoxAlign",
"WebkitBoxDirection",
"WebkitBoxFlex",
"WebkitBoxOrdinalGroup",
"WebkitBoxOrient",
"WebkitBoxPack",
"WebkitBoxShadow",
"WebkitBoxSizing",
"WebkitFilter",
"WebkitFlex",
"WebkitFlexBasis",
"WebkitFlexDirection",
"WebkitFlexFlow",
"WebkitFlexGrow",
"WebkitFlexShrink",
"WebkitFlexWrap",
"WebkitJustifyContent",
"WebkitLineClamp",
"WebkitMask",
"WebkitMaskClip",
"WebkitMaskComposite",
"WebkitMaskImage",
"WebkitMaskOrigin",
"WebkitMaskPosition",
"WebkitMaskPositionX",
"WebkitMaskPositionY",
"WebkitMaskRepeat",
"WebkitMaskSize",
"WebkitOrder",
"WebkitPerspective",
"WebkitPerspectiveOrigin",
"WebkitTextFillColor",
"WebkitTextSizeAdjust",
"WebkitTextStroke",
"WebkitTextStrokeColor",
"WebkitTextStrokeWidth",
"WebkitTransform",
"WebkitTransformOrigin",
"WebkitTransformStyle",
"WebkitTransition",
"WebkitTransitionDelay",
"WebkitTransitionDuration",
"WebkitTransitionProperty",
"WebkitTransitionTimingFunction",
"WebkitUserSelect",
"WheelEvent",
"Window",
"Worker",
"Worklet",
"WritableStream",
"WritableStreamDefaultWriter",
"XMLDocument",
"XMLHttpRequest",
"XMLHttpRequestEventTarget",
"XMLHttpRequestException",
"XMLHttpRequestProgressEvent",
"XMLHttpRequestUpload",
"XMLSerializer",
"XMLStylesheetProcessingInstruction",
"XPathEvaluator",
"XPathException",
"XPathExpression",
"XPathNSResolver",
"XPathResult",
"XRBoundedReferenceSpace",
"XRDOMOverlayState",
"XRFrame",
"XRHitTestResult",
"XRHitTestSource",
"XRInputSource",
"XRInputSourceArray",
"XRInputSourceEvent",
"XRInputSourcesChangeEvent",
"XRLayer",
"XRPose",
"XRRay",
"XRReferenceSpace",
"XRReferenceSpaceEvent",
"XRRenderState",
"XRRigidTransform",
"XRSession",
"XRSessionEvent",
"XRSpace",
"XRSystem",
"XRTransientInputHitTestResult",
"XRTransientInputHitTestSource",
"XRView",
"XRViewerPose",
"XRViewport",
"XRWebGLLayer",
"XSLTProcessor",
"ZERO",
"_XD0M_",
"_YD0M_",
"__defineGetter__",
"__defineSetter__",
"__lookupGetter__",
"__lookupSetter__",
"__opera",
"__proto__",
"_browserjsran",
"a",
"aLink",
"abbr",
"abort",
"aborted",
"abs",
"absolute",
"acceleration",
"accelerationIncludingGravity",
"accelerator",
"accept",
"acceptCharset",
"acceptNode",
"accessKey",
"accessKeyLabel",
"accuracy",
"acos",
"acosh",
"action",
"actionURL",
"actions",
"activated",
"active",
"activeCues",
"activeElement",
"activeSourceBuffers",
"activeSourceCount",
"activeTexture",
"activeVRDisplays",
"actualBoundingBoxAscent",
"actualBoundingBoxDescent",
"actualBoundingBoxLeft",
"actualBoundingBoxRight",
"add",
"addAll",
"addBehavior",
"addCandidate",
"addColorStop",
"addCue",
"addElement",
"addEventListener",
"addFilter",
"addFromString",
"addFromUri",
"addIceCandidate",
"addImport",
"addListener",
"addModule",
"addNamed",
"addPageRule",
"addPath",
"addPointer",
"addRange",
"addRegion",
"addRule",
"addSearchEngine",
"addSourceBuffer",
"addStream",
"addTextTrack",
"addTrack",
"addTransceiver",
"addWakeLockListener",
"added",
"addedNodes",
"additionalName",
"additiveSymbols",
"addons",
"address",
"addressLine",
"adoptNode",
"adoptedStyleSheets",
"adr",
"advance",
"after",
"album",
"alert",
"algorithm",
"align",
"align-content",
"align-items",
"align-self",
"alignContent",
"alignItems",
"alignSelf",
"alignmentBaseline",
"alinkColor",
"all",
"allSettled",
"allow",
"allowFullscreen",
"allowPaymentRequest",
"allowedDirections",
"allowedFeatures",
"allowedToPlay",
"allowsFeature",
"alpha",
"alt",
"altGraphKey",
"altHtml",
"altKey",
"altLeft",
"alternate",
"alternateSetting",
"alternates",
"altitude",
"altitudeAccuracy",
"amplitude",
"ancestorOrigins",
"anchor",
"anchorNode",
"anchorOffset",
"anchors",
"and",
"angle",
"angularAcceleration",
"angularVelocity",
"animVal",
"animate",
"animatedInstanceRoot",
"animatedNormalizedPathSegList",
"animatedPathSegList",
"animatedPoints",
"animation",
"animation-delay",
"animation-direction",
"animation-duration",
"animation-fill-mode",
"animation-iteration-count",
"animation-name",
"animation-play-state",
"animation-timing-function",
"animationDelay",
"animationDirection",
"animationDuration",
"animationFillMode",
"animationIterationCount",
"animationName",
"animationPlayState",
"animationStartTime",
"animationTimingFunction",
"animationsPaused",
"anniversary",
"antialias",
"anticipatedRemoval",
"any",
"app",
"appCodeName",
"appMinorVersion",
"appName",
"appNotifications",
"appVersion",
"appearance",
"append",
"appendBuffer",
"appendChild",
"appendData",
"appendItem",
"appendMedium",
"appendNamed",
"appendRule",
"appendStream",
"appendWindowEnd",
"appendWindowStart",
"applets",
"applicationCache",
"applicationServerKey",
"apply",
"applyConstraints",
"applyElement",
"arc",
"arcTo",
"archive",
"areas",
"arguments",
"ariaAtomic",
"ariaAutoComplete",
"ariaBusy",
"ariaChecked",
"ariaColCount",
"ariaColIndex",
"ariaColSpan",
"ariaCurrent",
"ariaDescription",
"ariaDisabled",
"ariaExpanded",
"ariaHasPopup",
"ariaHidden",
"ariaKeyShortcuts",
"ariaLabel",
"ariaLevel",
"ariaLive",
"ariaModal",
"ariaMultiLine",
"ariaMultiSelectable",
"ariaOrientation",
"ariaPlaceholder",
"ariaPosInSet",
"ariaPressed",
"ariaReadOnly",
"ariaRelevant",
"ariaRequired",
"ariaRoleDescription",
"ariaRowCount",
"ariaRowIndex",
"ariaRowSpan",
"ariaSelected",
"ariaSetSize",
"ariaSort",
"ariaValueMax",
"ariaValueMin",
"ariaValueNow",
"ariaValueText",
"arrayBuffer",
"artist",
"artwork",
"as",
"asIntN",
"asUintN",
"asin",
"asinh",
"assert",
"assign",
"assignedElements",
"assignedNodes",
"assignedSlot",
"async",
"asyncIterator",
"atEnd",
"atan",
"atan2",
"atanh",
"atob",
"attachEvent",
"attachInternals",
"attachShader",
"attachShadow",
"attachments",
"attack",
"attestationObject",
"attrChange",
"attrName",
"attributeFilter",
"attributeName",
"attributeNamespace",
"attributeOldValue",
"attributeStyleMap",
"attributes",
"attribution",
"audioBitsPerSecond",
"audioTracks",
"audioWorklet",
"authenticatedSignedWrites",
"authenticatorData",
"autoIncrement",
"autobuffer",
"autocapitalize",
"autocomplete",
"autocorrect",
"autofocus",
"automationRate",
"autoplay",
"availHeight",
"availLeft",
"availTop",
"availWidth",
"availability",
"available",
"aversion",
"ax",
"axes",
"axis",
"ay",
"azimuth",
"b",
"back",
"backface-visibility",
"backfaceVisibility",
"background",
"background-attachment",
"background-blend-mode",
"background-clip",
"background-color",
"background-image",
"background-origin",
"background-position",
"background-position-x",
"background-position-y",
"background-repeat",
"background-size",
"backgroundAttachment",
"backgroundBlendMode",
"backgroundClip",
"backgroundColor",
"backgroundFetch",
"backgroundImage",
"backgroundOrigin",
"backgroundPosition",
"backgroundPositionX",
"backgroundPositionY",
"backgroundRepeat",
"backgroundSize",
"badInput",
"badge",
"balance",
"baseFrequencyX",
"baseFrequencyY",
"baseLatency",
"baseLayer",
"baseNode",
"baseOffset",
"baseURI",
"baseVal",
"baselineShift",
"battery",
"bday",
"before",
"beginElement",
"beginElementAt",
"beginPath",
"beginQuery",
"beginTransformFeedback",
"behavior",
"behaviorCookie",
"behaviorPart",
"behaviorUrns",
"beta",
"bezierCurveTo",
"bgColor",
"bgProperties",
"bias",
"big",
"bigint64",
"biguint64",
"binaryType",
"bind",
"bindAttribLocation",
"bindBuffer",
"bindBufferBase",
"bindBufferRange",
"bindFramebuffer",
"bindRenderbuffer",
"bindSampler",
"bindTexture",
"bindTransformFeedback",
"bindVertexArray",
"blendColor",
"blendEquation",
"blendEquationSeparate",
"blendFunc",
"blendFuncSeparate",
"blink",
"blitFramebuffer",
"blob",
"block-size",
"blockDirection",
"blockSize",
"blockedURI",
"blue",
"bluetooth",
"blur",
"body",
"bodyUsed",
"bold",
"bookmarks",
"booleanValue",
"border",
"border-block",
"border-block-color",
"border-block-end",
"border-block-end-color",
"border-block-end-style",
"border-block-end-width",
"border-block-start",
"border-block-start-color",
"border-block-start-style",
"border-block-start-width",
"border-block-style",
"border-block-width",
"border-bottom",
"border-bottom-color",
"border-bottom-left-radius",
"border-bottom-right-radius",
"border-bottom-style",
"border-bottom-width",
"border-collapse",
"border-color",
"border-end-end-radius",
"border-end-start-radius",
"border-image",
"border-image-outset",
"border-image-repeat",
"border-image-slice",
"border-image-source",
"border-image-width",
"border-inline",
"border-inline-color",
"border-inline-end",
"border-inline-end-color",
"border-inline-end-style",
"border-inline-end-width",
"border-inline-start",
"border-inline-start-color",
"border-inline-start-style",
"border-inline-start-width",
"border-inline-style",
"border-inline-width",
"border-left",
"border-left-color",
"border-left-style",
"border-left-width",
"border-radius",
"border-right",
"border-right-color",
"border-right-style",
"border-right-width",
"border-spacing",
"border-start-end-radius",
"border-start-start-radius",
"border-style",
"border-top",
"border-top-color",
"border-top-left-radius",
"border-top-right-radius",
"border-top-style",
"border-top-width",
"border-width",
"borderBlock",
"borderBlockColor",
"borderBlockEnd",
"borderBlockEndColor",
"borderBlockEndStyle",
"borderBlockEndWidth",
"borderBlockStart",
"borderBlockStartColor",
"borderBlockStartStyle",
"borderBlockStartWidth",
"borderBlockStyle",
"borderBlockWidth",
"borderBottom",
"borderBottomColor",
"borderBottomLeftRadius",
"borderBottomRightRadius",
"borderBottomStyle",
"borderBottomWidth",
"borderBoxSize",
"borderCollapse",
"borderColor",
"borderColorDark",
"borderColorLight",
"borderEndEndRadius",
"borderEndStartRadius",
"borderImage",
"borderImageOutset",
"borderImageRepeat",
"borderImageSlice",
"borderImageSource",
"borderImageWidth",
"borderInline",
"borderInlineColor",
"borderInlineEnd",
"borderInlineEndColor",
"borderInlineEndStyle",
"borderInlineEndWidth",
"borderInlineStart",
"borderInlineStartColor",
"borderInlineStartStyle",
"borderInlineStartWidth",
"borderInlineStyle",
"borderInlineWidth",
"borderLeft",
"borderLeftColor",
"borderLeftStyle",
"borderLeftWidth",
"borderRadius",
"borderRight",
"borderRightColor",
"borderRightStyle",
"borderRightWidth",
"borderSpacing",
"borderStartEndRadius",
"borderStartStartRadius",
"borderStyle",
"borderTop",
"borderTopColor",
"borderTopLeftRadius",
"borderTopRightRadius",
"borderTopStyle",
"borderTopWidth",
"borderWidth",
"bottom",
"bottomMargin",
"bound",
"boundElements",
"boundingClientRect",
"boundingHeight",
"boundingLeft",
"boundingTop",
"boundingWidth",
"bounds",
"boundsGeometry",
"box-decoration-break",
"box-shadow",
"box-sizing",
"boxDecorationBreak",
"boxShadow",
"boxSizing",
"break-after",
"break-before",
"break-inside",
"breakAfter",
"breakBefore",
"breakInside",
"broadcast",
"browserLanguage",
"btoa",
"bubbles",
"buffer",
"bufferData",
"bufferDepth",
"bufferSize",
"bufferSubData",
"buffered",
"bufferedAmount",
"bufferedAmountLowThreshold",
"buildID",
"buildNumber",
"button",
"buttonID",
"buttons",
"byteLength",
"byteOffset",
"bytesWritten",
"c",
"cache",
"caches",
"call",
"caller",
"canBeFormatted",
"canBeMounted",
"canBeShared",
"canHaveChildren",
"canHaveHTML",
"canInsertDTMF",
"canMakePayment",
"canPlayType",
"canPresent",
"canTrickleIceCandidates",
"cancel",
"cancelAndHoldAtTime",
"cancelAnimationFrame",
"cancelBubble",
"cancelIdleCallback",
"cancelScheduledValues",
"cancelVideoFrameCallback",
"cancelWatchAvailability",
"cancelable",
"candidate",
"canonicalUUID",
"canvas",
"capabilities",
"caption",
"caption-side",
"captionSide",
"capture",
"captureEvents",
"captureStackTrace",
"captureStream",
"caret-color",
"caretBidiLevel",
"caretColor",
"caretPositionFromPoint",
"caretRangeFromPoint",
"cast",
"catch",
"category",
"cbrt",
"cd",
"ceil",
"cellIndex",
"cellPadding",
"cellSpacing",
"cells",
"ch",
"chOff",
"chain",
"challenge",
"changeType",
"changedTouches",
"channel",
"channelCount",
"channelCountMode",
"channelInterpretation",
"char",
"charAt",
"charCode",
"charCodeAt",
"charIndex",
"charLength",
"characterData",
"characterDataOldValue",
"characterSet",
"characteristic",
"charging",
"chargingTime",
"charset",
"check",
"checkEnclosure",
"checkFramebufferStatus",
"checkIntersection",
"checkValidity",
"checked",
"childElementCount",
"childList",
"childNodes",
"children",
"chrome",
"ciphertext",
"cite",
"city",
"claimInterface",
"claimed",
"classList",
"className",
"classid",
"clear",
"clearAppBadge",
"clearAttributes",
"clearBufferfi",
"clearBufferfv",
"clearBufferiv",
"clearBufferuiv",
"clearColor",
"clearData",
"clearDepth",
"clearHalt",
"clearImmediate",
"clearInterval",
"clearLiveSeekableRange",
"clearMarks",
"clearMaxGCPauseAccumulator",
"clearMeasures",
"clearParameters",
"clearRect",
"clearResourceTimings",
"clearShadow",
"clearStencil",
"clearTimeout",
"clearWatch",
"click",
"clickCount",
"clientDataJSON",
"clientHeight",
"clientInformation",
"clientLeft",
"clientRect",
"clientRects",
"clientTop",
"clientWaitSync",
"clientWidth",
"clientX",
"clientY",
"clip",
"clip-path",
"clip-rule",
"clipBottom",
"clipLeft",
"clipPath",
"clipPathUnits",
"clipRight",
"clipRule",
"clipTop",
"clipboard",
"clipboardData",
"clone",
"cloneContents",
"cloneNode",
"cloneRange",
"close",
"closePath",
"closed",
"closest",
"clz",
"clz32",
"cm",
"cmp",
"code",
"codeBase",
"codePointAt",
"codeType",
"colSpan",
"collapse",
"collapseToEnd",
"collapseToStart",
"collapsed",
"collect",
"colno",
"color",
"color-adjust",
"color-interpolation",
"color-interpolation-filters",
"colorAdjust",
"colorDepth",
"colorInterpolation",
"colorInterpolationFilters",
"colorMask",
"colorType",
"cols",
"column-count",
"column-fill",
"column-gap",
"column-rule",
"column-rule-color",
"column-rule-style",
"column-rule-width",
"column-span",
"column-width",
"columnCount",
"columnFill",
"columnGap",
"columnNumber",
"columnRule",
"columnRuleColor",
"columnRuleStyle",
"columnRuleWidth",
"columnSpan",
"columnWidth",
"columns",
"command",
"commit",
"commitPreferences",
"commitStyles",
"commonAncestorContainer",
"compact",
"compareBoundaryPoints",
"compareDocumentPosition",
"compareEndPoints",
"compareExchange",
"compareNode",
"comparePoint",
"compatMode",
"compatible",
"compile",
"compileShader",
"compileStreaming",
"complete",
"component",
"componentFromPoint",
"composed",
"composedPath",
"composite",
"compositionEndOffset",
"compositionStartOffset",
"compressedTexImage2D",
"compressedTexImage3D",
"compressedTexSubImage2D",
"compressedTexSubImage3D",
"computedStyleMap",
"concat",
"conditionText",
"coneInnerAngle",
"coneOuterAngle",
"coneOuterGain",
"configuration",
"configurationName",
"configurationValue",
"configurations",
"confirm",
"confirmComposition",
"confirmSiteSpecificTrackingException",
"confirmWebWideTrackingException",
"connect",
"connectEnd",
"connectShark",
"connectStart",
"connected",
"connection",
"connectionList",
"connectionSpeed",
"connectionState",
"connections",
"console",
"consolidate",
"constraint",
"constrictionActive",
"construct",
"constructor",
"contactID",
"contain",
"containerId",
"containerName",
"containerSrc",
"containerType",
"contains",
"containsNode",
"content",
"contentBoxSize",
"contentDocument",
"contentEditable",
"contentHint",
"contentOverflow",
"contentRect",
"contentScriptType",
"contentStyleType",
"contentType",
"contentWindow",
"context",
"contextMenu",
"contextmenu",
"continue",
"continuePrimaryKey",
"continuous",
"control",
"controlTransferIn",
"controlTransferOut",
"controller",
"controls",
"controlsList",
"convertPointFromNode",
"convertQuadFromNode",
"convertRectFromNode",
"convertToBlob",
"convertToSpecifiedUnits",
"cookie",
"cookieEnabled",
"coords",
"copyBufferSubData",
"copyFromChannel",
"copyTexImage2D",
"copyTexSubImage2D",
"copyTexSubImage3D",
"copyToChannel",
"copyWithin",
"correspondingElement",
"correspondingUseElement",
"corruptedVideoFrames",
"cos",
"cosh",
"count",
"countReset",
"counter-increment",
"counter-reset",
"counter-set",
"counterIncrement",
"counterReset",
"counterSet",
"country",
"cpuClass",
"cpuSleepAllowed",
"create",
"createAnalyser",
"createAnswer",
"createAttribute",
"createAttributeNS",
"createBiquadFilter",
"createBuffer",
"createBufferSource",
"createCDATASection",
"createCSSStyleSheet",
"createCaption",
"createChannelMerger",
"createChannelSplitter",
"createComment",
"createConstantSource",
"createContextualFragment",
"createControlRange",
"createConvolver",
"createDTMFSender",
"createDataChannel",
"createDelay",
"createDelayNode",
"createDocument",
"createDocumentFragment",
"createDocumentType",
"createDynamicsCompressor",
"createElement",
"createElementNS",
"createEntityReference",
"createEvent",
"createEventObject",
"createExpression",
"createFramebuffer",
"createFunction",
"createGain",
"createGainNode",
"createHTML",
"createHTMLDocument",
"createIIRFilter",
"createImageBitmap",
"createImageData",
"createIndex",
"createJavaScriptNode",
"createLinearGradient",
"createMediaElementSource",
"createMediaKeys",
"createMediaStreamDestination",
"createMediaStreamSource",
"createMediaStreamTrackSource",
"createMutableFile",
"createNSResolver",
"createNodeIterator",
"createNotification",
"createObjectStore",
"createObjectURL",
"createOffer",
"createOscillator",
"createPanner",
"createPattern",
"createPeriodicWave",
"createPolicy",
"createPopup",
"createProcessingInstruction",
"createProgram",
"createQuery",
"createRadialGradient",
"createRange",
"createRangeCollection",
"createReader",
"createRenderbuffer",
"createSVGAngle",
"createSVGLength",
"createSVGMatrix",
"createSVGNumber",
"createSVGPathSegArcAbs",
"createSVGPathSegArcRel",
"createSVGPathSegClosePath",
"createSVGPathSegCurvetoCubicAbs",
"createSVGPathSegCurvetoCubicRel",
"createSVGPathSegCurvetoCubicSmoothAbs",
"createSVGPathSegCurvetoCubicSmoothRel",
"createSVGPathSegCurvetoQuadraticAbs",
"createSVGPathSegCurvetoQuadraticRel",
"createSVGPathSegCurvetoQuadraticSmoothAbs",
"createSVGPathSegCurvetoQuadraticSmoothRel",
"createSVGPathSegLinetoAbs",
"createSVGPathSegLinetoHorizontalAbs",
"createSVGPathSegLinetoHorizontalRel",
"createSVGPathSegLinetoRel",
"createSVGPathSegLinetoVerticalAbs",
"createSVGPathSegLinetoVerticalRel",
"createSVGPathSegMovetoAbs",
"createSVGPathSegMovetoRel",
"createSVGPoint",
"createSVGRect",
"createSVGTransform",
"createSVGTransformFromMatrix",
"createSampler",
"createScript",
"createScriptProcessor",
"createScriptURL",
"createSession",
"createShader",
"createShadowRoot",
"createStereoPanner",
"createStyleSheet",
"createTBody",
"createTFoot",
"createTHead",
"createTextNode",
"createTextRange",
"createTexture",
"createTouch",
"createTouchList",
"createTransformFeedback",
"createTreeWalker",
"createVertexArray",
"createWaveShaper",
"creationTime",
"credentials",
"crossOrigin",
"crossOriginIsolated",
"crypto",
"csi",
"csp",
"cssFloat",
"cssRules",
"cssText",
"cssValueType",
"ctrlKey",
"ctrlLeft",
"cues",
"cullFace",
"currentDirection",
"currentLocalDescription",
"currentNode",
"currentPage",
"currentRect",
"currentRemoteDescription",
"currentScale",
"currentScript",
"currentSrc",
"currentState",
"currentStyle",
"currentTarget",
"currentTime",
"currentTranslate",
"currentView",
"cursor",
"curve",
"customElements",
"customError",
"cx",
"cy",
"d",
"data",
"dataFld",
"dataFormatAs",
"dataLoss",
"dataLossMessage",
"dataPageSize",
"dataSrc",
"dataTransfer",
"database",
"databases",
"dataset",
"dateTime",
"db",
"debug",
"debuggerEnabled",
"declare",
"decode",
"decodeAudioData",
"decodeURI",
"decodeURIComponent",
"decodedBodySize",
"decoding",
"decodingInfo",
"decrypt",
"default",
"defaultCharset",
"defaultChecked",
"defaultMuted",
"defaultPlaybackRate",
"defaultPolicy",
"defaultPrevented",
"defaultRequest",
"defaultSelected",
"defaultStatus",
"defaultURL",
"defaultValue",
"defaultView",
"defaultstatus",
"defer",
"define",
"defineMagicFunction",
"defineMagicVariable",
"defineProperties",
"defineProperty",
"deg",
"delay",
"delayTime",
"delegatesFocus",
"delete",
"deleteBuffer",
"deleteCaption",
"deleteCell",
"deleteContents",
"deleteData",
"deleteDatabase",
"deleteFramebuffer",
"deleteFromDocument",
"deleteIndex",
"deleteMedium",
"deleteObjectStore",
"deleteProgram",
"deleteProperty",
"deleteQuery",
"deleteRenderbuffer",
"deleteRow",
"deleteRule",
"deleteSampler",
"deleteShader",
"deleteSync",
"deleteTFoot",
"deleteTHead",
"deleteTexture",
"deleteTransformFeedback",
"deleteVertexArray",
"deliverChangeRecords",
"delivery",
"deliveryInfo",
"deliveryStatus",
"deliveryTimestamp",
"delta",
"deltaMode",
"deltaX",
"deltaY",
"deltaZ",
"dependentLocality",
"depthFar",
"depthFunc",
"depthMask",
"depthNear",
"depthRange",
"deref",
"deriveBits",
"deriveKey",
"description",
"deselectAll",
"designMode",
"desiredSize",
"destination",
"destinationURL",
"detach",
"detachEvent",
"detachShader",
"detail",
"details",
"detect",
"detune",
"device",
"deviceClass",
"deviceId",
"deviceMemory",
"devicePixelContentBoxSize",
"devicePixelRatio",
"deviceProtocol",
"deviceSubclass",
"deviceVersionMajor",
"deviceVersionMinor",
"deviceVersionSubminor",
"deviceXDPI",
"deviceYDPI",
"didTimeout",
"diffuseConstant",
"digest",
"dimensions",
"dir",
"dirName",
"direction",
"dirxml",
"disable",
"disablePictureInPicture",
"disableRemotePlayback",
"disableVertexAttribArray",
"disabled",
"dischargingTime",
"disconnect",
"disconnectShark",
"dispatchEvent",
"display",
"displayId",
"displayName",
"disposition",
"distanceModel",
"div",
"divisor",
"djsapi",
"djsproxy",
"doImport",
"doNotTrack",
"doScroll",
"doctype",
"document",
"documentElement",
"documentMode",
"documentURI",
"dolphin",
"dolphinGameCenter",
"dolphininfo",
"dolphinmeta",
"domComplete",
"domContentLoadedEventEnd",
"domContentLoadedEventStart",
"domInteractive",
"domLoading",
"domOverlayState",
"domain",
"domainLookupEnd",
"domainLookupStart",
"dominant-baseline",
"dominantBaseline",
"done",
"dopplerFactor",
"dotAll",
"downDegrees",
"downlink",
"download",
"downloadTotal",
"downloaded",
"dpcm",
"dpi",
"dppx",
"dragDrop",
"draggable",
"drawArrays",
"drawArraysInstanced",
"drawArraysInstancedANGLE",
"drawBuffers",
"drawCustomFocusRing",
"drawElements",
"drawElementsInstanced",
"drawElementsInstancedANGLE",
"drawFocusIfNeeded",
"drawImage",
"drawImageFromRect",
"drawRangeElements",
"drawSystemFocusRing",
"drawingBufferHeight",
"drawingBufferWidth",
"dropEffect",
"droppedVideoFrames",
"dropzone",
"dtmf",
"dump",
"dumpProfile",
"duplicate",
"durability",
"duration",
"dvname",
"dvnum",
"dx",
"dy",
"dynsrc",
"e",
"edgeMode",
"effect",
"effectAllowed",
"effectiveDirective",
"effectiveType",
"elapsedTime",
"element",
"elementFromPoint",
"elementTiming",
"elements",
"elementsFromPoint",
"elevation",
"ellipse",
"em",
"email",
"embeds",
"emma",
"empty",
"empty-cells",
"emptyCells",
"emptyHTML",
"emptyScript",
"emulatedPosition",
"enable",
"enableBackground",
"enableDelegations",
"enableStyleSheetsForSet",
"enableVertexAttribArray",
"enabled",
"enabledPlugin",
"encode",
"encodeInto",
"encodeURI",
"encodeURIComponent",
"encodedBodySize",
"encoding",
"encodingInfo",
"encrypt",
"enctype",
"end",
"endContainer",
"endElement",
"endElementAt",
"endOfStream",
"endOffset",
"endQuery",
"endTime",
"endTransformFeedback",
"ended",
"endpoint",
"endpointNumber",
"endpoints",
"endsWith",
"enterKeyHint",
"entities",
"entries",
"entryType",
"enumerate",
"enumerateDevices",
"enumerateEditable",
"environmentBlendMode",
"equals",
"error",
"errorCode",
"errorDetail",
"errorText",
"escape",
"estimate",
"eval",
"evaluate",
"event",
"eventPhase",
"every",
"ex",
"exception",
"exchange",
"exec",
"execCommand",
"execCommandShowHelp",
"execScript",
"exitFullscreen",
"exitPictureInPicture",
"exitPointerLock",
"exitPresent",
"exp",
"expand",
"expandEntityReferences",
"expando",
"expansion",
"expiration",
"expirationTime",
"expires",
"expiryDate",
"explicitOriginalTarget",
"expm1",
"exponent",
"exponentialRampToValueAtTime",
"exportKey",
"exports",
"extend",
"extensions",
"extentNode",
"extentOffset",
"external",
"externalResourcesRequired",
"extractContents",
"extractable",
"eye",
"f",
"face",
"factoryReset",
"failureReason",
"fallback",
"family",
"familyName",
"farthestViewportElement",
"fastSeek",
"fatal",
"featureId",
"featurePolicy",
"featureSettings",
"features",
"fenceSync",
"fetch",
"fetchStart",
"fftSize",
"fgColor",
"fieldOfView",
"file",
"fileCreatedDate",
"fileHandle",
"fileModifiedDate",
"fileName",
"fileSize",
"fileUpdatedDate",
"filename",
"files",
"filesystem",
"fill",
"fill-opacity",
"fill-rule",
"fillLightMode",
"fillOpacity",
"fillRect",
"fillRule",
"fillStyle",
"fillText",
"filter",
"filterResX",
"filterResY",
"filterUnits",
"filters",
"finally",
"find",
"findIndex",
"findRule",
"findText",
"finish",
"finished",
"fireEvent",
"firesTouchEvents",
"firstChild",
"firstElementChild",
"firstPage",
"fixed",
"flags",
"flat",
"flatMap",
"flex",
"flex-basis",
"flex-direction",
"flex-flow",
"flex-grow",
"flex-shrink",
"flex-wrap",
"flexBasis",
"flexDirection",
"flexFlow",
"flexGrow",
"flexShrink",
"flexWrap",
"flipX",
"flipY",
"float",
"float32",
"float64",
"flood-color",
"flood-opacity",
"floodColor",
"floodOpacity",
"floor",
"flush",
"focus",
"focusNode",
"focusOffset",
"font",
"font-family",
"font-feature-settings",
"font-kerning",
"font-language-override",
"font-optical-sizing",
"font-size",
"font-size-adjust",
"font-stretch",
"font-style",
"font-synthesis",
"font-variant",
"font-variant-alternates",
"font-variant-caps",
"font-variant-east-asian",
"font-variant-ligatures",
"font-variant-numeric",
"font-variant-position",
"font-variation-settings",
"font-weight",
"fontFamily",
"fontFeatureSettings",
"fontKerning",
"fontLanguageOverride",
"fontOpticalSizing",
"fontSize",
"fontSizeAdjust",
"fontSmoothingEnabled",
"fontStretch",
"fontStyle",
"fontSynthesis",
"fontVariant",
"fontVariantAlternates",
"fontVariantCaps",
"fontVariantEastAsian",
"fontVariantLigatures",
"fontVariantNumeric",
"fontVariantPosition",
"fontVariationSettings",
"fontWeight",
"fontcolor",
"fontfaces",
"fonts",
"fontsize",
"for",
"forEach",
"force",
"forceRedraw",
"form",
"formAction",
"formData",
"formEnctype",
"formMethod",
"formNoValidate",
"formTarget",
"format",
"formatToParts",
"forms",
"forward",
"forwardX",
"forwardY",
"forwardZ",
"foundation",
"fr",
"fragmentDirective",
"frame",
"frameBorder",
"frameElement",
"frameSpacing",
"framebuffer",
"framebufferHeight",
"framebufferRenderbuffer",
"framebufferTexture2D",
"framebufferTextureLayer",
"framebufferWidth",
"frames",
"freeSpace",
"freeze",
"frequency",
"frequencyBinCount",
"from",
"fromCharCode",
"fromCodePoint",
"fromElement",
"fromEntries",
"fromFloat32Array",
"fromFloat64Array",
"fromMatrix",
"fromPoint",
"fromQuad",
"fromRect",
"frontFace",
"fround",
"fullPath",
"fullScreen",
"fullscreen",
"fullscreenElement",
"fullscreenEnabled",
"fx",
"fy",
"gain",
"gamepad",
"gamma",
"gap",
"gatheringState",
"gatt",
"genderIdentity",
"generateCertificate",
"generateKey",
"generateMipmap",
"generateRequest",
"geolocation",
"gestureObject",
"get",
"getActiveAttrib",
"getActiveUniform",
"getActiveUniformBlockName",
"getActiveUniformBlockParameter",
"getActiveUniforms",
"getAdjacentText",
"getAll",
"getAllKeys",
"getAllResponseHeaders",
"getAllowlistForFeature",
"getAnimations",
"getAsFile",
"getAsString",
"getAttachedShaders",
"getAttribLocation",
"getAttribute",
"getAttributeNS",
"getAttributeNames",
"getAttributeNode",
"getAttributeNodeNS",
"getAttributeType",
"getAudioTracks",
"getAvailability",
"getBBox",
"getBattery",
"getBigInt64",
"getBigUint64",
"getBlob",
"getBookmark",
"getBoundingClientRect",
"getBounds",
"getBoxQuads",
"getBufferParameter",
"getBufferSubData",
"getByteFrequencyData",
"getByteTimeDomainData",
"getCSSCanvasContext",
"getCTM",
"getCandidateWindowClientRect",
"getCanonicalLocales",
"getCapabilities",
"getChannelData",
"getCharNumAtPosition",
"getCharacteristic",
"getCharacteristics",
"getClientExtensionResults",
"getClientRect",
"getClientRects",
"getCoalescedEvents",
"getCompositionAlternatives",
"getComputedStyle",
"getComputedTextLength",
"getComputedTiming",
"getConfiguration",
"getConstraints",
"getContext",
"getContextAttributes",
"getContributingSources",
"getCounterValue",
"getCueAsHTML",
"getCueById",
"getCurrentPosition",
"getCurrentTime",
"getData",
"getDatabaseNames",
"getDate",
"getDay",
"getDefaultComputedStyle",
"getDescriptor",
"getDescriptors",
"getDestinationInsertionPoints",
"getDevices",
"getDirectory",
"getDisplayMedia",
"getDistributedNodes",
"getEditable",
"getElementById",
"getElementsByClassName",
"getElementsByName",
"getElementsByTagName",
"getElementsByTagNameNS",
"getEnclosureList",
"getEndPositionOfChar",
"getEntries",
"getEntriesByName",
"getEntriesByType",
"getError",
"getExtension",
"getExtentOfChar",
"getEyeParameters",
"getFeature",
"getFile",
"getFiles",
"getFilesAndDirectories",
"getFingerprints",
"getFloat32",
"getFloat64",
"getFloatFrequencyData",
"getFloatTimeDomainData",
"getFloatValue",
"getFragDataLocation",
"getFrameData",
"getFramebufferAttachmentParameter",
"getFrequencyResponse",
"getFullYear",
"getGamepads",
"getHitTestResults",
"getHitTestResultsForTransientInput",
"getHours",
"getIdentityAssertion",
"getIds",
"getImageData",
"getIndexedParameter",
"getInstalledRelatedApps",
"getInt16",
"getInt32",
"getInt8",
"getInternalformatParameter",
"getIntersectionList",
"getItem",
"getItems",
"getKey",
"getKeyframes",
"getLayers",
"getLayoutMap",
"getLineDash",
"getLocalCandidates",
"getLocalParameters",
"getLocalStreams",
"getMarks",
"getMatchedCSSRules",
"getMaxGCPauseSinceClear",
"getMeasures",
"getMetadata",
"getMilliseconds",
"getMinutes",
"getModifierState",
"getMonth",
"getNamedItem",
"getNamedItemNS",
"getNativeFramebufferScaleFactor",
"getNotifications",
"getNotifier",
"getNumberOfChars",
"getOffsetReferenceSpace",
"getOutputTimestamp",
"getOverrideHistoryNavigationMode",
"getOverrideStyle",
"getOwnPropertyDescriptor",
"getOwnPropertyDescriptors",
"getOwnPropertyNames",
"getOwnPropertySymbols",
"getParameter",
"getParameters",
"getParent",
"getPathSegAtLength",
"getPhotoCapabilities",
"getPhotoSettings",
"getPointAtLength",
"getPose",
"getPredictedEvents",
"getPreference",
"getPreferenceDefault",
"getPresentationAttribute",
"getPreventDefault",
"getPrimaryService",
"getPrimaryServices",
"getProgramInfoLog",
"getProgramParameter",
"getPropertyCSSValue",
"getPropertyPriority",
"getPropertyShorthand",
"getPropertyType",
"getPropertyValue",
"getPrototypeOf",
"getQuery",
"getQueryParameter",
"getRGBColorValue",
"getRandomValues",
"getRangeAt",
"getReader",
"getReceivers",
"getRectValue",
"getRegistration",
"getRegistrations",
"getRemoteCandidates",
"getRemoteCertificates",
"getRemoteParameters",
"getRemoteStreams",
"getRenderbufferParameter",
"getResponseHeader",
"getRoot",
"getRootNode",
"getRotationOfChar",
"getSVGDocument",
"getSamplerParameter",
"getScreenCTM",
"getSeconds",
"getSelectedCandidatePair",
"getSelection",
"getSenders",
"getService",
"getSettings",
"getShaderInfoLog",
"getShaderParameter",
"getShaderPrecisionFormat",
"getShaderSource",
"getSimpleDuration",
"getSiteIcons",
"getSources",
"getSpeculativeParserUrls",
"getStartPositionOfChar",
"getStartTime",
"getState",
"getStats",
"getStatusForPolicy",
"getStorageUpdates",
"getStreamById",
"getStringValue",
"getSubStringLength",
"getSubscription",
"getSupportedConstraints",
"getSupportedExtensions",
"getSupportedFormats",
"getSyncParameter",
"getSynchronizationSources",
"getTags",
"getTargetRanges",
"getTexParameter",
"getTime",
"getTimezoneOffset",
"getTiming",
"getTotalLength",
"getTrackById",
"getTracks",
"getTransceivers",
"getTransform",
"getTransformFeedbackVarying",
"getTransformToElement",
"getTransports",
"getType",
"getTypeMapping",
"getUTCDate",
"getUTCDay",
"getUTCFullYear",
"getUTCHours",
"getUTCMilliseconds",
"getUTCMinutes",
"getUTCMonth",
"getUTCSeconds",
"getUint16",
"getUint32",
"getUint8",
"getUniform",
"getUniformBlockIndex",
"getUniformIndices",
"getUniformLocation",
"getUserMedia",
"getVRDisplays",
"getValues",
"getVarDate",
"getVariableValue",
"getVertexAttrib",
"getVertexAttribOffset",
"getVideoPlaybackQuality",
"getVideoTracks",
"getViewerPose",
"getViewport",
"getVoices",
"getWakeLockState",
"getWriter",
"getYear",
"givenName",
"global",
"globalAlpha",
"globalCompositeOperation",
"globalThis",
"glyphOrientationHorizontal",
"glyphOrientationVertical",
"glyphRef",
"go",
"grabFrame",
"grad",
"gradientTransform",
"gradientUnits",
"grammars",
"green",
"grid",
"grid-area",
"grid-auto-columns",
"grid-auto-flow",
"grid-auto-rows",
"grid-column",
"grid-column-end",
"grid-column-gap",
"grid-column-start",
"grid-gap",
"grid-row",
"grid-row-end",
"grid-row-gap",
"grid-row-start",
"grid-template",
"grid-template-areas",
"grid-template-columns",
"grid-template-rows",
"gridArea",
"gridAutoColumns",
"gridAutoFlow",
"gridAutoRows",
"gridColumn",
"gridColumnEnd",
"gridColumnGap",
"gridColumnStart",
"gridGap",
"gridRow",
"gridRowEnd",
"gridRowGap",
"gridRowStart",
"gridTemplate",
"gridTemplateAreas",
"gridTemplateColumns",
"gridTemplateRows",
"gripSpace",
"group",
"groupCollapsed",
"groupEnd",
"groupId",
"hadRecentInput",
"hand",
"handedness",
"hapticActuators",
"hardwareConcurrency",
"has",
"hasAttribute",
"hasAttributeNS",
"hasAttributes",
"hasBeenActive",
"hasChildNodes",
"hasComposition",
"hasEnrolledInstrument",
"hasExtension",
"hasExternalDisplay",
"hasFeature",
"hasFocus",
"hasInstance",
"hasLayout",
"hasOrientation",
"hasOwnProperty",
"hasPointerCapture",
"hasPosition",
"hasReading",
"hasStorageAccess",
"hash",
"head",
"headers",
"heading",
"height",
"hidden",
"hide",
"hideFocus",
"high",
"highWaterMark",
"hint",
"history",
"honorificPrefix",
"honorificSuffix",
"horizontalOverflow",
"host",
"hostCandidate",
"hostname",
"href",
"hrefTranslate",
"hreflang",
"hspace",
"html5TagCheckInerface",
"htmlFor",
"htmlText",
"httpEquiv",
"httpRequestStatusCode",
"hwTimestamp",
"hyphens",
"hypot",
"iccId",
"iceConnectionState",
"iceGatheringState",
"iceTransport",
"icon",
"iconURL",
"id",
"identifier",
"identity",
"idpLoginUrl",
"ignoreBOM",
"ignoreCase",
"ignoreDepthValues",
"image-orientation",
"image-rendering",
"imageHeight",
"imageOrientation",
"imageRendering",
"imageSizes",
"imageSmoothingEnabled",
"imageSmoothingQuality",
"imageSrcset",
"imageWidth",
"images",
"ime-mode",
"imeMode",
"implementation",
"importKey",
"importNode",
"importStylesheet",
"imports",
"impp",
"imul",
"in",
"in1",
"in2",
"inBandMetadataTrackDispatchType",
"inRange",
"includes",
"incremental",
"indeterminate",
"index",
"indexNames",
"indexOf",
"indexedDB",
"indicate",
"inertiaDestinationX",
"inertiaDestinationY",
"info",
"init",
"initAnimationEvent",
"initBeforeLoadEvent",
"initClipboardEvent",
"initCloseEvent",
"initCommandEvent",
"initCompositionEvent",
"initCustomEvent",
"initData",
"initDataType",
"initDeviceMotionEvent",
"initDeviceOrientationEvent",
"initDragEvent",
"initErrorEvent",
"initEvent",
"initFocusEvent",
"initGestureEvent",
"initHashChangeEvent",
"initKeyEvent",
"initKeyboardEvent",
"initMSManipulationEvent",
"initMessageEvent",
"initMouseEvent",
"initMouseScrollEvent",
"initMouseWheelEvent",
"initMutationEvent",
"initNSMouseEvent",
"initOverflowEvent",
"initPageEvent",
"initPageTransitionEvent",
"initPointerEvent",
"initPopStateEvent",
"initProgressEvent",
"initScrollAreaEvent",
"initSimpleGestureEvent",
"initStorageEvent",
"initTextEvent",
"initTimeEvent",
"initTouchEvent",
"initTransitionEvent",
"initUIEvent",
"initWebKitAnimationEvent",
"initWebKitTransitionEvent",
"initWebKitWheelEvent",
"initWheelEvent",
"initialTime",
"initialize",
"initiatorType",
"inline-size",
"inlineSize",
"inlineVerticalFieldOfView",
"inner",
"innerHTML",
"innerHeight",
"innerText",
"innerWidth",
"input",
"inputBuffer",
"inputEncoding",
"inputMethod",
"inputMode",
"inputSource",
"inputSources",
"inputType",
"inputs",
"insertAdjacentElement",
"insertAdjacentHTML",
"insertAdjacentText",
"insertBefore",
"insertCell",
"insertDTMF",
"insertData",
"insertItemBefore",
"insertNode",
"insertRow",
"insertRule",
"inset",
"inset-block",
"inset-block-end",
"inset-block-start",
"inset-inline",
"inset-inline-end",
"inset-inline-start",
"insetBlock",
"insetBlockEnd",
"insetBlockStart",
"insetInline",
"insetInlineEnd",
"insetInlineStart",
"installing",
"instanceRoot",
"instantiate",
"instantiateStreaming",
"instruments",
"int16",
"int32",
"int8",
"integrity",
"interactionMode",
"intercept",
"interfaceClass",
"interfaceName",
"interfaceNumber",
"interfaceProtocol",
"interfaceSubclass",
"interfaces",
"interimResults",
"internalSubset",
"interpretation",
"intersectionRatio",
"intersectionRect",
"intersectsNode",
"interval",
"invalidIteratorState",
"invalidateFramebuffer",
"invalidateSubFramebuffer",
"inverse",
"invertSelf",
"is",
"is2D",
"isActive",
"isAlternate",
"isArray",
"isBingCurrentSearchDefault",
"isBuffer",
"isCandidateWindowVisible",
"isChar",
"isCollapsed",
"isComposing",
"isConcatSpreadable",
"isConnected",
"isContentEditable",
"isContentHandlerRegistered",
"isContextLost",
"isDefaultNamespace",
"isDirectory",
"isDisabled",
"isEnabled",
"isEqual",
"isEqualNode",
"isExtensible",
"isExternalCTAP2SecurityKeySupported",
"isFile",
"isFinite",
"isFramebuffer",
"isFrozen",
"isGenerator",
"isHTML",
"isHistoryNavigation",
"isId",
"isIdentity",
"isInjected",
"isInteger",
"isIntersecting",
"isLockFree",
"isMap",
"isMultiLine",
"isNaN",
"isOpen",
"isPointInFill",
"isPointInPath",
"isPointInRange",
"isPointInStroke",
"isPrefAlternate",
"isPresenting",
"isPrimary",
"isProgram",
"isPropertyImplicit",
"isProtocolHandlerRegistered",
"isPrototypeOf",
"isQuery",
"isRenderbuffer",
"isSafeInteger",
"isSameNode",
"isSampler",
"isScript",
"isScriptURL",
"isSealed",
"isSecureContext",
"isSessionSupported",
"isShader",
"isSupported",
"isSync",
"isTextEdit",
"isTexture",
"isTransformFeedback",
"isTrusted",
"isTypeSupported",
"isUserVerifyingPlatformAuthenticatorAvailable",
"isVertexArray",
"isView",
"isVisible",
"isochronousTransferIn",
"isochronousTransferOut",
"isolation",
"italics",
"item",
"itemId",
"itemProp",
"itemRef",
"itemScope",
"itemType",
"itemValue",
"items",
"iterateNext",
"iterationComposite",
"iterator",
"javaEnabled",
"jobTitle",
"join",
"json",
"justify-content",
"justify-items",
"justify-self",
"justifyContent",
"justifyItems",
"justifySelf",
"k1",
"k2",
"k3",
"k4",
"kHz",
"keepalive",
"kernelMatrix",
"kernelUnitLengthX",
"kernelUnitLengthY",
"kerning",
"key",
"keyCode",
"keyFor",
"keyIdentifier",
"keyLightEnabled",
"keyLocation",
"keyPath",
"keyStatuses",
"keySystem",
"keyText",
"keyUsage",
"keyboard",
"keys",
"keytype",
"kind",
"knee",
"label",
"labels",
"lang",
"language",
"languages",
"largeArcFlag",
"lastChild",
"lastElementChild",
"lastEventId",
"lastIndex",
"lastIndexOf",
"lastInputTime",
"lastMatch",
"lastMessageSubject",
"lastMessageType",
"lastModified",
"lastModifiedDate",
"lastPage",
"lastParen",
"lastState",
"lastStyleSheetSet",
"latitude",
"layerX",
"layerY",
"layoutFlow",
"layoutGrid",
"layoutGridChar",
"layoutGridLine",
"layoutGridMode",
"layoutGridType",
"lbound",
"left",
"leftContext",
"leftDegrees",
"leftMargin",
"leftProjectionMatrix",
"leftViewMatrix",
"length",
"lengthAdjust",
"lengthComputable",
"letter-spacing",
"letterSpacing",
"level",
"lighting-color",
"lightingColor",
"limitingConeAngle",
"line",
"line-break",
"line-height",
"lineAlign",
"lineBreak",
"lineCap",
"lineDashOffset",
"lineHeight",
"lineJoin",
"lineNumber",
"lineTo",
"lineWidth",
"linearAcceleration",
"linearRampToValueAtTime",
"linearVelocity",
"lineno",
"lines",
"link",
"linkColor",
"linkProgram",
"links",
"list",
"list-style",
"list-style-image",
"list-style-position",
"list-style-type",
"listStyle",
"listStyleImage",
"listStylePosition",
"listStyleType",
"listener",
"load",
"loadEventEnd",
"loadEventStart",
"loadTime",
"loadTimes",
"loaded",
"loading",
"localDescription",
"localName",
"localService",
"localStorage",
"locale",
"localeCompare",
"location",
"locationbar",
"lock",
"locked",
"lockedFile",
"locks",
"log",
"log10",
"log1p",
"log2",
"logicalXDPI",
"logicalYDPI",
"longDesc",
"longitude",
"lookupNamespaceURI",
"lookupPrefix",
"loop",
"loopEnd",
"loopStart",
"looping",
"low",
"lower",
"lowerBound",
"lowerOpen",
"lowsrc",
"m11",
"m12",
"m13",
"m14",
"m21",
"m22",
"m23",
"m24",
"m31",
"m32",
"m33",
"m34",
"m41",
"m42",
"m43",
"m44",
"makeXRCompatible",
"manifest",
"manufacturer",
"manufacturerName",
"map",
"mapping",
"margin",
"margin-block",
"margin-block-end",
"margin-block-start",
"margin-bottom",
"margin-inline",
"margin-inline-end",
"margin-inline-start",
"margin-left",
"margin-right",
"margin-top",
"marginBlock",
"marginBlockEnd",
"marginBlockStart",
"marginBottom",
"marginHeight",
"marginInline",
"marginInlineEnd",
"marginInlineStart",
"marginLeft",
"marginRight",
"marginTop",
"marginWidth",
"mark",
"marker",
"marker-end",
"marker-mid",
"marker-offset",
"marker-start",
"markerEnd",
"markerHeight",
"markerMid",
"markerOffset",
"markerStart",
"markerUnits",
"markerWidth",
"marks",
"mask",
"mask-clip",
"mask-composite",
"mask-image",
"mask-mode",
"mask-origin",
"mask-position",
"mask-position-x",
"mask-position-y",
"mask-repeat",
"mask-size",
"mask-type",
"maskClip",
"maskComposite",
"maskContentUnits",
"maskImage",
"maskMode",
"maskOrigin",
"maskPosition",
"maskPositionX",
"maskPositionY",
"maskRepeat",
"maskSize",
"maskType",
"maskUnits",
"match",
"matchAll",
"matchMedia",
"matchMedium",
"matches",
"matrix",
"matrixTransform",
"max",
"max-block-size",
"max-height",
"max-inline-size",
"max-width",
"maxActions",
"maxAlternatives",
"maxBlockSize",
"maxChannelCount",
"maxChannels",
"maxConnectionsPerServer",
"maxDecibels",
"maxDistance",
"maxHeight",
"maxInlineSize",
"maxLayers",
"maxLength",
"maxMessageSize",
"maxPacketLifeTime",
"maxRetransmits",
"maxTouchPoints",
"maxValue",
"maxWidth",
"measure",
"measureText",
"media",
"mediaCapabilities",
"mediaDevices",
"mediaElement",
"mediaGroup",
"mediaKeys",
"mediaSession",
"mediaStream",
"mediaText",
"meetOrSlice",
"memory",
"menubar",
"mergeAttributes",
"message",
"messageClass",
"messageHandlers",
"messageType",
"metaKey",
"metadata",
"method",
"methodDetails",
"methodName",
"mid",
"mimeType",
"mimeTypes",
"min",
"min-block-size",
"min-height",
"min-inline-size",
"min-width",
"minBlockSize",
"minDecibels",
"minHeight",
"minInlineSize",
"minLength",
"minValue",
"minWidth",
"miterLimit",
"mix-blend-mode",
"mixBlendMode",
"mm",
"mode",
"modify",
"mount",
"move",
"moveBy",
"moveEnd",
"moveFirst",
"moveFocusDown",
"moveFocusLeft",
"moveFocusRight",
"moveFocusUp",
"moveNext",
"moveRow",
"moveStart",
"moveTo",
"moveToBookmark",
"moveToElementText",
"moveToPoint",
"movementX",
"movementY",
"mozAdd",
"mozAnimationStartTime",
"mozAnon",
"mozApps",
"mozAudioCaptured",
"mozAudioChannelType",
"mozAutoplayEnabled",
"mozCancelAnimationFrame",
"mozCancelFullScreen",
"mozCancelRequestAnimationFrame",
"mozCaptureStream",
"mozCaptureStreamUntilEnded",
"mozClearDataAt",
"mozContact",
"mozContacts",
"mozCreateFileHandle",
"mozCurrentTransform",
"mozCurrentTransformInverse",
"mozCursor",
"mozDash",
"mozDashOffset",
"mozDecodedFrames",
"mozExitPointerLock",
"mozFillRule",
"mozFragmentEnd",
"mozFrameDelay",
"mozFullScreen",
"mozFullScreenElement",
"mozFullScreenEnabled",
"mozGetAll",
"mozGetAllKeys",
"mozGetAsFile",
"mozGetDataAt",
"mozGetMetadata",
"mozGetUserMedia",
"mozHasAudio",
"mozHasItem",
"mozHidden",
"mozImageSmoothingEnabled",
"mozIndexedDB",
"mozInnerScreenX",
"mozInnerScreenY",
"mozInputSource",
"mozIsTextField",
"mozItem",
"mozItemCount",
"mozItems",
"mozLength",
"mozLockOrientation",
"mozMatchesSelector",
"mozMovementX",
"mozMovementY",
"mozOpaque",
"mozOrientation",
"mozPaintCount",
"mozPaintedFrames",
"mozParsedFrames",
"mozPay",
"mozPointerLockElement",
"mozPresentedFrames",
"mozPreservesPitch",
"mozPressure",
"mozPrintCallback",
"mozRTCIceCandidate",
"mozRTCPeerConnection",
"mozRTCSessionDescription",
"mozRemove",
"mozRequestAnimationFrame",
"mozRequestFullScreen",
"mozRequestPointerLock",
"mozSetDataAt",
"mozSetImageElement",
"mozSourceNode",
"mozSrcObject",
"mozSystem",
"mozTCPSocket",
"mozTextStyle",
"mozTypesAt",
"mozUnlockOrientation",
"mozUserCancelled",
"mozVisibilityState",
"ms",
"msAnimation",
"msAnimationDelay",
"msAnimationDirection",
"msAnimationDuration",
"msAnimationFillMode",
"msAnimationIterationCount",
"msAnimationName",
"msAnimationPlayState",
"msAnimationStartTime",
"msAnimationTimingFunction",
"msBackfaceVisibility",
"msBlockProgression",
"msCSSOMElementFloatMetrics",
"msCaching",
"msCachingEnabled",
"msCancelRequestAnimationFrame",
"msCapsLockWarningOff",
"msClearImmediate",
"msClose",
"msContentZoomChaining",
"msContentZoomFactor",
"msContentZoomLimit",
"msContentZoomLimitMax",
"msContentZoomLimitMin",
"msContentZoomSnap",
"msContentZoomSnapPoints",
"msContentZoomSnapType",
"msContentZooming",
"msConvertURL",
"msCrypto",
"msDoNotTrack",
"msElementsFromPoint",
"msElementsFromRect",
"msExitFullscreen",
"msExtendedCode",
"msFillRule",
"msFirstPaint",
"msFlex",
"msFlexAlign",
"msFlexDirection",
"msFlexFlow",
"msFlexItemAlign",
"msFlexLinePack",
"msFlexNegative",
"msFlexOrder",
"msFlexPack",
"msFlexPositive",
"msFlexPreferredSize",
"msFlexWrap",
"msFlowFrom",
"msFlowInto",
"msFontFeatureSettings",
"msFullscreenElement",
"msFullscreenEnabled",
"msGetInputContext",
"msGetRegionContent",
"msGetUntransformedBounds",
"msGraphicsTrustStatus",
"msGridColumn",
"msGridColumnAlign",
"msGridColumnSpan",
"msGridColumns",
"msGridRow",
"msGridRowAlign",
"msGridRowSpan",
"msGridRows",
"msHidden",
"msHighContrastAdjust",
"msHyphenateLimitChars",
"msHyphenateLimitLines",
"msHyphenateLimitZone",
"msHyphens",
"msImageSmoothingEnabled",
"msImeAlign",
"msIndexedDB",
"msInterpolationMode",
"msIsStaticHTML",
"msKeySystem",
"msKeys",
"msLaunchUri",
"msLockOrientation",
"msManipulationViewsEnabled",
"msMatchMedia",
"msMatchesSelector",
"msMaxTouchPoints",
"msOrientation",
"msOverflowStyle",
"msPerspective",
"msPerspectiveOrigin",
"msPlayToDisabled",
"msPlayToPreferredSourceUri",
"msPlayToPrimary",
"msPointerEnabled",
"msRegionOverflow",
"msReleasePointerCapture",
"msRequestAnimationFrame",
"msRequestFullscreen",
"msSaveBlob",
"msSaveOrOpenBlob",
"msScrollChaining",
"msScrollLimit",
"msScrollLimitXMax",
"msScrollLimitXMin",
"msScrollLimitYMax",
"msScrollLimitYMin",
"msScrollRails",
"msScrollSnapPointsX",
"msScrollSnapPointsY",
"msScrollSnapType",
"msScrollSnapX",
"msScrollSnapY",
"msScrollTranslation",
"msSetImmediate",
"msSetMediaKeys",
"msSetPointerCapture",
"msTextCombineHorizontal",
"msTextSizeAdjust",
"msToBlob",
"msTouchAction",
"msTouchSelect",
"msTraceAsyncCallbackCompleted",
"msTraceAsyncCallbackStarting",
"msTraceAsyncOperationCompleted",
"msTraceAsyncOperationStarting",
"msTransform",
"msTransformOrigin",
"msTransformStyle",
"msTransition",
"msTransitionDelay",
"msTransitionDuration",
"msTransitionProperty",
"msTransitionTimingFunction",
"msUnlockOrientation",
"msUpdateAsyncCallbackRelation",
"msUserSelect",
"msVisibilityState",
"msWrapFlow",
"msWrapMargin",
"msWrapThrough",
"msWriteProfilerMark",
"msZoom",
"msZoomTo",
"mt",
"mul",
"multiEntry",
"multiSelectionObj",
"multiline",
"multiple",
"multiply",
"multiplySelf",
"mutableFile",
"muted",
"n",
"name",
"nameProp",
"namedItem",
"namedRecordset",
"names",
"namespaceURI",
"namespaces",
"naturalHeight",
"naturalWidth",
"navigate",
"navigation",
"navigationMode",
"navigationPreload",
"navigationStart",
"navigator",
"near",
"nearestViewportElement",
"negative",
"negotiated",
"netscape",
"networkState",
"newScale",
"newTranslate",
"newURL",
"newValue",
"newValueSpecifiedUnits",
"newVersion",
"newhome",
"next",
"nextElementSibling",
"nextHopProtocol",
"nextNode",
"nextPage",
"nextSibling",
"nickname",
"noHref",
"noModule",
"noResize",
"noShade",
"noValidate",
"noWrap",
"node",
"nodeName",
"nodeType",
"nodeValue",
"nonce",
"normalize",
"normalizedPathSegList",
"notationName",
"notations",
"note",
"noteGrainOn",
"noteOff",
"noteOn",
"notify",
"now",
"numOctaves",
"number",
"numberOfChannels",
"numberOfInputs",
"numberOfItems",
"numberOfOutputs",
"numberValue",
"oMatchesSelector",
"object",
"object-fit",
"object-position",
"objectFit",
"objectPosition",
"objectStore",
"objectStoreNames",
"objectType",
"observe",
"of",
"offscreenBuffering",
"offset",
"offset-anchor",
"offset-distance",
"offset-path",
"offset-rotate",
"offsetAnchor",
"offsetDistance",
"offsetHeight",
"offsetLeft",
"offsetNode",
"offsetParent",
"offsetPath",
"offsetRotate",
"offsetTop",
"offsetWidth",
"offsetX",
"offsetY",
"ok",
"oldURL",
"oldValue",
"oldVersion",
"olderShadowRoot",
"onLine",
"onabort",
"onabsolutedeviceorientation",
"onactivate",
"onactive",
"onaddsourcebuffer",
"onaddstream",
"onaddtrack",
"onafterprint",
"onafterscriptexecute",
"onafterupdate",
"onanimationcancel",
"onanimationend",
"onanimationiteration",
"onanimationstart",
"onappinstalled",
"onaudioend",
"onaudioprocess",
"onaudiostart",
"onautocomplete",
"onautocompleteerror",
"onauxclick",
"onbeforeactivate",
"onbeforecopy",
"onbeforecut",
"onbeforedeactivate",
"onbeforeeditfocus",
"onbeforeinstallprompt",
"onbeforepaste",
"onbeforeprint",
"onbeforescriptexecute",
"onbeforeunload",
"onbeforeupdate",
"onbeforexrselect",
"onbegin",
"onblocked",
"onblur",
"onbounce",
"onboundary",
"onbufferedamountlow",
"oncached",
"oncancel",
"oncandidatewindowhide",
"oncandidatewindowshow",
"oncandidatewindowupdate",
"oncanplay",
"oncanplaythrough",
"once",
"oncellchange",
"onchange",
"oncharacteristicvaluechanged",
"onchargingchange",
"onchargingtimechange",
"onchecking",
"onclick",
"onclose",
"onclosing",
"oncompassneedscalibration",
"oncomplete",
"onconnect",
"onconnecting",
"onconnectionavailable",
"onconnectionstatechange",
"oncontextmenu",
"oncontrollerchange",
"oncontrolselect",
"oncopy",
"oncuechange",
"oncut",
"ondataavailable",
"ondatachannel",
"ondatasetchanged",
"ondatasetcomplete",
"ondblclick",
"ondeactivate",
"ondevicechange",
"ondevicelight",
"ondevicemotion",
"ondeviceorientation",
"ondeviceorientationabsolute",
"ondeviceproximity",
"ondischargingtimechange",
"ondisconnect",
"ondisplay",
"ondownloading",
"ondrag",
"ondragend",
"ondragenter",
"ondragexit",
"ondragleave",
"ondragover",
"ondragstart",
"ondrop",
"ondurationchange",
"onemptied",
"onencrypted",
"onend",
"onended",
"onenter",
"onenterpictureinpicture",
"onerror",
"onerrorupdate",
"onexit",
"onfilterchange",
"onfinish",
"onfocus",
"onfocusin",
"onfocusout",
"onformdata",
"onfreeze",
"onfullscreenchange",
"onfullscreenerror",
"ongatheringstatechange",
"ongattserverdisconnected",
"ongesturechange",
"ongestureend",
"ongesturestart",
"ongotpointercapture",
"onhashchange",
"onhelp",
"onicecandidate",
"onicecandidateerror",
"oniceconnectionstatechange",
"onicegatheringstatechange",
"oninactive",
"oninput",
"oninputsourceschange",
"oninvalid",
"onkeydown",
"onkeypress",
"onkeystatuseschange",
"onkeyup",
"onlanguagechange",
"onlayoutcomplete",
"onleavepictureinpicture",
"onlevelchange",
"onload",
"onloadeddata",
"onloadedmetadata",
"onloadend",
"onloading",
"onloadingdone",
"onloadingerror",
"onloadstart",
"onlosecapture",
"onlostpointercapture",
"only",
"onmark",
"onmessage",
"onmessageerror",
"onmidimessage",
"onmousedown",
"onmouseenter",
"onmouseleave",
"onmousemove",
"onmouseout",
"onmouseover",
"onmouseup",
"onmousewheel",
"onmove",
"onmoveend",
"onmovestart",
"onmozfullscreenchange",
"onmozfullscreenerror",
"onmozorientationchange",
"onmozpointerlockchange",
"onmozpointerlockerror",
"onmscontentzoom",
"onmsfullscreenchange",
"onmsfullscreenerror",
"onmsgesturechange",
"onmsgesturedoubletap",
"onmsgestureend",
"onmsgesturehold",
"onmsgesturestart",
"onmsgesturetap",
"onmsgotpointercapture",
"onmsinertiastart",
"onmslostpointercapture",
"onmsmanipulationstatechanged",
"onmsneedkey",
"onmsorientationchange",
"onmspointercancel",
"onmspointerdown",
"onmspointerenter",
"onmspointerhover",
"onmspointerleave",
"onmspointermove",
"onmspointerout",
"onmspointerover",
"onmspointerup",
"onmssitemodejumplistitemremoved",
"onmsthumbnailclick",
"onmute",
"onnegotiationneeded",
"onnomatch",
"onnoupdate",
"onobsolete",
"onoffline",
"ononline",
"onopen",
"onorientationchange",
"onpagechange",
"onpagehide",
"onpageshow",
"onpaste",
"onpause",
"onpayerdetailchange",
"onpaymentmethodchange",
"onplay",
"onplaying",
"onpluginstreamstart",
"onpointercancel",
"onpointerdown",
"onpointerenter",
"onpointerleave",
"onpointerlockchange",
"onpointerlockerror",
"onpointermove",
"onpointerout",
"onpointerover",
"onpointerrawupdate",
"onpointerup",
"onpopstate",
"onprocessorerror",
"onprogress",
"onpropertychange",
"onratechange",
"onreading",
"onreadystatechange",
"onrejectionhandled",
"onrelease",
"onremove",
"onremovesourcebuffer",
"onremovestream",
"onremovetrack",
"onrepeat",
"onreset",
"onresize",
"onresizeend",
"onresizestart",
"onresourcetimingbufferfull",
"onresult",
"onresume",
"onrowenter",
"onrowexit",
"onrowsdelete",
"onrowsinserted",
"onscroll",
"onsearch",
"onsecuritypolicyviolation",
"onseeked",
"onseeking",
"onselect",
"onselectedcandidatepairchange",
"onselectend",
"onselectionchange",
"onselectstart",
"onshippingaddresschange",
"onshippingoptionchange",
"onshow",
"onsignalingstatechange",
"onsoundend",
"onsoundstart",
"onsourceclose",
"onsourceclosed",
"onsourceended",
"onsourceopen",
"onspeechend",
"onspeechstart",
"onsqueeze",
"onsqueezeend",
"onsqueezestart",
"onstalled",
"onstart",
"onstatechange",
"onstop",
"onstorage",
"onstoragecommit",
"onsubmit",
"onsuccess",
"onsuspend",
"onterminate",
"ontextinput",
"ontimeout",
"ontimeupdate",
"ontoggle",
"ontonechange",
"ontouchcancel",
"ontouchend",
"ontouchmove",
"ontouchstart",
"ontrack",
"ontransitioncancel",
"ontransitionend",
"ontransitionrun",
"ontransitionstart",
"onunhandledrejection",
"onunload",
"onunmute",
"onupdate",
"onupdateend",
"onupdatefound",
"onupdateready",
"onupdatestart",
"onupgradeneeded",
"onuserproximity",
"onversionchange",
"onvisibilitychange",
"onvoiceschanged",
"onvolumechange",
"onvrdisplayactivate",
"onvrdisplayconnect",
"onvrdisplaydeactivate",
"onvrdisplaydisconnect",
"onvrdisplaypresentchange",
"onwaiting",
"onwaitingforkey",
"onwarning",
"onwebkitanimationend",
"onwebkitanimationiteration",
"onwebkitanimationstart",
"onwebkitcurrentplaybacktargetiswirelesschanged",
"onwebkitfullscreenchange",
"onwebkitfullscreenerror",
"onwebkitkeyadded",
"onwebkitkeyerror",
"onwebkitkeymessage",
"onwebkitneedkey",
"onwebkitorientationchange",
"onwebkitplaybacktargetavailabilitychanged",
"onwebkitpointerlockchange",
"onwebkitpointerlockerror",
"onwebkitresourcetimingbufferfull",
"onwebkittransitionend",
"onwheel",
"onzoom",
"opacity",
"open",
"openCursor",
"openDatabase",
"openKeyCursor",
"opened",
"opener",
"opera",
"operationType",
"operator",
"opr",
"optimum",
"options",
"or",
"order",
"orderX",
"orderY",
"ordered",
"org",
"organization",
"orient",
"orientAngle",
"orientType",
"orientation",
"orientationX",
"orientationY",
"orientationZ",
"origin",
"originalPolicy",
"originalTarget",
"orphans",
"oscpu",
"outerHTML",
"outerHeight",
"outerText",
"outerWidth",
"outline",
"outline-color",
"outline-offset",
"outline-style",
"outline-width",
"outlineColor",
"outlineOffset",
"outlineStyle",
"outlineWidth",
"outputBuffer",
"outputLatency",
"outputs",
"overflow",
"overflow-anchor",
"overflow-block",
"overflow-inline",
"overflow-wrap",
"overflow-x",
"overflow-y",
"overflowAnchor",
"overflowBlock",
"overflowInline",
"overflowWrap",
"overflowX",
"overflowY",
"overrideMimeType",
"oversample",
"overscroll-behavior",
"overscroll-behavior-block",
"overscroll-behavior-inline",
"overscroll-behavior-x",
"overscroll-behavior-y",
"overscrollBehavior",
"overscrollBehaviorBlock",
"overscrollBehaviorInline",
"overscrollBehaviorX",
"overscrollBehaviorY",
"ownKeys",
"ownerDocument",
"ownerElement",
"ownerNode",
"ownerRule",
"ownerSVGElement",
"owningElement",
"p1",
"p2",
"p3",
"p4",
"packetSize",
"packets",
"pad",
"padEnd",
"padStart",
"padding",
"padding-block",
"padding-block-end",
"padding-block-start",
"padding-bottom",
"padding-inline",
"padding-inline-end",
"padding-inline-start",
"padding-left",
"padding-right",
"padding-top",
"paddingBlock",
"paddingBlockEnd",
"paddingBlockStart",
"paddingBottom",
"paddingInline",
"paddingInlineEnd",
"paddingInlineStart",
"paddingLeft",
"paddingRight",
"paddingTop",
"page",
"page-break-after",
"page-break-before",
"page-break-inside",
"pageBreakAfter",
"pageBreakBefore",
"pageBreakInside",
"pageCount",
"pageLeft",
"pageTop",
"pageX",
"pageXOffset",
"pageY",
"pageYOffset",
"pages",
"paint-order",
"paintOrder",
"paintRequests",
"paintType",
"paintWorklet",
"palette",
"pan",
"panningModel",
"parameters",
"parent",
"parentElement",
"parentNode",
"parentRule",
"parentStyleSheet",
"parentTextEdit",
"parentWindow",
"parse",
"parseAll",
"parseFloat",
"parseFromString",
"parseInt",
"part",
"participants",
"passive",
"password",
"pasteHTML",
"path",
"pathLength",
"pathSegList",
"pathSegType",
"pathSegTypeAsLetter",
"pathname",
"pattern",
"patternContentUnits",
"patternMismatch",
"patternTransform",
"patternUnits",
"pause",
"pauseAnimations",
"pauseOnExit",
"pauseProfilers",
"pauseTransformFeedback",
"paused",
"payerEmail",
"payerName",
"payerPhone",
"paymentManager",
"pc",
"peerIdentity",
"pending",
"pendingLocalDescription",
"pendingRemoteDescription",
"percent",
"performance",
"periodicSync",
"permission",
"permissionState",
"permissions",
"persist",
"persisted",
"personalbar",
"perspective",
"perspective-origin",
"perspectiveOrigin",
"phone",
"phoneticFamilyName",
"phoneticGivenName",
"photo",
"pictureInPictureElement",
"pictureInPictureEnabled",
"pictureInPictureWindow",
"ping",
"pipeThrough",
"pipeTo",
"pitch",
"pixelBottom",
"pixelDepth",
"pixelHeight",
"pixelLeft",
"pixelRight",
"pixelStorei",
"pixelTop",
"pixelUnitToMillimeterX",
"pixelUnitToMillimeterY",
"pixelWidth",
"place-content",
"place-items",
"place-self",
"placeContent",
"placeItems",
"placeSelf",
"placeholder",
"platform",
"platforms",
"play",
"playEffect",
"playState",
"playbackRate",
"playbackState",
"playbackTime",
"played",
"playoutDelayHint",
"playsInline",
"plugins",
"pluginspage",
"pname",
"pointer-events",
"pointerBeforeReferenceNode",
"pointerEnabled",
"pointerEvents",
"pointerId",
"pointerLockElement",
"pointerType",
"points",
"pointsAtX",
"pointsAtY",
"pointsAtZ",
"polygonOffset",
"pop",
"populateMatrix",
"popupWindowFeatures",
"popupWindowName",
"popupWindowURI",
"port",
"port1",
"port2",
"ports",
"posBottom",
"posHeight",
"posLeft",
"posRight",
"posTop",
"posWidth",
"pose",
"position",
"positionAlign",
"positionX",
"positionY",
"positionZ",
"postError",
"postMessage",
"postalCode",
"poster",
"pow",
"powerEfficient",
"powerOff",
"preMultiplySelf",
"precision",
"preferredStyleSheetSet",
"preferredStylesheetSet",
"prefix",
"preload",
"prepend",
"presentation",
"preserveAlpha",
"preserveAspectRatio",
"preserveAspectRatioString",
"pressed",
"pressure",
"prevValue",
"preventDefault",
"preventExtensions",
"preventSilentAccess",
"previousElementSibling",
"previousNode",
"previousPage",
"previousRect",
"previousScale",
"previousSibling",
"previousTranslate",
"primaryKey",
"primitiveType",
"primitiveUnits",
"principals",
"print",
"priority",
"privateKey",
"probablySupportsContext",
"process",
"processIceMessage",
"processingEnd",
"processingStart",
"product",
"productId",
"productName",
"productSub",
"profile",
"profileEnd",
"profiles",
"projectionMatrix",
"promise",
"prompt",
"properties",
"propertyIsEnumerable",
"propertyName",
"protocol",
"protocolLong",
"prototype",
"provider",
"pseudoClass",
"pseudoElement",
"pt",
"publicId",
"publicKey",
"published",
"pulse",
"push",
"pushManager",
"pushNotification",
"pushState",
"put",
"putImageData",
"px",
"quadraticCurveTo",
"qualifier",
"quaternion",
"query",
"queryCommandEnabled",
"queryCommandIndeterm",
"queryCommandState",
"queryCommandSupported",
"queryCommandText",
"queryCommandValue",
"querySelector",
"querySelectorAll",
"queueMicrotask",
"quote",
"quotes",
"r",
"r1",
"r2",
"race",
"rad",
"radiogroup",
"radiusX",
"radiusY",
"random",
"range",
"rangeCount",
"rangeMax",
"rangeMin",
"rangeOffset",
"rangeOverflow",
"rangeParent",
"rangeUnderflow",
"rate",
"ratio",
"raw",
"rawId",
"read",
"readAsArrayBuffer",
"readAsBinaryString",
"readAsBlob",
"readAsDataURL",
"readAsText",
"readBuffer",
"readEntries",
"readOnly",
"readPixels",
"readReportRequested",
"readText",
"readValue",
"readable",
"ready",
"readyState",
"reason",
"reboot",
"receivedAlert",
"receiver",
"receivers",
"recipient",
"reconnect",
"recordNumber",
"recordsAvailable",
"recordset",
"rect",
"red",
"redEyeReduction",
"redirect",
"redirectCount",
"redirectEnd",
"redirectStart",
"redirected",
"reduce",
"reduceRight",
"reduction",
"refDistance",
"refX",
"refY",
"referenceNode",
"referenceSpace",
"referrer",
"referrerPolicy",
"refresh",
"region",
"regionAnchorX",
"regionAnchorY",
"regionId",
"regions",
"register",
"registerContentHandler",
"registerElement",
"registerProperty",
"registerProtocolHandler",
"reject",
"rel",
"relList",
"relatedAddress",
"relatedNode",
"relatedPort",
"relatedTarget",
"release",
"releaseCapture",
"releaseEvents",
"releaseInterface",
"releaseLock",
"releasePointerCapture",
"releaseShaderCompiler",
"reliable",
"reliableWrite",
"reload",
"rem",
"remainingSpace",
"remote",
"remoteDescription",
"remove",
"removeAllRanges",
"removeAttribute",
"removeAttributeNS",
"removeAttributeNode",
"removeBehavior",
"removeChild",
"removeCue",
"removeEventListener",
"removeFilter",
"removeImport",
"removeItem",
"removeListener",
"removeNamedItem",
"removeNamedItemNS",
"removeNode",
"removeParameter",
"removeProperty",
"removeRange",
"removeRegion",
"removeRule",
"removeSiteSpecificTrackingException",
"removeSourceBuffer",
"removeStream",
"removeTrack",
"removeVariable",
"removeWakeLockListener",
"removeWebWideTrackingException",
"removed",
"removedNodes",
"renderHeight",
"renderState",
"renderTime",
"renderWidth",
"renderbufferStorage",
"renderbufferStorageMultisample",
"renderedBuffer",
"renderingMode",
"renotify",
"repeat",
"replace",
"replaceAdjacentText",
"replaceAll",
"replaceChild",
"replaceChildren",
"replaceData",
"replaceId",
"replaceItem",
"replaceNode",
"replaceState",
"replaceSync",
"replaceTrack",
"replaceWholeText",
"replaceWith",
"reportValidity",
"request",
"requestAnimationFrame",
"requestAutocomplete",
"requestData",
"requestDevice",
"requestFrame",
"requestFullscreen",
"requestHitTestSource",
"requestHitTestSourceForTransientInput",
"requestId",
"requestIdleCallback",
"requestMIDIAccess",
"requestMediaKeySystemAccess",
"requestPermission",
"requestPictureInPicture",
"requestPointerLock",
"requestPresent",
"requestReferenceSpace",
"requestSession",
"requestStart",
"requestStorageAccess",
"requestSubmit",
"requestVideoFrameCallback",
"requestingWindow",
"requireInteraction",
"required",
"requiredExtensions",
"requiredFeatures",
"reset",
"resetPose",
"resetTransform",
"resize",
"resizeBy",
"resizeTo",
"resolve",
"response",
"responseBody",
"responseEnd",
"responseReady",
"responseStart",
"responseText",
"responseType",
"responseURL",
"responseXML",
"restartIce",
"restore",
"result",
"resultIndex",
"resultType",
"results",
"resume",
"resumeProfilers",
"resumeTransformFeedback",
"retry",
"returnValue",
"rev",
"reverse",
"reversed",
"revocable",
"revokeObjectURL",
"rgbColor",
"right",
"rightContext",
"rightDegrees",
"rightMargin",
"rightProjectionMatrix",
"rightViewMatrix",
"role",
"rolloffFactor",
"root",
"rootBounds",
"rootElement",
"rootMargin",
"rotate",
"rotateAxisAngle",
"rotateAxisAngleSelf",
"rotateFromVector",
"rotateFromVectorSelf",
"rotateSelf",
"rotation",
"rotationAngle",
"rotationRate",
"round",
"row-gap",
"rowGap",
"rowIndex",
"rowSpan",
"rows",
"rtcpTransport",
"rtt",
"ruby-align",
"ruby-position",
"rubyAlign",
"rubyOverhang",
"rubyPosition",
"rules",
"runtime",
"runtimeStyle",
"rx",
"ry",
"s",
"safari",
"sample",
"sampleCoverage",
"sampleRate",
"samplerParameterf",
"samplerParameteri",
"sandbox",
"save",
"saveData",
"scale",
"scale3d",
"scale3dSelf",
"scaleNonUniform",
"scaleNonUniformSelf",
"scaleSelf",
"scheme",
"scissor",
"scope",
"scopeName",
"scoped",
"screen",
"screenBrightness",
"screenEnabled",
"screenLeft",
"screenPixelToMillimeterX",
"screenPixelToMillimeterY",
"screenTop",
"screenX",
"screenY",
"scriptURL",
"scripts",
"scroll",
"scroll-behavior",
"scroll-margin",
"scroll-margin-block",
"scroll-margin-block-end",
"scroll-margin-block-start",
"scroll-margin-bottom",
"scroll-margin-inline",
"scroll-margin-inline-end",
"scroll-margin-inline-start",
"scroll-margin-left",
"scroll-margin-right",
"scroll-margin-top",
"scroll-padding",
"scroll-padding-block",
"scroll-padding-block-end",
"scroll-padding-block-start",
"scroll-padding-bottom",
"scroll-padding-inline",
"scroll-padding-inline-end",
"scroll-padding-inline-start",
"scroll-padding-left",
"scroll-padding-right",
"scroll-padding-top",
"scroll-snap-align",
"scroll-snap-type",
"scrollAmount",
"scrollBehavior",
"scrollBy",
"scrollByLines",
"scrollByPages",
"scrollDelay",
"scrollHeight",
"scrollIntoView",
"scrollIntoViewIfNeeded",
"scrollLeft",
"scrollLeftMax",
"scrollMargin",
"scrollMarginBlock",
"scrollMarginBlockEnd",
"scrollMarginBlockStart",
"scrollMarginBottom",
"scrollMarginInline",
"scrollMarginInlineEnd",
"scrollMarginInlineStart",
"scrollMarginLeft",
"scrollMarginRight",
"scrollMarginTop",
"scrollMaxX",
"scrollMaxY",
"scrollPadding",
"scrollPaddingBlock",
"scrollPaddingBlockEnd",
"scrollPaddingBlockStart",
"scrollPaddingBottom",
"scrollPaddingInline",
"scrollPaddingInlineEnd",
"scrollPaddingInlineStart",
"scrollPaddingLeft",
"scrollPaddingRight",
"scrollPaddingTop",
"scrollRestoration",
"scrollSnapAlign",
"scrollSnapType",
"scrollTo",
"scrollTop",
"scrollTopMax",
"scrollWidth",
"scrollX",
"scrollY",
"scrollbar-color",
"scrollbar-width",
"scrollbar3dLightColor",
"scrollbarArrowColor",
"scrollbarBaseColor",
"scrollbarColor",
"scrollbarDarkShadowColor",
"scrollbarFaceColor",
"scrollbarHighlightColor",
"scrollbarShadowColor",
"scrollbarTrackColor",
"scrollbarWidth",
"scrollbars",
"scrolling",
"scrollingElement",
"sctp",
"sctpCauseCode",
"sdp",
"sdpLineNumber",
"sdpMLineIndex",
"sdpMid",
"seal",
"search",
"searchBox",
"searchBoxJavaBridge_",
"searchParams",
"sectionRowIndex",
"secureConnectionStart",
"security",
"seed",
"seekToNextFrame",
"seekable",
"seeking",
"select",
"selectAllChildren",
"selectAlternateInterface",
"selectConfiguration",
"selectNode",
"selectNodeContents",
"selectNodes",
"selectSingleNode",
"selectSubString",
"selected",
"selectedIndex",
"selectedOptions",
"selectedStyleSheetSet",
"selectedStylesheetSet",
"selection",
"selectionDirection",
"selectionEnd",
"selectionStart",
"selector",
"selectorText",
"self",
"send",
"sendAsBinary",
"sendBeacon",
"sender",
"sentAlert",
"sentTimestamp",
"separator",
"serialNumber",
"serializeToString",
"serverTiming",
"service",
"serviceWorker",
"session",
"sessionId",
"sessionStorage",
"set",
"setActionHandler",
"setActive",
"setAlpha",
"setAppBadge",
"setAttribute",
"setAttributeNS",
"setAttributeNode",
"setAttributeNodeNS",
"setBaseAndExtent",
"setBigInt64",
"setBigUint64",
"setBingCurrentSearchDefault",
"setCapture",
"setCodecPreferences",
"setColor",
"setCompositeOperation",
"setConfiguration",
"setCurrentTime",
"setCustomValidity",
"setData",
"setDate",
"setDragImage",
"setEnd",
"setEndAfter",
"setEndBefore",
"setEndPoint",
"setFillColor",
"setFilterRes",
"setFloat32",
"setFloat64",
"setFloatValue",
"setFormValue",
"setFullYear",
"setHeaderValue",
"setHours",
"setIdentityProvider",
"setImmediate",
"setInt16",
"setInt32",
"setInt8",
"setInterval",
"setItem",
"setKeyframes",
"setLineCap",
"setLineDash",
"setLineJoin",
"setLineWidth",
"setLiveSeekableRange",
"setLocalDescription",
"setMatrix",
"setMatrixValue",
"setMediaKeys",
"setMilliseconds",
"setMinutes",
"setMiterLimit",
"setMonth",
"setNamedItem",
"setNamedItemNS",
"setNonUserCodeExceptions",
"setOrientToAngle",
"setOrientToAuto",
"setOrientation",
"setOverrideHistoryNavigationMode",
"setPaint",
"setParameter",
"setParameters",
"setPeriodicWave",
"setPointerCapture",
"setPosition",
"setPositionState",
"setPreference",
"setProperty",
"setPrototypeOf",
"setRGBColor",
"setRGBColorICCColor",
"setRadius",
"setRangeText",
"setRemoteDescription",
"setRequestHeader",
"setResizable",
"setResourceTimingBufferSize",
"setRotate",
"setScale",
"setSeconds",
"setSelectionRange",
"setServerCertificate",
"setShadow",
"setSinkId",
"setSkewX",
"setSkewY",
"setStart",
"setStartAfter",
"setStartBefore",
"setStdDeviation",
"setStreams",
"setStringValue",
"setStrokeColor",
"setSuggestResult",
"setTargetAtTime",
"setTargetValueAtTime",
"setTime",
"setTimeout",
"setTransform",
"setTranslate",
"setUTCDate",
"setUTCFullYear",
"setUTCHours",
"setUTCMilliseconds",
"setUTCMinutes",
"setUTCMonth",
"setUTCSeconds",
"setUint16",
"setUint32",
"setUint8",
"setUri",
"setValidity",
"setValueAtTime",
"setValueCurveAtTime",
"setVariable",
"setVelocity",
"setVersion",
"setYear",
"settingName",
"settingValue",
"sex",
"shaderSource",
"shadowBlur",
"shadowColor",
"shadowOffsetX",
"shadowOffsetY",
"shadowRoot",
"shape",
"shape-image-threshold",
"shape-margin",
"shape-outside",
"shape-rendering",
"shapeImageThreshold",
"shapeMargin",
"shapeOutside",
"shapeRendering",
"sheet",
"shift",
"shiftKey",
"shiftLeft",
"shippingAddress",
"shippingOption",
"shippingType",
"show",
"showHelp",
"showModal",
"showModalDialog",
"showModelessDialog",
"showNotification",
"sidebar",
"sign",
"signal",
"signalingState",
"signature",
"silent",
"sin",
"singleNodeValue",
"sinh",
"sinkId",
"sittingToStandingTransform",
"size",
"sizeToContent",
"sizeX",
"sizeZ",
"sizes",
"skewX",
"skewXSelf",
"skewY",
"skewYSelf",
"slice",
"slope",
"slot",
"small",
"smil",
"smooth",
"smoothingTimeConstant",
"snapToLines",
"snapshotItem",
"snapshotLength",
"some",
"sort",
"sortingCode",
"source",
"sourceBuffer",
"sourceBuffers",
"sourceCapabilities",
"sourceFile",
"sourceIndex",
"sources",
"spacing",
"span",
"speak",
"speakAs",
"speaking",
"species",
"specified",
"specularConstant",
"specularExponent",
"speechSynthesis",
"speed",
"speedOfSound",
"spellcheck",
"splice",
"split",
"splitText",
"spreadMethod",
"sqrt",
"src",
"srcElement",
"srcFilter",
"srcObject",
"srcUrn",
"srcdoc",
"srclang",
"srcset",
"stack",
"stackTraceLimit",
"stacktrace",
"stageParameters",
"standalone",
"standby",
"start",
"startContainer",
"startIce",
"startMessages",
"startNotifications",
"startOffset",
"startProfiling",
"startRendering",
"startShark",
"startTime",
"startsWith",
"state",
"status",
"statusCode",
"statusMessage",
"statusText",
"statusbar",
"stdDeviationX",
"stdDeviationY",
"stencilFunc",
"stencilFuncSeparate",
"stencilMask",
"stencilMaskSeparate",
"stencilOp",
"stencilOpSeparate",
"step",
"stepDown",
"stepMismatch",
"stepUp",
"sticky",
"stitchTiles",
"stop",
"stop-color",
"stop-opacity",
"stopColor",
"stopImmediatePropagation",
"stopNotifications",
"stopOpacity",
"stopProfiling",
"stopPropagation",
"stopShark",
"stopped",
"storage",
"storageArea",
"storageName",
"storageStatus",
"store",
"storeSiteSpecificTrackingException",
"storeWebWideTrackingException",
"stpVersion",
"stream",
"streams",
"stretch",
"strike",
"string",
"stringValue",
"stringify",
"stroke",
"stroke-dasharray",
"stroke-dashoffset",
"stroke-linecap",
"stroke-linejoin",
"stroke-miterlimit",
"stroke-opacity",
"stroke-width",
"strokeDasharray",
"strokeDashoffset",
"strokeLinecap",
"strokeLinejoin",
"strokeMiterlimit",
"strokeOpacity",
"strokeRect",
"strokeStyle",
"strokeText",
"strokeWidth",
"style",
"styleFloat",
"styleMap",
"styleMedia",
"styleSheet",
"styleSheetSets",
"styleSheets",
"sub",
"subarray",
"subject",
"submit",
"submitFrame",
"submitter",
"subscribe",
"substr",
"substring",
"substringData",
"subtle",
"subtree",
"suffix",
"suffixes",
"summary",
"sup",
"supported",
"supportedContentEncodings",
"supportedEntryTypes",
"supports",
"supportsSession",
"surfaceScale",
"surroundContents",
"suspend",
"suspendRedraw",
"swapCache",
"swapNode",
"sweepFlag",
"symbols",
"sync",
"sysexEnabled",
"system",
"systemCode",
"systemId",
"systemLanguage",
"systemXDPI",
"systemYDPI",
"tBodies",
"tFoot",
"tHead",
"tabIndex",
"table",
"table-layout",
"tableLayout",
"tableValues",
"tag",
"tagName",
"tagUrn",
"tags",
"taintEnabled",
"takePhoto",
"takeRecords",
"tan",
"tangentialPressure",
"tanh",
"target",
"targetElement",
"targetRayMode",
"targetRaySpace",
"targetTouches",
"targetX",
"targetY",
"tcpType",
"tee",
"tel",
"terminate",
"test",
"texImage2D",
"texImage3D",
"texParameterf",
"texParameteri",
"texStorage2D",
"texStorage3D",
"texSubImage2D",
"texSubImage3D",
"text",
"text-align",
"text-align-last",
"text-anchor",
"text-combine-upright",
"text-decoration",
"text-decoration-color",
"text-decoration-line",
"text-decoration-skip-ink",
"text-decoration-style",
"text-decoration-thickness",
"text-emphasis",
"text-emphasis-color",
"text-emphasis-position",
"text-emphasis-style",
"text-indent",
"text-justify",
"text-orientation",
"text-overflow",
"text-rendering",
"text-shadow",
"text-transform",
"text-underline-offset",
"text-underline-position",
"textAlign",
"textAlignLast",
"textAnchor",
"textAutospace",
"textBaseline",
"textCombineUpright",
"textContent",
"textDecoration",
"textDecorationBlink",
"textDecorationColor",
"textDecorationLine",
"textDecorationLineThrough",
"textDecorationNone",
"textDecorationOverline",
"textDecorationSkipInk",
"textDecorationStyle",
"textDecorationThickness",
"textDecorationUnderline",
"textEmphasis",
"textEmphasisColor",
"textEmphasisPosition",
"textEmphasisStyle",
"textIndent",
"textJustify",
"textJustifyTrim",
"textKashida",
"textKashidaSpace",
"textLength",
"textOrientation",
"textOverflow",
"textRendering",
"textShadow",
"textTracks",
"textTransform",
"textUnderlineOffset",
"textUnderlinePosition",
"then",
"threadId",
"threshold",
"thresholds",
"tiltX",
"tiltY",
"time",
"timeEnd",
"timeLog",
"timeOrigin",
"timeRemaining",
"timeStamp",
"timecode",
"timeline",
"timelineTime",
"timeout",
"timestamp",
"timestampOffset",
"timing",
"title",
"to",
"toArray",
"toBlob",
"toDataURL",
"toDateString",
"toElement",
"toExponential",
"toFixed",
"toFloat32Array",
"toFloat64Array",
"toGMTString",
"toISOString",
"toJSON",
"toLocaleDateString",
"toLocaleFormat",
"toLocaleLowerCase",
"toLocaleString",
"toLocaleTimeString",
"toLocaleUpperCase",
"toLowerCase",
"toMatrix",
"toMethod",
"toPrecision",
"toPrimitive",
"toSdp",
"toSource",
"toStaticHTML",
"toString",
"toStringTag",
"toSum",
"toTimeString",
"toUTCString",
"toUpperCase",
"toggle",
"toggleAttribute",
"toggleLongPressEnabled",
"tone",
"toneBuffer",
"tooLong",
"tooShort",
"toolbar",
"top",
"topMargin",
"total",
"totalFrameDelay",
"totalVideoFrames",
"touch-action",
"touchAction",
"touched",
"touches",
"trace",
"track",
"trackVisibility",
"transaction",
"transactions",
"transceiver",
"transferControlToOffscreen",
"transferFromImageBitmap",
"transferImageBitmap",
"transferIn",
"transferOut",
"transferSize",
"transferToImageBitmap",
"transform",
"transform-box",
"transform-origin",
"transform-style",
"transformBox",
"transformFeedbackVaryings",
"transformOrigin",
"transformPoint",
"transformString",
"transformStyle",
"transformToDocument",
"transformToFragment",
"transition",
"transition-delay",
"transition-duration",
"transition-property",
"transition-timing-function",
"transitionDelay",
"transitionDuration",
"transitionProperty",
"transitionTimingFunction",
"translate",
"translateSelf",
"translationX",
"translationY",
"transport",
"trim",
"trimEnd",
"trimLeft",
"trimRight",
"trimStart",
"trueSpeed",
"trunc",
"truncate",
"trustedTypes",
"turn",
"twist",
"type",
"typeDetail",
"typeMismatch",
"typeMustMatch",
"types",
"u2f",
"ubound",
"uint16",
"uint32",
"uint8",
"uint8Clamped",
"undefined",
"unescape",
"uneval",
"unicode",
"unicode-bidi",
"unicodeBidi",
"unicodeRange",
"uniform1f",
"uniform1fv",
"uniform1i",
"uniform1iv",
"uniform1ui",
"uniform1uiv",
"uniform2f",
"uniform2fv",
"uniform2i",
"uniform2iv",
"uniform2ui",
"uniform2uiv",
"uniform3f",
"uniform3fv",
"uniform3i",
"uniform3iv",
"uniform3ui",
"uniform3uiv",
"uniform4f",
"uniform4fv",
"uniform4i",
"uniform4iv",
"uniform4ui",
"uniform4uiv",
"uniformBlockBinding",
"uniformMatrix2fv",
"uniformMatrix2x3fv",
"uniformMatrix2x4fv",
"uniformMatrix3fv",
"uniformMatrix3x2fv",
"uniformMatrix3x4fv",
"uniformMatrix4fv",
"uniformMatrix4x2fv",
"uniformMatrix4x3fv",
"unique",
"uniqueID",
"uniqueNumber",
"unit",
"unitType",
"units",
"unloadEventEnd",
"unloadEventStart",
"unlock",
"unmount",
"unobserve",
"unpause",
"unpauseAnimations",
"unreadCount",
"unregister",
"unregisterContentHandler",
"unregisterProtocolHandler",
"unscopables",
"unselectable",
"unshift",
"unsubscribe",
"unsuspendRedraw",
"unsuspendRedrawAll",
"unwatch",
"unwrapKey",
"upDegrees",
"upX",
"upY",
"upZ",
"update",
"updateCommands",
"updateIce",
"updateInterval",
"updatePlaybackRate",
"updateRenderState",
"updateSettings",
"updateTiming",
"updateViaCache",
"updateWith",
"updated",
"updating",
"upgrade",
"upload",
"uploadTotal",
"uploaded",
"upper",
"upperBound",
"upperOpen",
"uri",
"url",
"urn",
"urns",
"usages",
"usb",
"usbVersionMajor",
"usbVersionMinor",
"usbVersionSubminor",
"useCurrentView",
"useMap",
"useProgram",
"usedSpace",
"user-select",
"userActivation",
"userAgent",
"userChoice",
"userHandle",
"userHint",
"userLanguage",
"userSelect",
"userVisibleOnly",
"username",
"usernameFragment",
"utterance",
"uuid",
"v8BreakIterator",
"vAlign",
"vLink",
"valid",
"validate",
"validateProgram",
"validationMessage",
"validity",
"value",
"valueAsDate",
"valueAsNumber",
"valueAsString",
"valueInSpecifiedUnits",
"valueMissing",
"valueOf",
"valueText",
"valueType",
"values",
"variable",
"variant",
"variationSettings",
"vector-effect",
"vectorEffect",
"velocityAngular",
"velocityExpansion",
"velocityX",
"velocityY",
"vendor",
"vendorId",
"vendorSub",
"verify",
"version",
"vertexAttrib1f",
"vertexAttrib1fv",
"vertexAttrib2f",
"vertexAttrib2fv",
"vertexAttrib3f",
"vertexAttrib3fv",
"vertexAttrib4f",
"vertexAttrib4fv",
"vertexAttribDivisor",
"vertexAttribDivisorANGLE",
"vertexAttribI4i",
"vertexAttribI4iv",
"vertexAttribI4ui",
"vertexAttribI4uiv",
"vertexAttribIPointer",
"vertexAttribPointer",
"vertical",
"vertical-align",
"verticalAlign",
"verticalOverflow",
"vh",
"vibrate",
"vibrationActuator",
"videoBitsPerSecond",
"videoHeight",
"videoTracks",
"videoWidth",
"view",
"viewBox",
"viewBoxString",
"viewTarget",
"viewTargetString",
"viewport",
"viewportAnchorX",
"viewportAnchorY",
"viewportElement",
"views",
"violatedDirective",
"visibility",
"visibilityState",
"visible",
"visualViewport",
"vlinkColor",
"vmax",
"vmin",
"voice",
"voiceURI",
"volume",
"vrml",
"vspace",
"vw",
"w",
"wait",
"waitSync",
"waiting",
"wake",
"wakeLock",
"wand",
"warn",
"wasClean",
"wasDiscarded",
"watch",
"watchAvailability",
"watchPosition",
"webdriver",
"webkitAddKey",
"webkitAlignContent",
"webkitAlignItems",
"webkitAlignSelf",
"webkitAnimation",
"webkitAnimationDelay",
"webkitAnimationDirection",
"webkitAnimationDuration",
"webkitAnimationFillMode",
"webkitAnimationIterationCount",
"webkitAnimationName",
"webkitAnimationPlayState",
"webkitAnimationTimingFunction",
"webkitAppearance",
"webkitAudioContext",
"webkitAudioDecodedByteCount",
"webkitAudioPannerNode",
"webkitBackfaceVisibility",
"webkitBackground",
"webkitBackgroundAttachment",
"webkitBackgroundClip",
"webkitBackgroundColor",
"webkitBackgroundImage",
"webkitBackgroundOrigin",
"webkitBackgroundPosition",
"webkitBackgroundPositionX",
"webkitBackgroundPositionY",
"webkitBackgroundRepeat",
"webkitBackgroundSize",
"webkitBackingStorePixelRatio",
"webkitBorderBottomLeftRadius",
"webkitBorderBottomRightRadius",
"webkitBorderImage",
"webkitBorderImageOutset",
"webkitBorderImageRepeat",
"webkitBorderImageSlice",
"webkitBorderImageSource",
"webkitBorderImageWidth",
"webkitBorderRadius",
"webkitBorderTopLeftRadius",
"webkitBorderTopRightRadius",
"webkitBoxAlign",
"webkitBoxDirection",
"webkitBoxFlex",
"webkitBoxOrdinalGroup",
"webkitBoxOrient",
"webkitBoxPack",
"webkitBoxShadow",
"webkitBoxSizing",
"webkitCancelAnimationFrame",
"webkitCancelFullScreen",
"webkitCancelKeyRequest",
"webkitCancelRequestAnimationFrame",
"webkitClearResourceTimings",
"webkitClosedCaptionsVisible",
"webkitConvertPointFromNodeToPage",
"webkitConvertPointFromPageToNode",
"webkitCreateShadowRoot",
"webkitCurrentFullScreenElement",
"webkitCurrentPlaybackTargetIsWireless",
"webkitDecodedFrameCount",
"webkitDirectionInvertedFromDevice",
"webkitDisplayingFullscreen",
"webkitDroppedFrameCount",
"webkitEnterFullScreen",
"webkitEnterFullscreen",
"webkitEntries",
"webkitExitFullScreen",
"webkitExitFullscreen",
"webkitExitPointerLock",
"webkitFilter",
"webkitFlex",
"webkitFlexBasis",
"webkitFlexDirection",
"webkitFlexFlow",
"webkitFlexGrow",
"webkitFlexShrink",
"webkitFlexWrap",
"webkitFullScreenKeyboardInputAllowed",
"webkitFullscreenElement",
"webkitFullscreenEnabled",
"webkitGenerateKeyRequest",
"webkitGetAsEntry",
"webkitGetDatabaseNames",
"webkitGetEntries",
"webkitGetEntriesByName",
"webkitGetEntriesByType",
"webkitGetFlowByName",
"webkitGetGamepads",
"webkitGetImageDataHD",
"webkitGetNamedFlows",
"webkitGetRegionFlowRanges",
"webkitGetUserMedia",
"webkitHasClosedCaptions",
"webkitHidden",
"webkitIDBCursor",
"webkitIDBDatabase",
"webkitIDBDatabaseError",
"webkitIDBDatabaseException",
"webkitIDBFactory",
"webkitIDBIndex",
"webkitIDBKeyRange",
"webkitIDBObjectStore",
"webkitIDBRequest",
"webkitIDBTransaction",
"webkitImageSmoothingEnabled",
"webkitIndexedDB",
"webkitInitMessageEvent",
"webkitIsFullScreen",
"webkitJustifyContent",
"webkitKeys",
"webkitLineClamp",
"webkitLineDashOffset",
"webkitLockOrientation",
"webkitMask",
"webkitMaskClip",
"webkitMaskComposite",
"webkitMaskImage",
"webkitMaskOrigin",
"webkitMaskPosition",
"webkitMaskPositionX",
"webkitMaskPositionY",
"webkitMaskRepeat",
"webkitMaskSize",
"webkitMatchesSelector",
"webkitMediaStream",
"webkitNotifications",
"webkitOfflineAudioContext",
"webkitOrder",
"webkitOrientation",
"webkitPeerConnection00",
"webkitPersistentStorage",
"webkitPerspective",
"webkitPerspectiveOrigin",
"webkitPointerLockElement",
"webkitPostMessage",
"webkitPreservesPitch",
"webkitPutImageDataHD",
"webkitRTCPeerConnection",
"webkitRegionOverset",
"webkitRelativePath",
"webkitRequestAnimationFrame",
"webkitRequestFileSystem",
"webkitRequestFullScreen",
"webkitRequestFullscreen",
"webkitRequestPointerLock",
"webkitResolveLocalFileSystemURL",
"webkitSetMediaKeys",
"webkitSetResourceTimingBufferSize",
"webkitShadowRoot",
"webkitShowPlaybackTargetPicker",
"webkitSlice",
"webkitSpeechGrammar",
"webkitSpeechGrammarList",
"webkitSpeechRecognition",
"webkitSpeechRecognitionError",
"webkitSpeechRecognitionEvent",
"webkitStorageInfo",
"webkitSupportsFullscreen",
"webkitTemporaryStorage",
"webkitTextFillColor",
"webkitTextSizeAdjust",
"webkitTextStroke",
"webkitTextStrokeColor",
"webkitTextStrokeWidth",
"webkitTransform",
"webkitTransformOrigin",
"webkitTransformStyle",
"webkitTransition",
"webkitTransitionDelay",
"webkitTransitionDuration",
"webkitTransitionProperty",
"webkitTransitionTimingFunction",
"webkitURL",
"webkitUnlockOrientation",
"webkitUserSelect",
"webkitVideoDecodedByteCount",
"webkitVisibilityState",
"webkitWirelessVideoPlaybackDisabled",
"webkitdirectory",
"webkitdropzone",
"webstore",
"weight",
"whatToShow",
"wheelDelta",
"wheelDeltaX",
"wheelDeltaY",
"whenDefined",
"which",
"white-space",
"whiteSpace",
"wholeText",
"widows",
"width",
"will-change",
"willChange",
"willValidate",
"window",
"withCredentials",
"word-break",
"word-spacing",
"word-wrap",
"wordBreak",
"wordSpacing",
"wordWrap",
"workerStart",
"wrap",
"wrapKey",
"writable",
"writableAuxiliaries",
"write",
"writeText",
"writeValue",
"writeWithoutResponse",
"writeln",
"writing-mode",
"writingMode",
"x",
"x1",
"x2",
"xChannelSelector",
"xmlEncoding",
"xmlStandalone",
"xmlVersion",
"xmlbase",
"xmllang",
"xmlspace",
"xor",
"xr",
"y",
"y1",
"y2",
"yChannelSelector",
"yandex",
"z",
"z-index",
"zIndex",
"zoom",
"zoomAndPan",
"zoomRectScreen"
];
function addStrings(node, add) {
node.walk(new TreeWalker(function(node) {
return node instanceof AST_Sequence ? addStrings(node.tail_node(), add) : node instanceof AST_String ? add(node.value) : node instanceof AST_Conditional && (addStrings(node.consequent, add), addStrings(node.alternative, add)), !0;
}));
}
var to_ascii = "undefined" == typeof atob ? function(b64) {
return Buffer.from(b64, "base64").toString();
} : atob, to_base64 = "undefined" == typeof btoa ? function(str) {
return Buffer.from(str).toString("base64");
} : btoa;
function set_shorthand(name, options, keys) {
options[name] && keys.forEach(function(key) {
!options[key] || ("object" != typeof options[key] && (options[key] = {}), name in options[key] || (options[key][name] = options[name]));
});
}
function init_cache(cache) {
!cache || ("props" in cache ? cache.props instanceof Map || (cache.props = function(obj) {
var map = new Map();
for(var key in obj)HOP(obj, key) && "$" === key.charAt(0) && map.set(key.substr(1), obj[key]);
return map;
}(cache.props)) : cache.props = new Map());
}
function cache_to_json(cache) {
var map, obj;
return {
props: (map = cache.props, obj = Object.create(null), map.forEach(function(value, key) {
obj["$" + key] = value;
}), obj)
};
}
async function minify(files, options, _fs_module) {
_fs_module && "object" == typeof process && process.env && "string" == typeof process.env.TERSER_DEBUG_DIR && function(files, options, fs, debug_folder) {
if (!(fs && fs.writeFileSync && fs.mkdirSync)) return;
try {
fs.mkdirSync(debug_folder);
} catch (e) {
if ("EEXIST" !== e.code) throw e;
}
const log_path = `${debug_folder}/terser-debug-${9999999 * Math.random() | 0}.log`, options_str = JSON.stringify(options = options || {}, (_key, thing)=>"function" == typeof thing ? "[Function " + thing.toString() + "]" : thing instanceof RegExp ? "[RegExp " + thing.toString() + "]" : thing, 4), files_str = (file)=>"object" == typeof file && options.parse && options.parse.spidermonkey ? JSON.stringify(file, null, 2) : "object" == typeof file ? Object.keys(file).map((key)=>key + ": " + files_str(file[key])).join("\n\n") : "string" == typeof file ? "```\n" + file + "\n```" : file;
fs.writeFileSync(log_path, "Options: \n" + options_str + "\n\nInput files:\n\n" + files_str(files) + "\n");
}(files, options, _fs_module, process.env.TERSER_DEBUG_DIR);
var quoted_props, toplevel, timings = (options = defaults(options, {
compress: {},
ecma: void 0,
enclose: !1,
ie8: !1,
keep_classnames: void 0,
keep_fnames: !1,
mangle: {},
module: !1,
nameCache: null,
output: null,
format: null,
parse: {},
rename: void 0,
safari10: !1,
sourceMap: !1,
spidermonkey: !1,
timings: !1,
toplevel: !1,
warnings: !1,
wrap: !1
}, !0)).timings && {
start: Date.now()
};
if (void 0 === options.keep_classnames && (options.keep_classnames = options.keep_fnames), void 0 === options.rename && (options.rename = options.compress && options.mangle), options.output && options.format) throw Error("Please only specify either output or format option, preferrably format.");
if (options.format = options.format || options.output || {}, set_shorthand("ecma", options, [
"parse",
"compress",
"format"
]), set_shorthand("ie8", options, [
"compress",
"mangle",
"format"
]), set_shorthand("keep_classnames", options, [
"compress",
"mangle"
]), set_shorthand("keep_fnames", options, [
"compress",
"mangle"
]), set_shorthand("module", options, [
"parse",
"compress",
"mangle"
]), set_shorthand("safari10", options, [
"mangle",
"format"
]), set_shorthand("toplevel", options, [
"compress",
"mangle"
]), set_shorthand("warnings", options, [
"compress"
]), options.mangle && (options.mangle = defaults(options.mangle, {
cache: options.nameCache && (options.nameCache.vars || {}),
eval: !1,
ie8: !1,
keep_classnames: !1,
keep_fnames: !1,
module: !1,
nth_identifier: base54,
properties: !1,
reserved: [],
safari10: !1,
toplevel: !1
}, !0), !options.mangle.properties || ("object" != typeof options.mangle.properties && (options.mangle.properties = {}), options.mangle.properties.keep_quoted && (Array.isArray(quoted_props = options.mangle.properties.reserved) || (quoted_props = []), options.mangle.properties.reserved = quoted_props), !options.nameCache || "cache" in options.mangle.properties || (options.mangle.properties.cache = options.nameCache.props || {})), init_cache(options.mangle.cache), init_cache(options.mangle.properties.cache)), options.sourceMap && (options.sourceMap = defaults(options.sourceMap, {
asObject: !1,
content: null,
filename: null,
includeSources: !1,
root: null,
url: null
}, !0)), timings && (timings.parse = Date.now()), files instanceof AST_Toplevel) toplevel = files;
else {
if (("string" == typeof files || options.parse.spidermonkey && !Array.isArray(files)) && (files = [
files
]), options.parse = options.parse || {}, options.parse.toplevel = null, options.parse.spidermonkey) options.parse.toplevel = AST_Node.from_mozilla_ast(Object.keys(files).reduce(function(toplevel, name) {
return toplevel ? (toplevel.body = toplevel.body.concat(files[name].body), toplevel) : files[name];
}, null));
else for(var name in delete options.parse.spidermonkey, files)if (HOP(files, name) && (options.parse.filename = name, options.parse.toplevel = parse(files[name], options.parse), options.sourceMap && "inline" == options.sourceMap.content)) {
if (Object.keys(files).length > 1) throw Error("inline source map only works with singular input");
options.sourceMap.content = function(code) {
var match = /(?:^|[^.])\/\/# sourceMappingURL=data:application\/json(;[\w=-]*)?;base64,([+/0-9A-Za-z]*=*)\s*$/.exec(code);
return match ? to_ascii(match[2]) : (console.warn("inline source map not found"), null);
}(files[name]);
}
toplevel = options.parse.toplevel;
}
quoted_props && "strict" !== options.mangle.properties.keep_quoted && function(ast, reserved) {
function add(name) {
push_uniq(reserved, name);
}
ast.walk(new TreeWalker(function(node) {
node instanceof AST_ObjectKeyVal && node.quote ? add(node.key) : node instanceof AST_ObjectProperty && node.quote ? add(node.key.name) : node instanceof AST_Sub && addStrings(node.property, add);
}));
}(toplevel, quoted_props), options.wrap && (toplevel = toplevel.wrap_commonjs(options.wrap)), options.enclose && (toplevel = toplevel.wrap_enclose(options.enclose)), timings && (timings.rename = Date.now()), timings && (timings.compress = Date.now()), options.compress && (toplevel = new Compressor(options.compress, {
mangle_options: options.mangle
}).compress(toplevel)), timings && (timings.scope = Date.now()), options.mangle && toplevel.figure_out_scope(options.mangle), timings && (timings.mangle = Date.now()), options.mangle && (toplevel.compute_char_frequency(options.mangle), toplevel.mangle_names(options.mangle), toplevel = function(ast, options) {
var cprivate = -1, private_cache = new Map(), nth_identifier = options.nth_identifier || base54;
return ast = ast.transform(new TreeTransformer(function(node) {
node instanceof AST_ClassPrivateProperty || node instanceof AST_PrivateMethod || node instanceof AST_PrivateGetter || node instanceof AST_PrivateSetter ? node.key.name = mangle_private(node.key.name) : node instanceof AST_DotHash && (node.property = mangle_private(node.property));
}));
function mangle_private(name) {
let mangled = private_cache.get(name);
return mangled || (mangled = nth_identifier.get(++cprivate), private_cache.set(name, mangled)), mangled;
}
}(toplevel, options.mangle)), timings && (timings.properties = Date.now()), options.mangle && options.mangle.properties && (toplevel = function(ast, options) {
var cache, debug_name_suffix, nth_identifier = (options = defaults(options, {
builtins: !1,
cache: null,
debug: !1,
keep_quoted: !1,
nth_identifier: base54,
only_cache: !1,
regex: null,
reserved: null,
undeclared: !1
}, !0)).nth_identifier, reserved_option = options.reserved;
Array.isArray(reserved_option) || (reserved_option = [
reserved_option
]);
var reserved = new Set(reserved_option);
options.builtins || /***********************************************************************
A JavaScript tokenizer / parser / beautifier / compressor.
https://github.com/mishoo/UglifyJS2
-------------------------------- (C) ---------------------------------
Author: Mihai Bazon
<mihai.bazon@gmail.com>
http://mihai.bazon.net/blog
Distributed under the BSD license:
Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
***********************************************************************/ function(reserved) {
domprops.forEach(add);
var objects = {}, global_ref = "object" == typeof global ? global : self;
function add(name) {
reserved.add(name);
}
[
"Symbol",
"Map",
"Promise",
"Proxy",
"Reflect",
"Set",
"WeakMap",
"WeakSet"
].forEach(function(new_global) {
objects[new_global] = global_ref[new_global] || Function();
}), [
"null",
"true",
"false",
"NaN",
"Infinity",
"-Infinity",
"undefined"
].forEach(add), [
Object,
Array,
Function,
Number,
String,
Boolean,
Error,
Math,
Date,
RegExp,
objects.Symbol,
ArrayBuffer,
DataView,
decodeURI,
decodeURIComponent,
encodeURI,
encodeURIComponent,
eval,
EvalError,
Float32Array,
Float64Array,
Int8Array,
Int16Array,
Int32Array,
isFinite,
isNaN,
JSON,
objects.Map,
parseFloat,
parseInt,
objects.Promise,
objects.Proxy,
RangeError,
ReferenceError,
objects.Reflect,
objects.Set,
SyntaxError,
TypeError,
Uint8Array,
Uint8ClampedArray,
Uint16Array,
Uint32Array,
URIError,
objects.WeakMap,
objects.WeakSet
].forEach(function(ctor) {
Object.getOwnPropertyNames(ctor).map(add), ctor.prototype && Object.getOwnPropertyNames(ctor.prototype).map(add);
});
}(reserved);
var cname = -1;
cache = options.cache ? options.cache.props : new Map();
var regex = options.regex && new RegExp(options.regex), debug = !1 !== options.debug;
debug && (debug_name_suffix = !0 === options.debug ? "" : options.debug);
var names_to_mangle = new Set(), unmangleable = new Set();
// Track each already-mangled name to prevent nth_identifier from generating
// the same name.
cache.forEach((mangled_name)=>unmangleable.add(mangled_name));
var keep_quoted = !!options.keep_quoted;
// step 2: transform the tree, renaming properties
return(// step 1: find candidates to mangle
ast.walk(new TreeWalker(function(node) {
if (node instanceof AST_ClassPrivateProperty || node instanceof AST_PrivateMethod || node instanceof AST_PrivateGetter || node instanceof AST_PrivateSetter || node instanceof AST_DotHash) ;
else if (node instanceof AST_ObjectKeyVal) "string" != typeof node.key || keep_quoted && node.quote || add(node.key);
else if (node instanceof AST_ObjectProperty) // setter or getter, since KeyVal is handled above
keep_quoted && node.quote || add(node.key.name);
else if (node instanceof AST_Dot) {
var declared = !!options.undeclared;
if (!declared) {
for(var root = node; root.expression;)root = root.expression;
declared = !(root.thedef && root.thedef.undeclared);
}
!declared || keep_quoted && node.quote || add(node.property);
} else node instanceof AST_Sub ? keep_quoted || addStrings(node.property, add) : node instanceof AST_Call && "Object.defineProperty" == node.expression.print_to_string() ? addStrings(node.args[1], add) : node instanceof AST_Binary && "in" === node.operator && addStrings(node.left, add);
})), ast.transform(new TreeTransformer(function(node) {
node instanceof AST_ClassPrivateProperty || node instanceof AST_PrivateMethod || node instanceof AST_PrivateGetter || node instanceof AST_PrivateSetter || node instanceof AST_DotHash || (node instanceof AST_ObjectKeyVal ? "string" != typeof node.key || keep_quoted && node.quote || (node.key = mangle(node.key)) : node instanceof AST_ObjectProperty ? keep_quoted && node.quote || (node.key.name = mangle(node.key.name)) : node instanceof AST_Dot ? keep_quoted && node.quote || (node.property = mangle(node.property)) : !keep_quoted && node instanceof AST_Sub ? node.property = mangleStrings(node.property) : node instanceof AST_Call && "Object.defineProperty" == node.expression.print_to_string() ? node.args[1] = mangleStrings(node.args[1]) : node instanceof AST_Binary && "in" === node.operator && (node.left = mangleStrings(node.left)));
})));
// only function declarations after this line
function can_mangle(name) {
return !(unmangleable.has(name) || reserved.has(name)) && (options.only_cache ? cache.has(name) : !/^-?[0-9]+(\.[0-9]+)?(e[+-][0-9]+)?$/.test(name));
}
function should_mangle(name) {
return !(regex && !regex.test(name) || reserved.has(name)) && (cache.has(name) || names_to_mangle.has(name));
}
function add(name) {
can_mangle(name) && names_to_mangle.add(name), should_mangle(name) || unmangleable.add(name);
}
function mangle(name) {
if (!should_mangle(name)) return name;
var mangled = cache.get(name);
if (!mangled) {
if (debug) {
// debug mode: use a prefix and suffix to preserve readability, e.g. o.foo -> o._$foo$NNN_.
var debug_mangled = "_$" + name + "$" + debug_name_suffix + "_";
can_mangle(debug_mangled) && (mangled = debug_mangled);
}
// either debug mode is off, or it is on and we could not use the mangled name
if (!mangled) do mangled = nth_identifier.get(++cname);
while (!can_mangle(mangled))
cache.set(name, mangled);
}
return mangled;
}
function mangleStrings(node) {
return node.transform(new TreeTransformer(function(node) {
if (node instanceof AST_Sequence) {
var last = node.expressions.length - 1;
node.expressions[last] = mangleStrings(node.expressions[last]);
} else node instanceof AST_String ? node.value = mangle(node.value) : node instanceof AST_Conditional && (node.consequent = mangleStrings(node.consequent), node.alternative = mangleStrings(node.alternative));
return node;
}));
}
}(toplevel, options.mangle.properties)), timings && (timings.format = Date.now());
var result = {};
if (options.format.ast && (result.ast = toplevel), options.format.spidermonkey && (result.ast = toplevel.to_mozilla_ast()), !HOP(options.format, "code") || options.format.code) {
if (options.sourceMap && (options.format.source_map = await SourceMap({
file: options.sourceMap.filename,
orig: options.sourceMap.content,
root: options.sourceMap.root
}), options.sourceMap.includeSources)) {
if (files instanceof AST_Toplevel) throw Error("original source content unavailable");
for(var name in files)HOP(files, name) && options.format.source_map.get().setSourceContent(name, files[name]);
}
delete options.format.ast, delete options.format.code, delete options.format.spidermonkey;
var stream = OutputStream(options.format);
if (toplevel.print(stream), result.code = stream.get(), options.sourceMap) {
if (options.sourceMap.asObject ? result.map = options.format.source_map.get().toJSON() : result.map = options.format.source_map.toString(), "inline" == options.sourceMap.url) {
var sourceMap = "object" == typeof result.map ? JSON.stringify(result.map) : result.map;
result.code += "\n//# sourceMappingURL=data:application/json;charset=utf-8;base64," + to_base64(sourceMap);
} else options.sourceMap.url && (result.code += "\n//# sourceMappingURL=" + options.sourceMap.url);
}
}
return options.nameCache && options.mangle && (options.mangle.cache && (options.nameCache.vars = cache_to_json(options.mangle.cache)), options.mangle.properties && options.mangle.properties.cache && (options.nameCache.props = cache_to_json(options.mangle.properties.cache))), options.format && options.format.source_map && options.format.source_map.destroy(), timings && (timings.end = Date.now(), result.timings = {
parse: 1e-3 * (timings.rename - timings.parse),
rename: 1e-3 * (timings.compress - timings.rename),
compress: 1e-3 * (timings.scope - timings.compress),
scope: 1e-3 * (timings.mangle - timings.scope),
mangle: 1e-3 * (timings.properties - timings.mangle),
properties: 1e-3 * (timings.format - timings.properties),
format: 1e-3 * (timings.end - timings.format),
total: 1e-3 * (timings.end - timings.start)
}), result;
}
async function run_cli({ program, packageJson, fs, path }) {
let filesList;
const skip_keys = new Set([
"cname",
"parent_scope",
"scope",
"uses_eval",
"uses_with"
]);
var base, files = {}, options = {
compress: !1,
mangle: !1
};
const default_options = await _default_options();
if (program.version(packageJson.name + " " + packageJson.version), program.parseArgv = program.parse, program.parse = void 0, process.argv.includes("ast") ? program.helpInformation = function() {
var out = OutputStream({
beautify: !0
});
return function doitem(ctor) {
out.print("AST_" + ctor.TYPE);
const props = ctor.SELF_PROPS.filter((prop)=>!/^\$/.test(prop));
props.length > 0 && (out.space(), out.with_parens(function() {
props.forEach(function(prop, i) {
i && out.space(), out.print(prop);
});
})), ctor.documentation && (out.space(), out.print_string(ctor.documentation)), ctor.SUBCLASSES.length > 0 && (out.space(), out.with_block(function() {
ctor.SUBCLASSES.forEach(function(ctor) {
out.indent(), doitem(ctor), out.newline();
});
}));
}(AST_Node), out + "\n";
} : process.argv.includes("options") && (program.helpInformation = function() {
var text = [];
for(var option in default_options)text.push("--" + ("sourceMap" === option ? "source-map" : option) + " options:"), text.push(format_object(default_options[option])), text.push("");
return text.join("\n");
}), program.option("-p, --parse <options>", "Specify parser options.", parse_js()), program.option("-c, --compress [options]", "Enable compressor/specify compressor options.", parse_js()), program.option("-m, --mangle [options]", "Mangle names/specify mangler options.", parse_js()), program.option("--mangle-props [options]", "Mangle properties/specify mangler options.", parse_js()), program.option("-f, --format [options]", "Format options.", parse_js()), program.option("-b, --beautify [options]", "Alias for --format.", parse_js()), program.option("-o, --output <file>", "Output file (default STDOUT)."), program.option("--comments [filter]", "Preserve copyright comments in the output."), program.option("--config-file <file>", "Read minify() options from JSON file."), program.option("-d, --define <expr>[=value]", "Global definitions.", parse_js("define")), program.option("--ecma <version>", "Specify ECMAScript release: 5, 2015, 2016 or 2017..."), program.option("-e, --enclose [arg[,...][:value[,...]]]", "Embed output in a big function with configurable arguments and values."), program.option("--ie8", "Support non-standard Internet Explorer 8."), program.option("--keep-classnames", "Do not mangle/drop class names."), program.option("--keep-fnames", "Do not mangle/drop function names. Useful for code relying on Function.prototype.name."), program.option("--module", "Input is an ES6 module"), program.option("--name-cache <file>", "File to hold mangled name mappings."), program.option("--rename", "Force symbol expansion."), program.option("--no-rename", "Disable symbol expansion."), program.option("--safari10", "Support non-standard Safari 10."), program.option("--source-map [options]", "Enable source map/specify source map options.", parse_js()), program.option("--timings", "Display operations run time on STDERR."), program.option("--toplevel", "Compress and/or mangle variables in toplevel scope."), program.option("--wrap <name>", "Embed everything as a function with “exports” corresponding to “name” globally."), program.arguments("[files...]").parseArgv(process.argv), program.configFile && (options = JSON.parse(read_file(program.configFile))), !program.output && program.sourceMap && "inline" != program.sourceMap.url && fatal("ERROR: cannot write source map to STDOUT"), [
"compress",
"enclose",
"ie8",
"mangle",
"module",
"safari10",
"sourceMap",
"toplevel",
"wrap"
].forEach(function(name) {
name in program && (options[name] = program[name]);
}), "ecma" in program) {
program.ecma != (0 | program.ecma) && fatal("ERROR: ecma must be an integer");
const ecma = 0 | program.ecma;
ecma > 5 && ecma < 2015 ? options.ecma = ecma + 2009 : options.ecma = ecma;
}
if (program.format || program.beautify) {
const chosenOption = program.format || program.beautify;
options.format = "object" == typeof chosenOption ? chosenOption : {};
}
if (program.comments && ("object" != typeof options.format && (options.format = {}), options.format.comments = "string" == typeof program.comments ? "false" != program.comments && program.comments : "some"), program.define) for(var expr in "object" != typeof options.compress && (options.compress = {}), "object" != typeof options.compress.global_defs && (options.compress.global_defs = {}), program.define)options.compress.global_defs[expr] = program.define[expr];
program.keepClassnames && (options.keep_classnames = !0), program.keepFnames && (options.keep_fnames = !0), program.mangleProps && (program.mangleProps.domprops ? delete program.mangleProps.domprops : ("object" != typeof program.mangleProps && (program.mangleProps = {}), Array.isArray(program.mangleProps.reserved) || (program.mangleProps.reserved = [])), "object" != typeof options.mangle && (options.mangle = {}), options.mangle.properties = program.mangleProps), program.nameCache && (options.nameCache = JSON.parse(read_file(program.nameCache, "{}"))), "ast" == program.output && (options.format = {
ast: !0,
code: !1
}), program.parse && (program.parse.acorn || program.parse.spidermonkey ? program.sourceMap && "inline" == program.sourceMap.content && fatal("ERROR: inline source map only works with built-in parser") : options.parse = program.parse), ~program.rawArgs.indexOf("--rename") ? options.rename = !0 : program.rename || (options.rename = !1);
let convert_path = (name)=>name;
function convert_ast(fn) {
return AST_Node.from_mozilla_ast(Object.keys(files).reduce(fn, null));
}
async function run_cli() {
let result;
var content = program.sourceMap && program.sourceMap.content;
content && "inline" !== content && (options.sourceMap.content = read_file(content, content)), program.timings && (options.timings = !0);
try {
program.parse && (program.parse.acorn ? files = convert_ast(function(toplevel, name) {
return require("acorn").parse(files[name], {
ecmaVersion: 2018,
locations: !0,
program: toplevel,
sourceFile: name,
sourceType: options.module || program.parse.module ? "module" : "script"
});
}) : program.parse.spidermonkey && (files = convert_ast(function(toplevel, name) {
var obj = JSON.parse(files[name]);
return toplevel ? (toplevel.body = toplevel.body.concat(obj.body), toplevel) : obj;
})));
} catch (ex) {
fatal(ex);
}
try {
result = await minify(files, options, fs);
} catch (ex) {
if ("SyntaxError" == ex.name) {
print_error("Parse error at " + ex.filename + ":" + ex.line + "," + ex.col);
var col = ex.col, lines = files[ex.filename].split(/\r?\n/), line = lines[ex.line - 1];
line || col || (col = (line = lines[ex.line - 2]).length), line && (col > 70 && (line = line.slice(col - 70), col = 70), print_error(line.slice(0, 80)), print_error(line.slice(0, col).replace(/\S/g, " ") + "^"));
}
ex.defs && (print_error("Supported options:"), print_error(format_object(ex.defs))), fatal(ex);
return;
}
if ("ast" == program.output) options.compress || options.mangle || result.ast.figure_out_scope({}), console.log(JSON.stringify(result.ast, function(key, value) {
if (value) switch(key){
case "thedef":
return symdef(value);
case "enclosed":
return value.length ? value.map(symdef) : void 0;
case "variables":
case "globals":
var result;
return value.size ? (result = [], value.forEach(function(def) {
result.push(symdef(def));
}), result) : void 0;
}
if (!skip_keys.has(key) && !(value instanceof AST_Token) && !(value instanceof Map)) {
if (value instanceof AST_Node) {
var result1 = {
_class: "AST_" + value.TYPE
};
return value.block_scope && (result1.variables = value.block_scope.variables, result1.enclosed = value.block_scope.enclosed), value.CTOR.PROPS.forEach(function(prop) {
result1[prop] = value[prop];
}), result1;
}
return value;
}
}, 2));
else if ("spidermonkey" == program.output) try {
const minified = await minify(result.code, {
compress: !1,
mangle: !1,
format: {
ast: !0,
code: !1
}
}, fs);
console.log(JSON.stringify(minified.ast.to_mozilla_ast(), null, 2));
} catch (ex) {
fatal(ex);
return;
}
else program.output ? (fs.writeFileSync(program.output, result.code), options.sourceMap && "inline" !== options.sourceMap.url && result.map && fs.writeFileSync(program.output + ".map", result.map)) : console.log(result.code);
if (program.nameCache && fs.writeFileSync(program.nameCache, JSON.stringify(options.nameCache)), result.timings) for(var phase in result.timings)print_error("- " + phase + ": " + result.timings[phase].toFixed(3) + "s");
}
function fatal(message) {
message instanceof Error && (message = message.stack.replace(/^\S*?Error:/, "ERROR:")), print_error(message), process.exit(1);
}
function read_file(path, default_value) {
try {
return fs.readFileSync(path, "utf8");
} catch (ex) {
if (("ENOENT" == ex.code || "ENAMETOOLONG" == ex.code) && null != default_value) return default_value;
fatal(ex);
}
}
function parse_js(flag) {
return function(value, options) {
options = options || {};
try {
walk(parse(value, {
expression: !0
}), (node)=>{
if (node instanceof AST_Assign) {
var name = node.left.print_to_string(), value = node.right;
return flag ? options[name] = value : value instanceof AST_Array ? options[name] = value.elements.map(to_string) : value instanceof AST_RegExp ? (value = value.value, options[name] = new RegExp(value.source, value.flags)) : options[name] = to_string(value), !0;
}
if (node instanceof AST_Symbol || node instanceof AST_PropAccess) {
var name = node.print_to_string();
return options[name] = !0, !0;
}
if (!(node instanceof AST_Sequence)) throw node;
function to_string(value) {
return value instanceof AST_Constant ? value.getValue() : value.print_to_string({
quote_keys: !0
});
}
});
} catch (ex) {
flag ? fatal("Error parsing arguments for '" + flag + "': " + value) : options[value] = null;
}
return options;
};
}
function symdef(def) {
var ret = 1e6 + def.id + " " + def.name;
return def.mangled_name && (ret += " " + def.mangled_name), ret;
}
function format_object(obj) {
var lines = [], padding = "";
return Object.keys(obj).map(function(name) {
return padding.length < name.length && (padding = Array(name.length + 1).join(" ")), [
name,
JSON.stringify(obj[name])
];
}).forEach(function(tokens) {
lines.push(" " + tokens[0] + padding.slice(tokens[0].length - 2) + tokens[1]);
}), lines.join("\n");
}
function print_error(msg) {
process.stderr.write(msg), process.stderr.write("\n");
}
"object" == typeof program.sourceMap && "base" in program.sourceMap && (base = program.sourceMap.base, delete options.sourceMap.base, convert_path = function(name) {
return path.relative(base, name);
}), options.files && options.files.length ? (filesList = options.files, delete options.files) : program.args.length && (filesList = program.args), filesList ? // A file glob function that only supports "*" and "?" wildcards in the basename.
// Example: "foo/bar/*baz??.*.js"
// Argument `glob` may be a string or an array of strings.
// Returns an array of strings. Garbage in, garbage out.
(function simple_glob(glob) {
if (Array.isArray(glob)) return [].concat.apply([], glob.map(simple_glob));
if (glob && glob.match(/[*?]/)) {
var dir = path.dirname(glob);
try {
var entries = fs.readdirSync(dir);
} catch (ex) {}
if (entries) {
var rx = RegExp("^" + path.basename(glob).replace(/[.+^$[\]\\(){}]/g, "\\$&").replace(/\*/g, "[^/\\\\]*").replace(/\?/g, "[^/\\\\]") + "$", "win32" === process.platform ? "i" : ""), results = entries.filter(function(name) {
return rx.test(name);
}).map(function(name) {
return path.join(dir, name);
});
if (results.length) return results;
}
}
return [
glob
];
})(filesList).forEach(function(name) {
files[convert_path(name)] = read_file(name);
}) : await new Promise((resolve)=>{
var chunks = [];
process.stdin.setEncoding("utf8"), process.stdin.on("data", function(chunk) {
chunks.push(chunk);
}).on("end", function() {
files = [
chunks.join("")
], resolve();
}), process.stdin.resume();
}), await run_cli();
}
async function _default_options() {
const defs = {};
return Object.keys(infer_options({
0: 0
})).forEach((component)=>{
const options = infer_options({
[component]: {
0: 0
}
});
options && (defs[component] = options);
}), defs;
}
async function infer_options(options) {
try {
await minify("", options);
} catch (error) {
return error.defs;
}
}
exports1._default_options = _default_options, exports1._run_cli = run_cli, exports1.minify = minify;
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/benches-full/vue.js | JavaScript | !/*!
* Vue.js v2.6.12
* (c) 2014-2020 Evan You
* Released under the MIT License.
*/ function(global1, factory) {
'object' == typeof exports && 'undefined' != typeof module ? module.exports = factory() : 'function' == typeof define && define.amd ? define(factory) : (global1 = global1 || self).Vue = factory();
}(this, function() {
'use strict';
/* */ var Vue, cid, configDef, dataDef, propsDef, hookRE, baseCompile, _isServer, _Set, timerFunc, mark, measure, initProxy, target, len, str, chr, index$1, expressionPos, expressionEndPos, warn$1, target$1, svgContainer, emptyStyle, decoder, warn$2, delimiters, transforms, preTransforms, postTransforms, platformIsPreTag, platformMustUseProp, platformGetTagNamespace, maybeComponent, isStaticKey, isPlatformReservedTag, div, emptyObject = Object.freeze({});
// These helpers produce better VM code in JS engines due to their
// explicitness and function inlining.
function isUndef(v) {
return null == v;
}
function isDef(v) {
return null != v;
}
function isTrue(v) {
return !0 === v;
}
/**
* Check if value is primitive.
*/ function isPrimitive(value) {
return 'string' == typeof value || 'number' == typeof value || // $flow-disable-line
'symbol' == typeof value || 'boolean' == typeof value;
}
/**
* Quick object check - this is primarily used to tell
* Objects from primitive values when we know the value
* is a JSON-compliant type.
*/ function isObject(obj) {
return null !== obj && 'object' == typeof obj;
}
/**
* Get the raw type string of a value, e.g., [object Object].
*/ var _toString = Object.prototype.toString;
function toRawType(value) {
return _toString.call(value).slice(8, -1);
}
/**
* Strict object type check. Only returns true
* for plain JavaScript objects.
*/ function isPlainObject(obj) {
return '[object Object]' === _toString.call(obj);
}
function isRegExp(v) {
return '[object RegExp]' === _toString.call(v);
}
/**
* Check if val is a valid array index.
*/ function isValidArrayIndex(val) {
var n = parseFloat(String(val));
return n >= 0 && Math.floor(n) === n && isFinite(val);
}
function isPromise(val) {
return isDef(val) && 'function' == typeof val.then && 'function' == typeof val.catch;
}
/**
* Convert a value to a string that is actually rendered.
*/ function toString(val) {
return null == val ? '' : Array.isArray(val) || isPlainObject(val) && val.toString === _toString ? JSON.stringify(val, null, 2) : String(val);
}
/**
* Convert an input value to a number for persistence.
* If the conversion fails, return original string.
*/ function toNumber(val) {
var n = parseFloat(val);
return isNaN(n) ? val : n;
}
/**
* Make a map and return a function for checking if a key
* is in that map.
*/ function makeMap(str, expectsLowerCase) {
for(var map = Object.create(null), list = str.split(','), i = 0; i < list.length; i++)map[list[i]] = !0;
return expectsLowerCase ? function(val) {
return map[val.toLowerCase()];
} : function(val) {
return map[val];
};
}
/**
* Check if a tag is a built-in tag.
*/ var isBuiltInTag = makeMap('slot,component', !0), isReservedAttribute = makeMap('key,ref,slot,slot-scope,is');
/**
* Remove an item from an array.
*/ function remove(arr, item) {
if (arr.length) {
var index = arr.indexOf(item);
if (index > -1) return arr.splice(index, 1);
}
}
/**
* Check whether an object has the property.
*/ var hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwn(obj, key) {
return hasOwnProperty.call(obj, key);
}
/**
* Create a cached version of a pure function.
*/ function cached(fn) {
var cache = Object.create(null);
return function(str) {
return cache[str] || (cache[str] = fn(str));
};
}
/**
* Camelize a hyphen-delimited string.
*/ var camelizeRE = /-(\w)/g, camelize = cached(function(str) {
return str.replace(camelizeRE, function(_, c) {
return c ? c.toUpperCase() : '';
});
}), capitalize = cached(function(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}), hyphenateRE = /\B([A-Z])/g, hyphenate = cached(function(str) {
return str.replace(hyphenateRE, '-$1').toLowerCase();
}), bind = Function.prototype.bind ? function(fn, ctx) {
return fn.bind(ctx);
} : /**
* Simple bind polyfill for environments that do not support it,
* e.g., PhantomJS 1.x. Technically, we don't need this anymore
* since native bind is now performant enough in most browsers.
* But removing it would mean breaking code that was able to run in
* PhantomJS 1.x, so this must be kept for backward compatibility.
*/ /* istanbul ignore next */ function(fn, ctx) {
function boundFn(a) {
var l = arguments.length;
return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx);
}
return boundFn._length = fn.length, boundFn;
};
/**
* Convert an Array-like object to a real Array.
*/ function toArray(list, start) {
start = start || 0;
for(var i = list.length - start, ret = Array(i); i--;)ret[i] = list[i + start];
return ret;
}
/**
* Mix properties into target object.
*/ function extend(to, _from) {
for(var key in _from)to[key] = _from[key];
return to;
}
/**
* Merge an Array of Objects into a single Object.
*/ function toObject(arr) {
for(var res = {}, i = 0; i < arr.length; i++)arr[i] && extend(res, arr[i]);
return res;
}
/* eslint-disable no-unused-vars */ /**
* Perform no operation.
* Stubbing args to make Flow happy without leaving useless transpiled code
* with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/).
*/ function noop(a, b, c) {}
/**
* Always return false.
*/ var no = function(a, b, c) {
return !1;
}, identity = function(_) {
return _;
};
/**
* Check if two values are loosely equal - that is,
* if they are plain objects, do they have the same shape?
*/ function looseEqual(a, b) {
if (a === b) return !0;
var isObjectA = isObject(a), isObjectB = isObject(b);
if (isObjectA && isObjectB) try {
var isArrayA = Array.isArray(a), isArrayB = Array.isArray(b);
if (isArrayA && isArrayB) return a.length === b.length && a.every(function(e, i) {
return looseEqual(e, b[i]);
});
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
if (isArrayA || isArrayB) /* istanbul ignore next */ return !1;
var keysA = Object.keys(a), keysB = Object.keys(b);
return keysA.length === keysB.length && keysA.every(function(key) {
return looseEqual(a[key], b[key]);
});
} catch (e) {
/* istanbul ignore next */ return !1;
}
else if (!isObjectA && !isObjectB) return String(a) === String(b);
else return !1;
}
/**
* Return the first index at which a loosely equal value can be
* found in the array (if value is a plain object, the array must
* contain an object of the same shape), or -1 if it is not present.
*/ function looseIndexOf(arr, val) {
for(var i = 0; i < arr.length; i++)if (looseEqual(arr[i], val)) return i;
return -1;
}
/**
* Ensure a function is called only once.
*/ function once(fn) {
var called = !1;
return function() {
called || (called = !0, fn.apply(this, arguments));
};
}
var SSR_ATTR = 'data-server-rendered', ASSET_TYPES = [
'component',
'directive',
'filter'
], LIFECYCLE_HOOKS = [
'beforeCreate',
'created',
'beforeMount',
'mounted',
'beforeUpdate',
'updated',
'beforeDestroy',
'destroyed',
'activated',
'deactivated',
'errorCaptured',
'serverPrefetch'
], config = {
/**
* Option merge strategies (used in core/util/options)
*/ // $flow-disable-line
optionMergeStrategies: Object.create(null),
/**
* Whether to suppress warnings.
*/ silent: !1,
/**
* Show production mode tip message on boot?
*/ productionTip: !0,
/**
* Whether to enable devtools
*/ devtools: !0,
/**
* Whether to record perf
*/ performance: !1,
/**
* Error handler for watcher errors
*/ errorHandler: null,
/**
* Warn handler for watcher warns
*/ warnHandler: null,
/**
* Ignore certain custom elements
*/ ignoredElements: [],
/**
* Custom user key aliases for v-on
*/ // $flow-disable-line
keyCodes: Object.create(null),
/**
* Check if a tag is reserved so that it cannot be registered as a
* component. This is platform-dependent and may be overwritten.
*/ isReservedTag: no,
/**
* Check if an attribute is reserved so that it cannot be used as a component
* prop. This is platform-dependent and may be overwritten.
*/ isReservedAttr: no,
/**
* Check if a tag is an unknown element.
* Platform-dependent.
*/ isUnknownElement: no,
/**
* Get the namespace of an element
*/ getTagNamespace: noop,
/**
* Parse the real tag name for the specific platform.
*/ parsePlatformTagName: identity,
/**
* Check if an attribute must be bound using property, e.g. value
* Platform-dependent.
*/ mustUseProp: no,
/**
* Perform updates asynchronously. Intended to be used by Vue Test Utils
* This will significantly reduce performance if set to false.
*/ async: !0,
/**
* Exposed for legacy reasons
*/ _lifecycleHooks: LIFECYCLE_HOOKS
}, unicodeRegExp = /a-zA-Z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD/;
/**
* Check if a string starts with $ or _
*/ function isReserved(str) {
var c = (str + '').charCodeAt(0);
return 0x24 === c || 0x5F === c;
}
/**
* Define a property.
*/ function def(obj, key, val, enumerable) {
Object.defineProperty(obj, key, {
value: val,
enumerable: !!enumerable,
writable: !0,
configurable: !0
});
}
/**
* Parse simple path.
*/ var bailRE = RegExp("[^" + unicodeRegExp.source + ".$_\\d]"), hasProto = '__proto__' in {}, inBrowser = 'undefined' != typeof window, inWeex = 'undefined' != typeof WXEnvironment && !!WXEnvironment.platform, weexPlatform = inWeex && WXEnvironment.platform.toLowerCase(), UA = inBrowser && window.navigator.userAgent.toLowerCase(), isIE = UA && /msie|trident/.test(UA), isIE9 = UA && UA.indexOf('msie 9.0') > 0, isEdge = UA && UA.indexOf('edge/') > 0;
UA && UA.indexOf('android');
var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA) || 'ios' === weexPlatform;
UA && /chrome\/\d+/.test(UA), UA && /phantomjs/.test(UA);
var isFF = UA && UA.match(/firefox\/(\d+)/), nativeWatch = {}.watch, supportsPassive = !1;
if (inBrowser) try {
var opts = {};
Object.defineProperty(opts, 'passive', {
get: function() {
/* istanbul ignore next */ supportsPassive = !0;
}
}), window.addEventListener('test-passive', null, opts);
} catch (e) {}
var isServerRendering = function() {
return void 0 === _isServer && (_isServer = !inBrowser && !inWeex && 'undefined' != typeof global && global.process && 'server' === global.process.env.VUE_ENV), _isServer;
}, devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__;
/* istanbul ignore next */ function isNative(Ctor) {
return 'function' == typeof Ctor && /native code/.test(Ctor.toString());
}
var hasSymbol = 'undefined' != typeof Symbol && isNative(Symbol) && 'undefined' != typeof Reflect && isNative(Reflect.ownKeys);
// use native Set when available.
_Set = 'undefined' != typeof Set && isNative(Set) ? Set : /*@__PURE__*/ function() {
function Set1() {
this.set = Object.create(null);
}
return Set1.prototype.has = function(key) {
return !0 === this.set[key];
}, Set1.prototype.add = function(key) {
this.set[key] = !0;
}, Set1.prototype.clear = function() {
this.set = Object.create(null);
}, Set1;
}();
/* */ var warn = noop, tip = noop, generateComponentTrace = noop, formatComponentName = noop, hasConsole = 'undefined' != typeof console, classifyRE = /(?:^|[-_])(\w)/g;
warn = function(msg, vm) {
var trace = vm ? generateComponentTrace(vm) : '';
config.warnHandler ? config.warnHandler.call(null, msg, vm, trace) : hasConsole && !config.silent && console.error("[Vue warn]: " + msg + trace);
}, tip = function(msg, vm) {
hasConsole && !config.silent && console.warn("[Vue tip]: " + msg + (vm ? generateComponentTrace(vm) : ''));
}, formatComponentName = function(vm, includeFile) {
if (vm.$root === vm) return '<Root>';
var options = 'function' == typeof vm && null != vm.cid ? vm.options : vm._isVue ? vm.$options || vm.constructor.options : vm, name = options.name || options._componentTag, file = options.__file;
if (!name && file) {
var match = file.match(/([^/\\]+)\.vue$/);
name = match && match[1];
}
return (name ? "<" + name.replace(classifyRE, function(c) {
return c.toUpperCase();
}).replace(/[-_]/g, '') + ">" : "<Anonymous>") + (file && !1 !== includeFile ? " at " + file : '');
};
var repeat = function(str, n) {
for(var res = ''; n;)n % 2 == 1 && (res += str), n > 1 && (str += str), n >>= 1;
return res;
};
generateComponentTrace = function(vm) {
if (!vm._isVue || !vm.$parent) return "\n\n(found in " + formatComponentName(vm) + ")";
for(var tree = [], currentRecursiveSequence = 0; vm;){
if (tree.length > 0) {
var last = tree[tree.length - 1];
if (last.constructor === vm.constructor) {
currentRecursiveSequence++, vm = vm.$parent;
continue;
}
currentRecursiveSequence > 0 && (tree[tree.length - 1] = [
last,
currentRecursiveSequence
], currentRecursiveSequence = 0);
}
tree.push(vm), vm = vm.$parent;
}
return '\n\nfound in\n\n' + tree.map(function(vm, i) {
return "" + (0 === i ? '---> ' : repeat(' ', 5 + 2 * i)) + (Array.isArray(vm) ? formatComponentName(vm[0]) + "... (" + vm[1] + " recursive calls)" : formatComponentName(vm));
}).join('\n');
};
/* */ var uid = 0, Dep = function() {
this.id = uid++, this.subs = [];
};
Dep.prototype.addSub = function(sub) {
this.subs.push(sub);
}, Dep.prototype.removeSub = function(sub) {
remove(this.subs, sub);
}, Dep.prototype.depend = function() {
Dep.target && Dep.target.addDep(this);
}, Dep.prototype.notify = function() {
// stabilize the subscriber list first
var subs = this.subs.slice();
config.async || // subs aren't sorted in scheduler if not running async
// we need to sort them now to make sure they fire in correct
// order
subs.sort(function(a, b) {
return a.id - b.id;
});
for(var i = 0, l = subs.length; i < l; i++)subs[i].update();
}, // The current target watcher being evaluated.
// This is globally unique because only one watcher
// can be evaluated at a time.
Dep.target = null;
var targetStack = [];
function pushTarget(target) {
targetStack.push(target), Dep.target = target;
}
function popTarget() {
targetStack.pop(), Dep.target = targetStack[targetStack.length - 1];
}
/* */ var VNode = function(tag, data, children, text, elm, context, componentOptions, asyncFactory) {
this.tag = tag, this.data = data, this.children = children, this.text = text, this.elm = elm, this.ns = void 0, this.context = context, this.fnContext = void 0, this.fnOptions = void 0, this.fnScopeId = void 0, this.key = data && data.key, this.componentOptions = componentOptions, this.componentInstance = void 0, this.parent = void 0, this.raw = !1, this.isStatic = !1, this.isRootInsert = !0, this.isComment = !1, this.isCloned = !1, this.isOnce = !1, this.asyncFactory = asyncFactory, this.asyncMeta = void 0, this.isAsyncPlaceholder = !1;
}, prototypeAccessors = {
child: {
configurable: !0
}
};
// DEPRECATED: alias for componentInstance for backwards compat.
/* istanbul ignore next */ prototypeAccessors.child.get = function() {
return this.componentInstance;
}, Object.defineProperties(VNode.prototype, prototypeAccessors);
var createEmptyVNode = function(text) {
void 0 === text && (text = '');
var node = new VNode();
return node.text = text, node.isComment = !0, node;
};
function createTextVNode(val) {
return new VNode(void 0, void 0, void 0, String(val));
}
// optimized shallow clone
// used for static nodes and slot nodes because they may be reused across
// multiple renders, cloning them avoids errors when DOM manipulations rely
// on their elm reference.
function cloneVNode(vnode) {
var cloned = new VNode(vnode.tag, vnode.data, // #7975
// clone children array to avoid mutating original in case of cloning
// a child.
vnode.children && vnode.children.slice(), vnode.text, vnode.elm, vnode.context, vnode.componentOptions, vnode.asyncFactory);
return cloned.ns = vnode.ns, cloned.isStatic = vnode.isStatic, cloned.key = vnode.key, cloned.isComment = vnode.isComment, cloned.fnContext = vnode.fnContext, cloned.fnOptions = vnode.fnOptions, cloned.fnScopeId = vnode.fnScopeId, cloned.asyncMeta = vnode.asyncMeta, cloned.isCloned = !0, cloned;
}
/*
* not type checking this file because flow doesn't play well with
* dynamically accessing methods on Array prototype
*/ var arrayProto = Array.prototype, arrayMethods = Object.create(arrayProto);
/**
* Intercept mutating methods and emit events
*/ [
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
].forEach(function(method) {
// cache original method
var original = arrayProto[method];
def(arrayMethods, method, function() {
for(var inserted, args = [], len = arguments.length; len--;)args[len] = arguments[len];
var result = original.apply(this, args), ob = this.__ob__;
switch(method){
case 'push':
case 'unshift':
inserted = args;
break;
case 'splice':
inserted = args.slice(2);
}
return inserted && ob.observeArray(inserted), // notify change
ob.dep.notify(), result;
});
});
/* */ var arrayKeys = Object.getOwnPropertyNames(arrayMethods), shouldObserve = !0, Observer = function(value) {
this.value = value, this.dep = new Dep(), this.vmCount = 0, def(value, '__ob__', this), Array.isArray(value) ? (hasProto ? /* eslint-disable no-proto */ value.__proto__ = arrayMethods : /**
* Augment a target Object or Array by defining
* hidden properties.
*/ /* istanbul ignore next */ function(target, src, keys) {
for(var i = 0, l = keys.length; i < l; i++){
var key = keys[i];
def(target, key, src[key]);
}
}(value, arrayMethods, arrayKeys), this.observeArray(value)) : this.walk(value);
};
/**
* Attempt to create an observer instance for a value,
* returns the new observer if successfully observed,
* or the existing observer if the value already has one.
*/ function observe(value, asRootData) {
var ob;
if (isObject(value) && !(value instanceof VNode)) return hasOwn(value, '__ob__') && value.__ob__ instanceof Observer ? ob = value.__ob__ : shouldObserve && !isServerRendering() && (Array.isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value._isVue && (ob = new Observer(value)), asRootData && ob && ob.vmCount++, ob;
}
/**
* Define a reactive property on an Object.
*/ function defineReactive$$1(obj, key, val, customSetter, shallow) {
var dep = new Dep(), property = Object.getOwnPropertyDescriptor(obj, key);
if (!property || !1 !== property.configurable) {
// cater for pre-defined getter/setters
var getter = property && property.get, setter = property && property.set;
(!getter || setter) && 2 == arguments.length && (val = obj[key]);
var childOb = !shallow && observe(val);
Object.defineProperty(obj, key, {
enumerable: !0,
configurable: !0,
get: function() {
var value = getter ? getter.call(obj) : val;
return Dep.target && (dep.depend(), childOb && (childOb.dep.depend(), Array.isArray(value) && /**
* Collect dependencies on array elements when the array is touched, since
* we cannot intercept array element access like property getters.
*/ function dependArray(value) {
for(var e = void 0, i = 0, l = value.length; i < l; i++)(e = value[i]) && e.__ob__ && e.__ob__.dep.depend(), Array.isArray(e) && dependArray(e);
}(value))), value;
},
set: function(newVal) {
var value = getter ? getter.call(obj) : val;
/* eslint-disable no-self-compare */ newVal !== value && (newVal == newVal || value == value) && (customSetter && customSetter(), (!getter || setter) && (setter ? setter.call(obj, newVal) : val = newVal, childOb = !shallow && observe(newVal), dep.notify()));
}
});
}
}
/**
* Set a property on an object. Adds the new property and
* triggers change notification if the property doesn't
* already exist.
*/ function set(target, key, val) {
if ((isUndef(target) || isPrimitive(target)) && warn("Cannot set reactive property on undefined, null, or primitive value: " + target), Array.isArray(target) && isValidArrayIndex(key)) return target.length = Math.max(target.length, key), target.splice(key, 1, val), val;
if (key in target && !(key in Object.prototype)) return target[key] = val, val;
var ob = target.__ob__;
return target._isVue || ob && ob.vmCount ? warn("Avoid adding reactive properties to a Vue instance or its root $data at runtime - declare it upfront in the data option.") : ob ? (defineReactive$$1(ob.value, key, val), ob.dep.notify()) : target[key] = val, val;
}
/**
* Delete a property and trigger change if necessary.
*/ function del(target, key) {
if ((isUndef(target) || isPrimitive(target)) && warn("Cannot delete reactive property on undefined, null, or primitive value: " + target), Array.isArray(target) && isValidArrayIndex(key)) {
target.splice(key, 1);
return;
}
var ob = target.__ob__;
if (target._isVue || ob && ob.vmCount) {
warn("Avoid deleting properties on a Vue instance or its root $data - just set it to null.");
return;
}
hasOwn(target, key) && (delete target[key], ob && ob.dep.notify());
}
/**
* Walk through all properties and convert them into
* getter/setters. This method should only be called when
* value type is Object.
*/ Observer.prototype.walk = function(obj) {
for(var keys = Object.keys(obj), i = 0; i < keys.length; i++)defineReactive$$1(obj, keys[i]);
}, /**
* Observe a list of Array items.
*/ Observer.prototype.observeArray = function(items) {
for(var i = 0, l = items.length; i < l; i++)observe(items[i]);
};
/* */ /**
* Option overwriting strategies are functions that handle
* how to merge a parent option value and a child option
* value into the final value.
*/ var strats = config.optionMergeStrategies;
/**
* Helper that recursively merges two data objects together.
*/ function mergeData(to, from) {
if (!from) return to;
for(var key, toVal, fromVal, keys = hasSymbol ? Reflect.ownKeys(from) : Object.keys(from), i = 0; i < keys.length; i++)// in case the object is already observed...
'__ob__' !== (key = keys[i]) && (toVal = to[key], fromVal = from[key], hasOwn(to, key) ? toVal !== fromVal && isPlainObject(toVal) && isPlainObject(fromVal) && mergeData(toVal, fromVal) : set(to, key, fromVal));
return to;
}
/**
* Data
*/ function mergeDataOrFn(parentVal, childVal, vm) {
return vm ? function() {
// instance merge
var instanceData = 'function' == typeof childVal ? childVal.call(vm, vm) : childVal, defaultData = 'function' == typeof parentVal ? parentVal.call(vm, vm) : parentVal;
return instanceData ? mergeData(instanceData, defaultData) : defaultData;
} : // in a Vue.extend merge, both should be functions
childVal ? parentVal ? function() {
return mergeData('function' == typeof childVal ? childVal.call(this, this) : childVal, 'function' == typeof parentVal ? parentVal.call(this, this) : parentVal);
} : childVal : parentVal;
}
/**
* Hooks and props are merged as arrays.
*/ function mergeHook(parentVal, childVal) {
var res = childVal ? parentVal ? parentVal.concat(childVal) : Array.isArray(childVal) ? childVal : [
childVal
] : parentVal;
return res ? function(hooks) {
for(var res = [], i = 0; i < hooks.length; i++)-1 === res.indexOf(hooks[i]) && res.push(hooks[i]);
return res;
}(res) : res;
}
/**
* Assets
*
* When a vm is present (instance creation), we need to do
* a three-way merge between constructor options, instance
* options and parent options.
*/ function mergeAssets(parentVal, childVal, vm, key) {
var res = Object.create(parentVal || null);
return childVal ? (assertObjectType(key, childVal, vm), extend(res, childVal)) : res;
}
strats.el = strats.propsData = function(parent, child, vm, key) {
return vm || warn("option \"" + key + '" can only be used during instance creation with the `new` keyword.'), defaultStrat(parent, child);
}, strats.data = function(parentVal, childVal, vm) {
return vm ? mergeDataOrFn(parentVal, childVal, vm) : childVal && 'function' != typeof childVal ? (warn('The "data" option should be a function that returns a per-instance value in component definitions.', vm), parentVal) : mergeDataOrFn(parentVal, childVal);
}, LIFECYCLE_HOOKS.forEach(function(hook) {
strats[hook] = mergeHook;
}), ASSET_TYPES.forEach(function(type) {
strats[type + 's'] = mergeAssets;
}), /**
* Watchers.
*
* Watchers hashes should not overwrite one
* another, so we merge them as arrays.
*/ strats.watch = function(parentVal, childVal, vm, key) {
/* istanbul ignore if */ if (parentVal === nativeWatch && (parentVal = void 0), childVal === nativeWatch && (childVal = void 0), !childVal) return Object.create(parentVal || null);
if (assertObjectType(key, childVal, vm), !parentVal) return childVal;
var ret = {};
for(var key$1 in extend(ret, parentVal), childVal){
var parent = ret[key$1], child = childVal[key$1];
parent && !Array.isArray(parent) && (parent = [
parent
]), ret[key$1] = parent ? parent.concat(child) : Array.isArray(child) ? child : [
child
];
}
return ret;
}, /**
* Other object hashes.
*/ strats.props = strats.methods = strats.inject = strats.computed = function(parentVal, childVal, vm, key) {
if (childVal && assertObjectType(key, childVal, vm), !parentVal) return childVal;
var ret = Object.create(null);
return extend(ret, parentVal), childVal && extend(ret, childVal), ret;
}, strats.provide = mergeDataOrFn;
/**
* Default strategy.
*/ var defaultStrat = function(parentVal, childVal) {
return void 0 === childVal ? parentVal : childVal;
};
function validateComponentName(name) {
RegExp("^[a-zA-Z][\\-\\.0-9_" + unicodeRegExp.source + "]*$").test(name) || warn('Invalid component name: "' + name + '". Component names should conform to valid custom element name in html5 specification.'), (isBuiltInTag(name) || config.isReservedTag(name)) && warn("Do not use built-in or reserved HTML elements as component id: " + name);
}
function assertObjectType(name, value, vm) {
isPlainObject(value) || warn("Invalid value for option \"" + name + '": expected an Object, but got ' + toRawType(value) + ".", vm);
}
/**
* Merge two option objects into a new one.
* Core utility used in both instantiation and inheritance.
*/ function mergeOptions(parent, child, vm) {
// Apply extends and mixins on the child options,
// but only if it is a raw options object that isn't
// the result of another mergeOptions call.
// Only merged options has the _base property.
if (!/**
* Validate component names
*/ function(options) {
for(var key in options.components)validateComponentName(key);
}(child), 'function' == typeof child && (child = child.options), !/**
* Ensure all props option syntax are normalized into the
* Object-based format.
*/ function(options, vm) {
var i, val, props = options.props;
if (props) {
var res = {};
if (Array.isArray(props)) for(i = props.length; i--;)'string' == typeof (val = props[i]) ? res[camelize(val)] = {
type: null
} : warn('props must be strings when using array syntax.');
else if (isPlainObject(props)) for(var key in props)val = props[key], res[camelize(key)] = isPlainObject(val) ? val : {
type: val
};
else warn('Invalid value for option "props": expected an Array or an Object, but got ' + toRawType(props) + ".", vm);
options.props = res;
}
}(child, vm), !/**
* Normalize all injections into Object-based format
*/ function(options, vm) {
var inject = options.inject;
if (inject) {
var normalized = options.inject = {};
if (Array.isArray(inject)) for(var i = 0; i < inject.length; i++)normalized[inject[i]] = {
from: inject[i]
};
else if (isPlainObject(inject)) for(var key in inject){
var val = inject[key];
normalized[key] = isPlainObject(val) ? extend({
from: key
}, val) : {
from: val
};
}
else warn('Invalid value for option "inject": expected an Array or an Object, but got ' + toRawType(inject) + ".", vm);
}
}(child, vm), !/**
* Normalize raw function directives into object format.
*/ function(options) {
var dirs = options.directives;
if (dirs) for(var key in dirs){
var def$$1 = dirs[key];
'function' == typeof def$$1 && (dirs[key] = {
bind: def$$1,
update: def$$1
});
}
}(child), !child._base && (child.extends && (parent = mergeOptions(parent, child.extends, vm)), child.mixins)) for(var key, i = 0, l = child.mixins.length; i < l; i++)parent = mergeOptions(parent, child.mixins[i], vm);
var options = {};
for(key in parent)mergeField(key);
for(key in child)hasOwn(parent, key) || mergeField(key);
function mergeField(key) {
var strat = strats[key] || defaultStrat;
options[key] = strat(parent[key], child[key], vm, key);
}
return options;
}
/**
* Resolve an asset.
* This function is used because child instances need access
* to assets defined in its ancestor chain.
*/ function resolveAsset(options, type, id, warnMissing) {
/* istanbul ignore if */ if ('string' == typeof id) {
var assets = options[type];
// check local registration variations first
if (hasOwn(assets, id)) return assets[id];
var camelizedId = camelize(id);
if (hasOwn(assets, camelizedId)) return assets[camelizedId];
var PascalCaseId = capitalize(camelizedId);
if (hasOwn(assets, PascalCaseId)) return assets[PascalCaseId];
// fallback to prototype chain
var res = assets[id] || assets[camelizedId] || assets[PascalCaseId];
return warnMissing && !res && warn('Failed to resolve ' + type.slice(0, -1) + ': ' + id, options), res;
}
}
/* */ function validateProp(key, propOptions, propsData, vm) {
var prop = propOptions[key], absent = !hasOwn(propsData, key), value = propsData[key], booleanIndex = getTypeIndex(Boolean, prop.type);
if (booleanIndex > -1) {
if (absent && !hasOwn(prop, 'default')) value = !1;
else if ('' === value || value === hyphenate(key)) {
// only cast empty string / same name to boolean if
// boolean has higher priority
var stringIndex = getTypeIndex(String, prop.type);
(stringIndex < 0 || booleanIndex < stringIndex) && (value = !0);
}
}
// check default value
if (void 0 === value) {
value = /**
* Get the default value of a prop.
*/ function(vm, prop, key) {
// no default, return undefined
if (hasOwn(prop, 'default')) {
var def = prop.default;
return(// the raw prop value was also undefined from previous render,
// return previous default value to avoid unnecessary watcher trigger
(isObject(def) && warn('Invalid default value for prop "' + key + '": Props with type Object/Array must use a factory function to return the default value.', vm), vm && vm.$options.propsData && void 0 === vm.$options.propsData[key] && void 0 !== vm._props[key]) ? vm._props[key] : 'function' == typeof def && 'Function' !== getType(prop.type) ? def.call(vm) : def);
}
}(vm, prop, key);
// since the default value is a fresh copy,
// make sure to observe it.
var prevShouldObserve = shouldObserve;
shouldObserve = !0, observe(value), shouldObserve = prevShouldObserve;
}
return(/**
* Assert whether a prop is valid.
*/ function(prop, name, value, vm, absent) {
if (prop.required && absent) {
warn('Missing required prop: "' + name + '"', vm);
return;
}
if (null != value || prop.required) {
var message, expectedType, receivedType, expectedValue, receivedValue, type = prop.type, valid = !type || !0 === type, expectedTypes = [];
if (type) {
Array.isArray(type) || (type = [
type
]);
for(var i = 0; i < type.length && !valid; i++){
var assertedType = function(value, type) {
var valid, expectedType = getType(type);
if (simpleCheckRE.test(expectedType)) {
var t = typeof value;
// for primitive wrapper objects
(valid = t === expectedType.toLowerCase()) || 'object' !== t || (valid = value instanceof type);
} else valid = 'Object' === expectedType ? isPlainObject(value) : 'Array' === expectedType ? Array.isArray(value) : value instanceof type;
return {
valid: valid,
expectedType: expectedType
};
}(value, type[i]);
expectedTypes.push(assertedType.expectedType || ''), valid = assertedType.valid;
}
}
if (!valid) {
warn((message = "Invalid prop: type check failed for prop \"" + name + '". Expected ' + expectedTypes.map(capitalize).join(', '), expectedType = expectedTypes[0], receivedType = toRawType(value), expectedValue = styleValue(value, expectedType), receivedValue = styleValue(value, receivedType), 1 === expectedTypes.length && isExplicable(expectedType) && !function() {
for(var args = [], len = arguments.length; len--;)args[len] = arguments[len];
return args.some(function(elem) {
return 'boolean' === elem.toLowerCase();
});
}(expectedType, receivedType) && (message += " with value " + expectedValue), message += ", got " + receivedType + " ", isExplicable(receivedType) && (message += "with value " + receivedValue + "."), message), vm);
return;
}
var validator = prop.validator;
validator && !validator(value) && warn('Invalid prop: custom validator check failed for prop "' + name + '".', vm);
}
}(prop, key, value, vm, absent), value);
}
var simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/;
/**
* Use function string name to check built-in types,
* because a simple equality check will fail when running
* across different vms / iframes.
*/ function getType(fn) {
var match = fn && fn.toString().match(/^\s*function (\w+)/);
return match ? match[1] : '';
}
function getTypeIndex(type, expectedTypes) {
if (!Array.isArray(expectedTypes)) return getType(expectedTypes) === getType(type) ? 0 : -1;
for(var i = 0, len = expectedTypes.length; i < len; i++)if (getType(expectedTypes[i]) === getType(type)) return i;
return -1;
}
function styleValue(value, type) {
return 'String' === type ? "\"" + value + "\"" : 'Number' === type ? "" + Number(value) : "" + value;
}
function isExplicable(value) {
return [
'string',
'number',
'boolean'
].some(function(elem) {
return value.toLowerCase() === elem;
});
}
/* */ function handleError(err, vm, info) {
// Deactivate deps tracking while processing error handler to avoid possible infinite rendering.
// See: https://github.com/vuejs/vuex/issues/1505
pushTarget();
try {
if (vm) for(var cur = vm; cur = cur.$parent;){
var hooks = cur.$options.errorCaptured;
if (hooks) for(var i = 0; i < hooks.length; i++)try {
if (!1 === hooks[i].call(cur, err, vm, info)) return;
} catch (e) {
globalHandleError(e, cur, 'errorCaptured hook');
}
}
globalHandleError(err, vm, info);
} finally{
popTarget();
}
}
function invokeWithErrorHandling(handler, context, args, vm, info) {
var res;
try {
(res = args ? handler.apply(context, args) : handler.call(context)) && !res._isVue && isPromise(res) && !res._handled && (res.catch(function(e) {
return handleError(e, vm, info + " (Promise/async)");
}), // issue #9511
// avoid catch triggering multiple times when nested calls
res._handled = !0);
} catch (e) {
handleError(e, vm, info);
}
return res;
}
function globalHandleError(err, vm, info) {
if (config.errorHandler) try {
return config.errorHandler.call(null, err, vm, info);
} catch (e) {
// if the user intentionally throws the original error in the handler,
// do not log it twice
e !== err && logError(e, null, 'config.errorHandler');
}
logError(err, vm, info);
}
function logError(err, vm, info) {
/* istanbul ignore else */ if (warn("Error in " + info + ": \"" + err.toString() + "\"", vm), (inBrowser || inWeex) && 'undefined' != typeof console) console.error(err);
else throw err;
}
/* */ var isUsingMicroTask = !1, callbacks = [], pending = !1;
function flushCallbacks() {
pending = !1;
var copies = callbacks.slice(0);
callbacks.length = 0;
for(var i = 0; i < copies.length; i++)copies[i]();
}
// The nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore next, $flow-disable-line */ if ('undefined' != typeof Promise && isNative(Promise)) {
var p = Promise.resolve();
timerFunc = function() {
p.then(flushCallbacks), isIOS && setTimeout(noop);
}, isUsingMicroTask = !0;
} else if (!isIE && 'undefined' != typeof MutationObserver && (isNative(MutationObserver) || // PhantomJS and iOS 7.x
'[object MutationObserverConstructor]' === MutationObserver.toString())) {
// Use MutationObserver where native Promise is not available,
// e.g. PhantomJS, iOS7, Android 4.4
// (#6466 MutationObserver is unreliable in IE11)
var counter = 1, observer = new MutationObserver(flushCallbacks), textNode = document.createTextNode(String(counter));
observer.observe(textNode, {
characterData: !0
}), timerFunc = function() {
textNode.data = String(counter = (counter + 1) % 2);
}, isUsingMicroTask = !0;
} else // Fallback to setImmediate.
// Technically it leverages the (macro) task queue,
// but it is still a better choice than setTimeout.
timerFunc = 'undefined' != typeof setImmediate && isNative(setImmediate) ? function() {
setImmediate(flushCallbacks);
} : function() {
setTimeout(flushCallbacks, 0);
};
function nextTick(cb, ctx) {
var _resolve;
// $flow-disable-line
if (callbacks.push(function() {
if (cb) try {
cb.call(ctx);
} catch (e) {
handleError(e, ctx, 'nextTick');
}
else _resolve && _resolve(ctx);
}), pending || (pending = !0, timerFunc()), !cb && 'undefined' != typeof Promise) return new Promise(function(resolve) {
_resolve = resolve;
});
}
var perf = inBrowser && window.performance;
perf && perf.mark && perf.measure && perf.clearMarks && perf.clearMeasures && (mark = function(tag) {
return perf.mark(tag);
}, measure = function(name, startTag, endTag) {
perf.measure(name, startTag, endTag), perf.clearMarks(startTag), perf.clearMarks(endTag);
// perf.clearMeasures(name)
});
var allowedGlobals = makeMap("Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,require" // for Webpack/Browserify
), warnNonPresent = function(target, key) {
warn("Property or method \"" + key + '" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.', target);
}, warnReservedPrefix = function(target, key) {
warn("Property \"" + key + "\" must be accessed with \"$data." + key + '" because properties starting with "$" or "_" are not proxied in the Vue instance to prevent conflicts with Vue internals. See: https://vuejs.org/v2/api/#data', target);
}, hasProxy = 'undefined' != typeof Proxy && isNative(Proxy);
if (hasProxy) {
var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta,exact');
config.keyCodes = new Proxy(config.keyCodes, {
set: function(target, key, value) {
return isBuiltInModifier(key) ? (warn("Avoid overwriting built-in modifier in config.keyCodes: ." + key), !1) : (target[key] = value, !0);
}
});
}
var hasHandler = {
has: function(target, key) {
var has = key in target, isAllowed = allowedGlobals(key) || 'string' == typeof key && '_' === key.charAt(0) && !(key in target.$data);
return has || isAllowed || (key in target.$data ? warnReservedPrefix(target, key) : warnNonPresent(target, key)), has || !isAllowed;
}
}, getHandler = {
get: function(target, key) {
return 'string' != typeof key || key in target || (key in target.$data ? warnReservedPrefix(target, key) : warnNonPresent(target, key)), target[key];
}
};
initProxy = function(vm) {
if (hasProxy) {
// determine which proxy handler to use
var options = vm.$options;
vm._renderProxy = new Proxy(vm, options.render && options.render._withStripped ? getHandler : hasHandler);
} else vm._renderProxy = vm;
};
/* */ var seenObjects = new _Set();
/**
* Recursively traverse an object to evoke all converted
* getters, so that every nested property inside the object
* is collected as a "deep" dependency.
*/ function traverse(val) {
(function _traverse(val, seen) {
var i, keys, isA = Array.isArray(val);
if (!(!isA && !isObject(val) || Object.isFrozen(val)) && !(val instanceof VNode)) {
if (val.__ob__) {
var depId = val.__ob__.dep.id;
if (seen.has(depId)) return;
seen.add(depId);
}
if (isA) for(i = val.length; i--;)_traverse(val[i], seen);
else for(i = (keys = Object.keys(val)).length; i--;)_traverse(val[keys[i]], seen);
}
})(val, seenObjects), seenObjects.clear();
}
/* */ var normalizeEvent = cached(function(name) {
var passive = '&' === name.charAt(0), once$$1 = '~' === (name = passive ? name.slice(1) : name).charAt(0), capture = '!' === (name = once$$1 ? name.slice(1) : name).charAt(0);
return {
name: name = capture ? name.slice(1) : name,
once: once$$1,
capture: capture,
passive: passive
};
});
function createFnInvoker(fns, vm) {
function invoker() {
var arguments$1 = arguments, fns = invoker.fns;
if (!Array.isArray(fns)) // return handler return value for single handlers
return invokeWithErrorHandling(fns, null, arguments, vm, "v-on handler");
for(var cloned = fns.slice(), i = 0; i < cloned.length; i++)invokeWithErrorHandling(cloned[i], null, arguments$1, vm, "v-on handler");
}
return invoker.fns = fns, invoker;
}
function updateListeners(on, oldOn, add, remove$$1, createOnceHandler, vm) {
var name, cur, old, event;
for(name in on)cur = on[name], old = oldOn[name], event = normalizeEvent(name), isUndef(cur) ? warn("Invalid handler for event \"" + event.name + "\": got " + String(cur), vm) : isUndef(old) ? (isUndef(cur.fns) && (cur = on[name] = createFnInvoker(cur, vm)), isTrue(event.once) && (cur = on[name] = createOnceHandler(event.name, cur, event.capture)), add(event.name, cur, event.capture, event.passive, event.params)) : cur !== old && (old.fns = cur, on[name] = old);
for(name in oldOn)isUndef(on[name]) && remove$$1((event = normalizeEvent(name)).name, oldOn[name], event.capture);
}
/* */ function mergeVNodeHook(def, hookKey, hook) {
def instanceof VNode && (def = def.data.hook || (def.data.hook = {}));
var invoker, oldHook = def[hookKey];
function wrappedHook() {
hook.apply(this, arguments), // important: remove merged hook to ensure it's called only once
// and prevent memory leak
remove(invoker.fns, wrappedHook);
}
isUndef(oldHook) ? // no existing hook
invoker = createFnInvoker([
wrappedHook
]) : isDef(oldHook.fns) && isTrue(oldHook.merged) ? // already a merged invoker
(invoker = oldHook).fns.push(wrappedHook) : // existing plain hook
invoker = createFnInvoker([
oldHook,
wrappedHook
]), invoker.merged = !0, def[hookKey] = invoker;
}
function checkProp(res, hash, key, altKey, preserve) {
if (isDef(hash)) {
if (hasOwn(hash, key)) return res[key] = hash[key], preserve || delete hash[key], !0;
if (hasOwn(hash, altKey)) return res[key] = hash[altKey], preserve || delete hash[altKey], !0;
}
return !1;
}
// 2. When the children contains constructs that always generated nested Arrays,
// e.g. <template>, <slot>, v-for, or when the children is provided by user
// with hand-written render functions / JSX. In such cases a full normalization
// is needed to cater to all possible types of children values.
function normalizeChildren(children) {
return isPrimitive(children) ? [
createTextVNode(children)
] : Array.isArray(children) ? function normalizeArrayChildren(children, nestedIndex) {
var i, c, lastIndex, last, res = [];
for(i = 0; i < children.length; i++)!isUndef(c = children[i]) && 'boolean' != typeof c && (lastIndex = res.length - 1, last = res[lastIndex], Array.isArray(c) ? c.length > 0 && (isTextNode((c = normalizeArrayChildren(c, (nestedIndex || '') + "_" + i))[0]) && isTextNode(last) && (res[lastIndex] = createTextVNode(last.text + c[0].text), c.shift()), res.push.apply(res, c)) : isPrimitive(c) ? isTextNode(last) ? // merge adjacent text nodes
// this is necessary for SSR hydration because text nodes are
// essentially merged when rendered to HTML strings
res[lastIndex] = createTextVNode(last.text + c) : '' !== c && // convert primitive to vnode
res.push(createTextVNode(c)) : isTextNode(c) && isTextNode(last) ? // merge adjacent text nodes
res[lastIndex] = createTextVNode(last.text + c.text) : (isTrue(children._isVList) && isDef(c.tag) && isUndef(c.key) && isDef(nestedIndex) && (c.key = "__vlist" + nestedIndex + "_" + i + "__"), res.push(c)));
return res;
}(children) : void 0;
}
function isTextNode(node) {
return isDef(node) && isDef(node.text) && !1 === node.isComment;
}
function resolveInject(inject, vm) {
if (inject) {
for(var result = Object.create(null), keys = hasSymbol ? Reflect.ownKeys(inject) : Object.keys(inject), i = 0; i < keys.length; i++){
var key = keys[i];
// #6574 in case the inject object is observed...
if ('__ob__' !== key) {
for(var provideKey = inject[key].from, source = vm; source;){
if (source._provided && hasOwn(source._provided, provideKey)) {
result[key] = source._provided[provideKey];
break;
}
source = source.$parent;
}
if (!source) {
if ('default' in inject[key]) {
var provideDefault = inject[key].default;
result[key] = 'function' == typeof provideDefault ? provideDefault.call(vm) : provideDefault;
} else warn("Injection \"" + key + "\" not found", vm);
}
}
}
return result;
}
}
/* */ /**
* Runtime helper for resolving raw children VNodes into a slot object.
*/ function resolveSlots(children, context) {
if (!children || !children.length) return {};
for(var slots = {}, i = 0, l = children.length; i < l; i++){
var child = children[i], data = child.data;
// named slots should only be respected if the vnode was rendered in the
// same context.
if (data && data.attrs && data.attrs.slot && delete data.attrs.slot, (child.context === context || child.fnContext === context) && data && null != data.slot) {
var name = data.slot, slot = slots[name] || (slots[name] = []);
'template' === child.tag ? slot.push.apply(slot, child.children || []) : slot.push(child);
} else (slots.default || (slots.default = [])).push(child);
}
// ignore slots that contains only whitespace
for(var name$1 in slots)slots[name$1].every(isWhitespace) && delete slots[name$1];
return slots;
}
function isWhitespace(node) {
return node.isComment && !node.asyncFactory || ' ' === node.text;
}
/* */ function normalizeScopedSlots(slots, normalSlots, prevSlots) {
var res, hasNormalSlots = Object.keys(normalSlots).length > 0, isStable = slots ? !!slots.$stable : !hasNormalSlots, key = slots && slots.$key;
if (slots) {
if (slots._normalized) // fast path 1: child component re-render only, parent did not change
return slots._normalized;
if (isStable && prevSlots && prevSlots !== emptyObject && key === prevSlots.$key && !hasNormalSlots && !prevSlots.$hasNormal) // fast path 2: stable scoped slots w/ no normal slots to proxy,
// only need to normalize once
return prevSlots;
for(var key$1 in res = {}, slots)slots[key$1] && '$' !== key$1[0] && (res[key$1] = function(normalSlots, key, fn) {
var normalized = function() {
var res = arguments.length ? fn.apply(null, arguments) : fn({});
return (res = res && 'object' == typeof res && !Array.isArray(res) ? [
res
] // single vnode
: normalizeChildren(res)) && (0 === res.length || 1 === res.length && res[0].isComment // #9658
) ? void 0 : res;
};
return fn.proxy && Object.defineProperty(normalSlots, key, {
get: normalized,
enumerable: !0,
configurable: !0
}), normalized;
}(normalSlots, key$1, slots[key$1]));
} else res = {};
// expose normal slots on scopedSlots
for(var key$2 in normalSlots)key$2 in res || (res[key$2] = function(slots, key) {
return function() {
return slots[key];
};
}(normalSlots, key$2));
return slots && Object.isExtensible(slots) && (slots._normalized = res), def(res, '$stable', isStable), def(res, '$key', key), def(res, '$hasNormal', hasNormalSlots), res;
}
/* */ /**
* Runtime helper for rendering v-for lists.
*/ function renderList(val, render) {
var ret, i, l, keys, key;
if (Array.isArray(val) || 'string' == typeof val) for(i = 0, ret = Array(val.length), l = val.length; i < l; i++)ret[i] = render(val[i], i);
else if ('number' == typeof val) for(i = 0, ret = Array(val); i < val; i++)ret[i] = render(i + 1, i);
else if (isObject(val)) {
if (hasSymbol && val[Symbol.iterator]) {
ret = [];
for(var iterator = val[Symbol.iterator](), result = iterator.next(); !result.done;)ret.push(render(result.value, ret.length)), result = iterator.next();
} else for(i = 0, ret = Array((keys = Object.keys(val)).length), l = keys.length; i < l; i++)key = keys[i], ret[i] = render(val[key], key, i);
}
return isDef(ret) || (ret = []), ret._isVList = !0, ret;
}
/* */ /**
* Runtime helper for rendering <slot>
*/ function renderSlot(name, fallback, props, bindObject) {
var nodes, scopedSlotFn = this.$scopedSlots[name];
scopedSlotFn ? (props = props || {}, bindObject && (isObject(bindObject) || warn('slot v-bind without argument expects an Object', this), props = extend(extend({}, bindObject), props)), nodes = scopedSlotFn(props) || fallback) : nodes = this.$slots[name] || fallback;
var target = props && props.slot;
return target ? this.$createElement('template', {
slot: target
}, nodes) : nodes;
}
/* */ /**
* Runtime helper for resolving filters
*/ function resolveFilter(id) {
return resolveAsset(this.$options, 'filters', id, !0) || identity;
}
/* */ function isKeyNotMatch(expect, actual) {
return Array.isArray(expect) ? -1 === expect.indexOf(actual) : expect !== actual;
}
/**
* Runtime helper for checking keyCodes from config.
* exposed as Vue.prototype._k
* passing in eventKeyName as last argument separately for backwards compat
*/ function checkKeyCodes(eventKeyCode, key, builtInKeyCode, eventKeyName, builtInKeyName) {
var mappedKeyCode = config.keyCodes[key] || builtInKeyCode;
return builtInKeyName && eventKeyName && !config.keyCodes[key] ? isKeyNotMatch(builtInKeyName, eventKeyName) : mappedKeyCode ? isKeyNotMatch(mappedKeyCode, eventKeyCode) : eventKeyName ? hyphenate(eventKeyName) !== key : void 0;
}
/* */ /**
* Runtime helper for merging v-bind="object" into a VNode's data.
*/ function bindObjectProps(data, tag, value, asProp, isSync) {
if (value) {
if (isObject(value)) {
Array.isArray(value) && (value = toObject(value));
var hash, loop = function(key) {
if ('class' === key || 'style' === key || isReservedAttribute(key)) hash = data;
else {
var type = data.attrs && data.attrs.type;
hash = asProp || config.mustUseProp(tag, type, key) ? data.domProps || (data.domProps = {}) : data.attrs || (data.attrs = {});
}
var camelizedKey = camelize(key), hyphenatedKey = hyphenate(key);
camelizedKey in hash || hyphenatedKey in hash || (hash[key] = value[key], isSync && ((data.on || (data.on = {}))["update:" + key] = function($event) {
value[key] = $event;
}));
};
for(var key in value)loop(key);
} else warn('v-bind without argument expects an Object or Array value', this);
}
return data;
}
/* */ /**
* Runtime helper for rendering static trees.
*/ function renderStatic(index, isInFor) {
var cached = this._staticTrees || (this._staticTrees = []), tree = cached[index];
return tree && !isInFor || markStatic(// otherwise, render a fresh tree.
tree = cached[index] = this.$options.staticRenderFns[index].call(this._renderProxy, null, this // for render fns generated for functional component templates
), "__static__" + index, !1), tree;
}
/**
* Runtime helper for v-once.
* Effectively it means marking the node as static with a unique key.
*/ function markOnce(tree, index, key) {
return markStatic(tree, "__once__" + index + (key ? "_" + key : ""), !0), tree;
}
function markStatic(tree, key, isOnce) {
if (Array.isArray(tree)) for(var i = 0; i < tree.length; i++)tree[i] && 'string' != typeof tree[i] && markStaticNode(tree[i], key + "_" + i, isOnce);
else markStaticNode(tree, key, isOnce);
}
function markStaticNode(node, key, isOnce) {
node.isStatic = !0, node.key = key, node.isOnce = isOnce;
}
/* */ function bindObjectListeners(data, value) {
if (value) {
if (isPlainObject(value)) {
var on = data.on = data.on ? extend({}, data.on) : {};
for(var key in value){
var existing = on[key], ours = value[key];
on[key] = existing ? [].concat(existing, ours) : ours;
}
} else warn('v-on without argument expects an Object value', this);
}
return data;
}
/* */ function bindDynamicKeys(baseObj, values) {
for(var i = 0; i < values.length; i += 2){
var key = values[i];
'string' == typeof key && key ? baseObj[values[i]] = values[i + 1] : '' !== key && null !== key && // null is a special value for explicitly removing a binding
warn("Invalid value for dynamic directive argument (expected string or null): " + key, this);
}
return baseObj;
}
// helper to dynamically append modifier runtime markers to event names.
// ensure only append when value is already string, otherwise it will be cast
// to string and cause the type check to miss.
function prependModifier(value, symbol) {
return 'string' == typeof value ? symbol + value : value;
}
/* */ function installRenderHelpers(target) {
target._o = markOnce, target._n = toNumber, target._s = toString, target._l = renderList, target._t = renderSlot, target._q = looseEqual, target._i = looseIndexOf, target._m = renderStatic, target._f = resolveFilter, target._k = checkKeyCodes, target._b = bindObjectProps, target._v = createTextVNode, target._e = createEmptyVNode, target._u = /* */ function resolveScopedSlots(fns, res, // the following are added in 2.6
hasDynamicKeys, contentHashKey) {
res = res || {
$stable: !hasDynamicKeys
};
for(var i = 0; i < fns.length; i++){
var slot = fns[i];
Array.isArray(slot) ? resolveScopedSlots(slot, res, hasDynamicKeys) : slot && (slot.proxy && (slot.fn.proxy = !0), res[slot.key] = slot.fn);
}
return contentHashKey && (res.$key = contentHashKey), res;
}, target._g = bindObjectListeners, target._d = bindDynamicKeys, target._p = prependModifier;
}
/* */ function FunctionalRenderContext(data, props, children, parent, Ctor) {
var contextVm, this$1 = this, options = Ctor.options;
hasOwn(parent, '_uid') ? // $flow-disable-line
(contextVm = Object.create(parent))._original = parent : (// the context vm passed in is a functional context as well.
// in this case we want to make sure we are able to get a hold to the
// real context instance.
contextVm = parent, // $flow-disable-line
parent = parent._original);
var isCompiled = isTrue(options._compiled), needNormalization = !isCompiled;
this.data = data, this.props = props, this.children = children, this.parent = parent, this.listeners = data.on || emptyObject, this.injections = resolveInject(options.inject, parent), this.slots = function() {
return this$1.$slots || normalizeScopedSlots(data.scopedSlots, this$1.$slots = resolveSlots(children, parent)), this$1.$slots;
}, Object.defineProperty(this, 'scopedSlots', {
enumerable: !0,
get: function() {
return normalizeScopedSlots(data.scopedSlots, this.slots());
}
}), isCompiled && (// exposing $options for renderStatic()
this.$options = options, // pre-resolve slots for renderSlot()
this.$slots = this.slots(), this.$scopedSlots = normalizeScopedSlots(data.scopedSlots, this.$slots)), options._scopeId ? this._c = function(a, b, c, d) {
var vnode = createElement(contextVm, a, b, c, d, needNormalization);
return vnode && !Array.isArray(vnode) && (vnode.fnScopeId = options._scopeId, vnode.fnContext = parent), vnode;
} : this._c = function(a, b, c, d) {
return createElement(contextVm, a, b, c, d, needNormalization);
};
}
function cloneAndMarkFunctionalResult(vnode, data, contextVm, options, renderContext) {
// #7817 clone node before setting fnContext, otherwise if the node is reused
// (e.g. it was from a cached normal slot) the fnContext causes named slots
// that should not be matched to match.
var clone = cloneVNode(vnode);
return clone.fnContext = contextVm, clone.fnOptions = options, (clone.devtoolsMeta = clone.devtoolsMeta || {}).renderContext = renderContext, data.slot && ((clone.data || (clone.data = {})).slot = data.slot), clone;
}
function mergeProps(to, from) {
for(var key in from)to[camelize(key)] = from[key];
}
installRenderHelpers(FunctionalRenderContext.prototype);
/* */ /* */ /* */ /* */ // inline hooks to be invoked on component VNodes during patch
var componentVNodeHooks = {
init: function(vnode, hydrating) {
var options, inlineTemplate;
vnode.componentInstance && !vnode.componentInstance._isDestroyed && vnode.data.keepAlive ? componentVNodeHooks.prepatch(vnode, vnode) : (options = {
_isComponent: !0,
_parentVnode: vnode,
parent: activeInstance
}, isDef(inlineTemplate = vnode.data.inlineTemplate) && (options.render = inlineTemplate.render, options.staticRenderFns = inlineTemplate.staticRenderFns), vnode.componentInstance = new vnode.componentOptions.Ctor(options)).$mount(hydrating ? vnode.elm : void 0, hydrating);
},
prepatch: function(oldVnode, vnode) {
var options = vnode.componentOptions;
!function(vm, propsData, listeners, parentVnode, renderChildren) {
isUpdatingChildComponent = !0;
// determine whether component has slot children
// we need to do this before overwriting $options._renderChildren.
// check if there are dynamic scopedSlots (hand-written or compiled but with
// dynamic slot names). Static scoped slots compiled from template has the
// "$stable" marker.
var newScopedSlots = parentVnode.data.scopedSlots, oldScopedSlots = vm.$scopedSlots, hasDynamicScopedSlot = !!(newScopedSlots && !newScopedSlots.$stable || oldScopedSlots !== emptyObject && !oldScopedSlots.$stable || newScopedSlots && vm.$scopedSlots.$key !== newScopedSlots.$key), needsForceUpdate = !!(renderChildren || // has new static slots
vm.$options._renderChildren || // has old static slots
hasDynamicScopedSlot);
// update props
if (vm.$options._parentVnode = parentVnode, vm.$vnode = parentVnode, vm._vnode && (vm._vnode.parent = parentVnode), vm.$options._renderChildren = renderChildren, // update $attrs and $listeners hash
// these are also reactive so they may trigger child update if the child
// used them during render
vm.$attrs = parentVnode.data.attrs || emptyObject, vm.$listeners = listeners || emptyObject, propsData && vm.$options.props) {
shouldObserve = !1;
for(var props = vm._props, propKeys = vm.$options._propKeys || [], i = 0; i < propKeys.length; i++){
var key = propKeys[i], propOptions = vm.$options.props;
props[key] = validateProp(key, propOptions, propsData, vm);
}
shouldObserve = !0, // keep a copy of raw propsData
vm.$options.propsData = propsData;
}
// update listeners
listeners = listeners || emptyObject;
var oldListeners = vm.$options._parentListeners;
vm.$options._parentListeners = listeners, updateComponentListeners(vm, listeners, oldListeners), needsForceUpdate && (vm.$slots = resolveSlots(renderChildren, parentVnode.context), vm.$forceUpdate()), isUpdatingChildComponent = !1;
}(vnode.componentInstance = oldVnode.componentInstance, options.propsData, options.listeners, vnode, options.children // new children
);
},
insert: function(vnode) {
var context = vnode.context, componentInstance = vnode.componentInstance;
componentInstance._isMounted || (componentInstance._isMounted = !0, callHook(componentInstance, 'mounted')), vnode.data.keepAlive && (context._isMounted ? (// setting _inactive to false here so that a render function can
// rely on checking whether it's in an inactive tree (e.g. router-view)
componentInstance._inactive = !1, activatedChildren.push(componentInstance)) : activateChildComponent(componentInstance, !0));
},
destroy: function(vnode) {
var componentInstance = vnode.componentInstance;
componentInstance._isDestroyed || (vnode.data.keepAlive ? function deactivateChildComponent(vm, direct) {
if (!(direct && (vm._directInactive = !0, isInInactiveTree(vm))) && !vm._inactive) {
vm._inactive = !0;
for(var i = 0; i < vm.$children.length; i++)deactivateChildComponent(vm.$children[i]);
callHook(vm, 'deactivated');
}
}(componentInstance, !0) : componentInstance.$destroy());
}
}, hooksToMerge = Object.keys(componentVNodeHooks);
function createComponent(Ctor, data, context, children, tag) {
if (!isUndef(Ctor)) {
var factory, data1, node, options, data2, prop, event, on, existing, callback, asyncFactory, baseCtor = context.$options._base;
// if at this stage it's not a constructor or an async component factory,
// reject.
if (isObject(Ctor) && (Ctor = baseCtor.extend(Ctor)), 'function' != typeof Ctor) {
warn("Invalid Component definition: " + String(Ctor), context);
return;
}
if (isUndef(Ctor.cid) && void 0 === (Ctor = function(factory, baseCtor) {
if (isTrue(factory.error) && isDef(factory.errorComp)) return factory.errorComp;
if (isDef(factory.resolved)) return factory.resolved;
var owner = currentRenderingInstance;
if (owner && isDef(factory.owners) && -1 === factory.owners.indexOf(owner) && // already pending
factory.owners.push(owner), isTrue(factory.loading) && isDef(factory.loadingComp)) return factory.loadingComp;
if (owner && !isDef(factory.owners)) {
var owners = factory.owners = [
owner
], sync = !0, timerLoading = null, timerTimeout = null;
owner.$on('hook:destroyed', function() {
return remove(owners, owner);
});
var forceRender = function(renderCompleted) {
for(var i = 0, l = owners.length; i < l; i++)owners[i].$forceUpdate();
renderCompleted && (owners.length = 0, null !== timerLoading && (clearTimeout(timerLoading), timerLoading = null), null !== timerTimeout && (clearTimeout(timerTimeout), timerTimeout = null));
}, resolve = once(function(res) {
// cache resolved
factory.resolved = ensureCtor(res, baseCtor), sync ? owners.length = 0 : forceRender(!0);
}), reject = once(function(reason) {
warn("Failed to resolve async component: " + String(factory) + (reason ? "\nReason: " + reason : '')), isDef(factory.errorComp) && (factory.error = !0, forceRender(!0));
}), res = factory(resolve, reject);
// return in case resolved synchronously
return isObject(res) && (isPromise(res) ? isUndef(factory.resolved) && res.then(resolve, reject) : isPromise(res.component) && (res.component.then(resolve, reject), isDef(res.error) && (factory.errorComp = ensureCtor(res.error, baseCtor)), isDef(res.loading) && (factory.loadingComp = ensureCtor(res.loading, baseCtor), 0 === res.delay ? factory.loading = !0 : timerLoading = setTimeout(function() {
timerLoading = null, isUndef(factory.resolved) && isUndef(factory.error) && (factory.loading = !0, forceRender(!1));
}, res.delay || 200)), isDef(res.timeout) && (timerTimeout = setTimeout(function() {
timerTimeout = null, isUndef(factory.resolved) && reject("timeout (" + res.timeout + "ms)");
}, res.timeout)))), sync = !1, factory.loading ? factory.loadingComp : factory.resolved;
}
}(asyncFactory = Ctor, baseCtor))) // return a placeholder node for async component, which is rendered
// as a comment node but preserves all the raw information for the node.
// the information will be used for async server-rendering and hydration.
return factory = asyncFactory, data1 = data, (node = createEmptyVNode()).asyncFactory = factory, node.asyncMeta = {
data: data1,
context: context,
children: children,
tag: tag
}, node;
data = data || {}, // resolve constructor options in case global mixins are applied after
// component constructor creation
resolveConstructorOptions(Ctor), isDef(data.model) && (options = Ctor.options, data2 = data, prop = options.model && options.model.prop || 'value', event = options.model && options.model.event || 'input', (data2.attrs || (data2.attrs = {}))[prop] = data2.model.value, existing = (on = data2.on || (data2.on = {}))[event], callback = data2.model.callback, isDef(existing) ? (Array.isArray(existing) ? -1 === existing.indexOf(callback) : existing !== callback) && (on[event] = [
callback
].concat(existing)) : on[event] = callback);
// extract props
var propsData = /* */ function(data, Ctor, tag) {
// we are only extracting raw values here.
// validation and default values are handled in the child
// component itself.
var propOptions = Ctor.options.props;
if (!isUndef(propOptions)) {
var res = {}, attrs = data.attrs, props = data.props;
if (isDef(attrs) || isDef(props)) for(var key in propOptions){
var altKey = hyphenate(key), keyInLowerCase = key.toLowerCase();
key !== keyInLowerCase && attrs && hasOwn(attrs, keyInLowerCase) && tip("Prop \"" + keyInLowerCase + "\" is passed to component " + formatComponentName(tag || Ctor) + ', but the declared prop name is "' + key + '". Note that HTML attributes are case-insensitive and camelCased props need to use their kebab-case equivalents when using in-DOM templates. You should probably use "' + altKey + "\" instead of \"" + key + "\"."), checkProp(res, props, key, altKey, !0) || checkProp(res, attrs, key, altKey, !1);
}
return res;
}
}(data, Ctor, tag);
// functional component
if (isTrue(Ctor.options.functional)) return function(Ctor, propsData, data, contextVm, children) {
var options = Ctor.options, props = {}, propOptions = options.props;
if (isDef(propOptions)) for(var key in propOptions)props[key] = validateProp(key, propOptions, propsData || emptyObject);
else isDef(data.attrs) && mergeProps(props, data.attrs), isDef(data.props) && mergeProps(props, data.props);
var renderContext = new FunctionalRenderContext(data, props, children, contextVm, Ctor), vnode = options.render.call(null, renderContext._c, renderContext);
if (vnode instanceof VNode) return cloneAndMarkFunctionalResult(vnode, data, renderContext.parent, options, renderContext);
if (Array.isArray(vnode)) {
for(var vnodes = normalizeChildren(vnode) || [], res = Array(vnodes.length), i = 0; i < vnodes.length; i++)res[i] = cloneAndMarkFunctionalResult(vnodes[i], data, renderContext.parent, options, renderContext);
return res;
}
}(Ctor, propsData, data, context, children);
// extract listeners, since these needs to be treated as
// child component listeners instead of DOM listeners
var listeners = data.on;
if (// replace with listeners with .native modifier
// so it gets processed during parent component patch.
data.on = data.nativeOn, isTrue(Ctor.options.abstract)) {
// abstract components do not keep anything
// other than props & listeners & slot
// work around flow
var slot = data.slot;
data = {}, slot && (data.slot = slot);
}
!// install component management hooks onto the placeholder node
function(data) {
for(var hooks = data.hook || (data.hook = {}), i = 0; i < hooksToMerge.length; i++){
var key = hooksToMerge[i], existing = hooks[key], toMerge = componentVNodeHooks[key];
existing === toMerge || existing && existing._merged || (hooks[key] = existing ? function(f1, f2) {
var merged = function(a, b) {
// flow complains about extra args which is why we use any
f1(a, b), f2(a, b);
};
return merged._merged = !0, merged;
}(toMerge, existing) : toMerge);
}
}(data);
// return a placeholder vnode
var name = Ctor.options.name || tag;
return new VNode("vue-component-" + Ctor.cid + (name ? "-" + name : ''), data, void 0, void 0, void 0, context, {
Ctor: Ctor,
propsData: propsData,
listeners: listeners,
tag: tag,
children: children
}, asyncFactory);
}
}
// wrapper function for providing a more flexible interface
// without getting yelled at by flow
function createElement(context, tag, data, children, normalizationType, alwaysNormalize) {
var tag1, data1, children1, normalizationType1, vnode, ns, Ctor, data2;
return (Array.isArray(data) || isPrimitive(data)) && (normalizationType = children, children = data, data = void 0), isTrue(alwaysNormalize) && (normalizationType = 2), tag1 = tag, data1 = data, children1 = children, normalizationType1 = normalizationType, isDef(data1) && isDef(data1.__ob__) ? (warn("Avoid using observed data object as vnode data: " + JSON.stringify(data1) + "\nAlways create fresh vnode data objects in each render!", context), createEmptyVNode()) : (isDef(data1) && isDef(data1.is) && (tag1 = data1.is), tag1) ? (isDef(data1) && isDef(data1.key) && !isPrimitive(data1.key) && warn("Avoid using non-primitive value as key, use string/number value instead.", context), Array.isArray(children1) && 'function' == typeof children1[0] && ((data1 = data1 || {}).scopedSlots = {
default: children1[0]
}, children1.length = 0), 2 === normalizationType1 ? children1 = normalizeChildren(children1) : 1 === normalizationType1 && (children1 = /* */ // The template compiler attempts to minimize the need for normalization by
// statically analyzing the template at compile time.
//
// For plain HTML markup, normalization can be completely skipped because the
// generated render function is guaranteed to return Array<VNode>. There are
// two cases where extra normalization is needed:
// 1. When the children contains components - because a functional component
// may return an Array instead of a single root. In this case, just a simple
// normalization is needed - if any child is an Array, we flatten the whole
// thing with Array.prototype.concat. It is guaranteed to be only 1-level deep
// because functional components already normalize their own children.
function(children) {
for(var i = 0; i < children.length; i++)if (Array.isArray(children[i])) return Array.prototype.concat.apply([], children);
return children;
}(children1)), 'string' == typeof tag1 ? (ns = context.$vnode && context.$vnode.ns || config.getTagNamespace(tag1), config.isReservedTag(tag1) ? (isDef(data1) && isDef(data1.nativeOn) && warn("The .native modifier for v-on is only valid on components but it was used on <" + tag1 + ">.", context), vnode = new VNode(config.parsePlatformTagName(tag1), data1, children1, void 0, void 0, context)) : // component
vnode = (!data1 || !data1.pre) && isDef(Ctor = resolveAsset(context.$options, 'components', tag1)) ? createComponent(Ctor, data1, context, children1, tag1) : new VNode(tag1, data1, children1, void 0, void 0, context)) : // direct component options / constructor
vnode = createComponent(tag1, data1, context, children1), Array.isArray(vnode)) ? vnode : isDef(vnode) ? (isDef(ns) && function applyNS(vnode, ns, force) {
if (vnode.ns = ns, 'foreignObject' === vnode.tag && (// use default namespace inside foreignObject
ns = void 0, force = !0), isDef(vnode.children)) for(var i = 0, l = vnode.children.length; i < l; i++){
var child = vnode.children[i];
isDef(child.tag) && (isUndef(child.ns) || isTrue(force) && 'svg' !== child.tag) && applyNS(child, ns, force);
}
}(vnode, ns), isDef(data1) && (isObject((data2 = data1).style) && traverse(data2.style), isObject(data2.class) && traverse(data2.class)), vnode) : createEmptyVNode() : createEmptyVNode();
}
var currentRenderingInstance = null;
/* */ function ensureCtor(comp, base) {
return (comp.__esModule || hasSymbol && 'Module' === comp[Symbol.toStringTag]) && (comp = comp.default), isObject(comp) ? base.extend(comp) : comp;
}
/* */ function isAsyncPlaceholder(node) {
return node.isComment && node.asyncFactory;
}
/* */ function getFirstComponentChild(children) {
if (Array.isArray(children)) for(var i = 0; i < children.length; i++){
var c = children[i];
if (isDef(c) && (isDef(c.componentOptions) || isAsyncPlaceholder(c))) return c;
}
}
function add(event, fn) {
target.$on(event, fn);
}
function remove$1(event, fn) {
target.$off(event, fn);
}
function createOnceHandler(event, fn) {
var _target = target;
return function onceHandler() {
var res = fn.apply(null, arguments);
null !== res && _target.$off(event, onceHandler);
};
}
function updateComponentListeners(vm, listeners, oldListeners) {
target = vm, updateListeners(listeners, oldListeners || {}, add, remove$1, createOnceHandler, vm), target = void 0;
}
/* */ var activeInstance = null, isUpdatingChildComponent = !1;
function setActiveInstance(vm) {
var prevActiveInstance = activeInstance;
return activeInstance = vm, function() {
activeInstance = prevActiveInstance;
};
}
function isInInactiveTree(vm) {
for(; vm && (vm = vm.$parent);)if (vm._inactive) return !0;
return !1;
}
function activateChildComponent(vm, direct) {
if (direct) {
if (vm._directInactive = !1, isInInactiveTree(vm)) return;
} else if (vm._directInactive) return;
if (vm._inactive || null === vm._inactive) {
vm._inactive = !1;
for(var i = 0; i < vm.$children.length; i++)activateChildComponent(vm.$children[i]);
callHook(vm, 'activated');
}
}
function callHook(vm, hook) {
// #7573 disable dep collection when invoking lifecycle hooks
pushTarget();
var handlers = vm.$options[hook], info = hook + " hook";
if (handlers) for(var i = 0, j = handlers.length; i < j; i++)invokeWithErrorHandling(handlers[i], vm, null, vm, info);
vm._hasHookEvent && vm.$emit('hook:' + hook), popTarget();
}
var queue = [], activatedChildren = [], has = {}, circular = {}, waiting = !1, flushing = !1, index = 0, currentFlushTimestamp = 0, getNow = Date.now;
// Determine what event timestamp the browser is using. Annoyingly, the
// timestamp can either be hi-res (relative to page load) or low-res
// (relative to UNIX epoch), so in order to compare time we have to use the
// same timestamp type when saving the flush timestamp.
// All IE versions use low-res event timestamps, and have problematic clock
// implementations (#9632)
if (inBrowser && !isIE) {
var performance = window.performance;
performance && 'function' == typeof performance.now && getNow() > document.createEvent('Event').timeStamp && // if the event timestamp, although evaluated AFTER the Date.now(), is
// smaller than it, it means the event is using a hi-res timestamp,
// and we need to use the hi-res version for event listener timestamps as
// well.
(getNow = function() {
return performance.now();
});
}
/**
* Flush both queues and run the watchers.
*/ function flushSchedulerQueue() {
// do not cache length because more watchers might be pushed
// as we run existing watchers
for(currentFlushTimestamp = getNow(), flushing = !0, // Sort queue before flush.
// This ensures that:
// 1. Components are updated from parent to child. (because parent is always
// created before the child)
// 2. A component's user watchers are run before its render watcher (because
// user watchers are created before the render watcher)
// 3. If a component is destroyed during a parent component's watcher run,
// its watchers can be skipped.
queue.sort(function(a, b) {
return a.id - b.id;
}), index = 0; index < queue.length; index++)// in dev build, check and stop circular updates.
if ((watcher = queue[index]).before && watcher.before(), has[id = watcher.id] = null, watcher.run(), null != has[id] && (circular[id] = (circular[id] || 0) + 1, circular[id] > 100)) {
warn('You may have an infinite update loop ' + (watcher.user ? "in watcher with expression \"" + watcher.expression + "\"" : "in a component render function."), watcher.vm);
break;
}
// keep copies of post queues before resetting state
var watcher, id, activatedQueue = activatedChildren.slice(), updatedQueue = queue.slice();
index = queue.length = activatedChildren.length = 0, has = {}, circular = {}, waiting = flushing = !1, // call component updated and activated hooks
function(queue) {
for(var i = 0; i < queue.length; i++)queue[i]._inactive = !0, activateChildComponent(queue[i], !0);
}(activatedQueue), function(queue) {
for(var i = queue.length; i--;){
var watcher = queue[i], vm = watcher.vm;
vm._watcher === watcher && vm._isMounted && !vm._isDestroyed && callHook(vm, 'updated');
}
}(updatedQueue), devtools && config.devtools && devtools.emit('flush');
}
/* */ var uid$2 = 0, Watcher = function(vm, expOrFn, cb, options, isRenderWatcher) {
this.vm = vm, isRenderWatcher && (vm._watcher = this), vm._watchers.push(this), options ? (this.deep = !!options.deep, this.user = !!options.user, this.lazy = !!options.lazy, this.sync = !!options.sync, this.before = options.before) : this.deep = this.user = this.lazy = this.sync = !1, this.cb = cb, this.id = ++uid$2, this.active = !0, this.dirty = this.lazy, this.deps = [], this.newDeps = [], this.depIds = new _Set(), this.newDepIds = new _Set(), this.expression = expOrFn.toString(), 'function' == typeof expOrFn ? this.getter = expOrFn : (this.getter = function(path) {
if (!bailRE.test(path)) {
var segments = path.split('.');
return function(obj) {
for(var i = 0; i < segments.length; i++){
if (!obj) return;
obj = obj[segments[i]];
}
return obj;
};
}
}(expOrFn), this.getter || (this.getter = noop, warn("Failed watching path: \"" + expOrFn + '" Watcher only accepts simple dot-delimited paths. For full control, use a function instead.', vm))), this.value = this.lazy ? void 0 : this.get();
};
/**
* Evaluate the getter, and re-collect dependencies.
*/ Watcher.prototype.get = function() {
pushTarget(this);
var value, vm = this.vm;
try {
value = this.getter.call(vm, vm);
} catch (e) {
if (this.user) handleError(e, vm, "getter for watcher \"" + this.expression + "\"");
else throw e;
} finally{
this.deep && traverse(value), popTarget(), this.cleanupDeps();
}
return value;
}, /**
* Add a dependency to this directive.
*/ Watcher.prototype.addDep = function(dep) {
var id = dep.id;
this.newDepIds.has(id) || (this.newDepIds.add(id), this.newDeps.push(dep), this.depIds.has(id) || dep.addSub(this));
}, /**
* Clean up for dependency collection.
*/ Watcher.prototype.cleanupDeps = function() {
for(var i = this.deps.length; i--;){
var dep = this.deps[i];
this.newDepIds.has(dep.id) || dep.removeSub(this);
}
var tmp = this.depIds;
this.depIds = this.newDepIds, this.newDepIds = tmp, this.newDepIds.clear(), tmp = this.deps, this.deps = this.newDeps, this.newDeps = tmp, this.newDeps.length = 0;
}, /**
* Subscriber interface.
* Will be called when a dependency changes.
*/ Watcher.prototype.update = function() {
/* istanbul ignore else */ this.lazy ? this.dirty = !0 : this.sync ? this.run() : /**
* Push a watcher into the watcher queue.
* Jobs with duplicate IDs will be skipped unless it's
* pushed when the queue is being flushed.
*/ function(watcher) {
var id = watcher.id;
if (null == has[id]) {
if (has[id] = !0, flushing) {
for(// if already flushing, splice the watcher based on its id
// if already past its id, it will be run next immediately.
var i = queue.length - 1; i > index && queue[i].id > watcher.id;)i--;
queue.splice(i + 1, 0, watcher);
} else queue.push(watcher);
// queue the flush
if (!waiting) {
if (waiting = !0, !config.async) {
flushSchedulerQueue();
return;
}
nextTick(flushSchedulerQueue);
}
}
}(this);
}, /**
* Scheduler job interface.
* Will be called by the scheduler.
*/ Watcher.prototype.run = function() {
if (this.active) {
var value = this.get();
if (value !== this.value || // Deep watchers and watchers on Object/Arrays should fire even
// when the value is the same, because the value may
// have mutated.
isObject(value) || this.deep) {
// set new value
var oldValue = this.value;
if (this.value = value, this.user) try {
this.cb.call(this.vm, value, oldValue);
} catch (e) {
handleError(e, this.vm, "callback for watcher \"" + this.expression + "\"");
}
else this.cb.call(this.vm, value, oldValue);
}
}
}, /**
* Evaluate the value of the watcher.
* This only gets called for lazy watchers.
*/ Watcher.prototype.evaluate = function() {
this.value = this.get(), this.dirty = !1;
}, /**
* Depend on all deps collected by this watcher.
*/ Watcher.prototype.depend = function() {
for(var i = this.deps.length; i--;)this.deps[i].depend();
}, /**
* Remove self from all dependencies' subscriber list.
*/ Watcher.prototype.teardown = function() {
if (this.active) {
// remove self from vm's watcher list
// this is a somewhat expensive operation so we skip it
// if the vm is being destroyed.
this.vm._isBeingDestroyed || remove(this.vm._watchers, this);
for(var i = this.deps.length; i--;)this.deps[i].removeSub(this);
this.active = !1;
}
};
/* */ var sharedPropertyDefinition = {
enumerable: !0,
configurable: !0,
get: noop,
set: noop
};
function proxy(target, sourceKey, key) {
sharedPropertyDefinition.get = function() {
return this[sourceKey][key];
}, sharedPropertyDefinition.set = function(val) {
this[sourceKey][key] = val;
}, Object.defineProperty(target, key, sharedPropertyDefinition);
}
var computedWatcherOptions = {
lazy: !0
};
function defineComputed(target, key, userDef) {
var shouldCache = !isServerRendering();
'function' == typeof userDef ? (sharedPropertyDefinition.get = shouldCache ? createComputedGetter(key) : createGetterInvoker(userDef), sharedPropertyDefinition.set = noop) : (sharedPropertyDefinition.get = userDef.get ? shouldCache && !1 !== userDef.cache ? createComputedGetter(key) : createGetterInvoker(userDef.get) : noop, sharedPropertyDefinition.set = userDef.set || noop), sharedPropertyDefinition.set === noop && (sharedPropertyDefinition.set = function() {
warn("Computed property \"" + key + "\" was assigned to but it has no setter.", this);
}), Object.defineProperty(target, key, sharedPropertyDefinition);
}
function createComputedGetter(key) {
return function() {
var watcher = this._computedWatchers && this._computedWatchers[key];
if (watcher) return watcher.dirty && watcher.evaluate(), Dep.target && watcher.depend(), watcher.value;
};
}
function createGetterInvoker(fn) {
return function() {
return fn.call(this, this);
};
}
function createWatcher(vm, expOrFn, handler, options) {
return isPlainObject(handler) && (options = handler, handler = handler.handler), 'string' == typeof handler && (handler = vm[handler]), vm.$watch(expOrFn, handler, options);
}
/* */ var uid$3 = 0;
function resolveConstructorOptions(Ctor) {
var options = Ctor.options;
if (Ctor.super) {
var superOptions = resolveConstructorOptions(Ctor.super);
if (superOptions !== Ctor.superOptions) {
// super option changed,
// need to resolve new options.
Ctor.superOptions = superOptions;
// check if there are any late-modified/attached options (#4976)
var modifiedOptions = function(Ctor) {
var modified, latest = Ctor.options, sealed = Ctor.sealedOptions;
for(var key in latest)latest[key] !== sealed[key] && (modified || (modified = {}), modified[key] = latest[key]);
return modified;
}(Ctor);
modifiedOptions && extend(Ctor.extendOptions, modifiedOptions), (options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions)).name && (options.components[options.name] = Ctor);
}
}
return options;
}
function Vue1(options) {
this instanceof Vue1 || warn('Vue is a constructor and should be called with the `new` keyword'), this._init(options);
}
/* */ function getComponentName(opts) {
return opts && (opts.Ctor.options.name || opts.tag);
}
function matches(pattern, name) {
return Array.isArray(pattern) ? pattern.indexOf(name) > -1 : 'string' == typeof pattern ? pattern.split(',').indexOf(name) > -1 : !!isRegExp(pattern) && pattern.test(name);
}
function pruneCache(keepAliveInstance, filter) {
var cache = keepAliveInstance.cache, keys = keepAliveInstance.keys, _vnode = keepAliveInstance._vnode;
for(var key in cache){
var cachedNode = cache[key];
if (cachedNode) {
var name = getComponentName(cachedNode.componentOptions);
name && !filter(name) && pruneCacheEntry(cache, key, keys, _vnode);
}
}
}
function pruneCacheEntry(cache, key, keys, current) {
var cached$$1 = cache[key];
cached$$1 && (!current || cached$$1.tag !== current.tag) && cached$$1.componentInstance.$destroy(), cache[key] = null, remove(keys, key);
}
Vue1.prototype._init = function(options) {
var startTag, endTag, listeners, vm, options1, parentVnode, renderContext, parentData, opts, provide, opts1, parentVnode1, vnodeComponentOptions, vm1, result;
// a uid
this._uid = uid$3++, config.performance && mark && (startTag = "vue-perf-start:" + this._uid, endTag = "vue-perf-end:" + this._uid, mark(startTag)), // a flag to avoid this being observed
this._isVue = !0, options && options._isComponent ? (opts1 = this.$options = Object.create(this.constructor.options), parentVnode1 = options._parentVnode, opts1.parent = options.parent, opts1._parentVnode = parentVnode1, opts1.propsData = (vnodeComponentOptions = parentVnode1.componentOptions).propsData, opts1._parentListeners = vnodeComponentOptions.listeners, opts1._renderChildren = vnodeComponentOptions.children, opts1._componentTag = vnodeComponentOptions.tag, options.render && (opts1.render = options.render, opts1.staticRenderFns = options.staticRenderFns)) : this.$options = mergeOptions(resolveConstructorOptions(this.constructor), options || {}, this), initProxy(this), // expose real self
this._self = this, function(vm) {
var options = vm.$options, parent = options.parent;
if (parent && !options.abstract) {
for(; parent.$options.abstract && parent.$parent;)parent = parent.$parent;
parent.$children.push(vm);
}
vm.$parent = parent, vm.$root = parent ? parent.$root : vm, vm.$children = [], vm.$refs = {}, vm._watcher = null, vm._inactive = null, vm._directInactive = !1, vm._isMounted = !1, vm._isDestroyed = !1, vm._isBeingDestroyed = !1;
}(this), this._events = Object.create(null), this._hasHookEvent = !1, (listeners = this.$options._parentListeners) && updateComponentListeners(this, listeners), vm = this, vm._vnode = null, vm._staticTrees = null, options1 = vm.$options, renderContext = (parentVnode = vm.$vnode = options1._parentVnode) && parentVnode.context, vm.$slots = resolveSlots(options1._renderChildren, renderContext), vm.$scopedSlots = emptyObject, // bind the createElement fn to this instance
// so that we get proper render context inside it.
// args order: tag, data, children, normalizationType, alwaysNormalize
// internal version is used by render functions compiled from templates
vm._c = function(a, b, c, d) {
return createElement(vm, a, b, c, d, !1);
}, // normalization is always applied for the public version, used in
// user-written render functions.
vm.$createElement = function(a, b, c, d) {
return createElement(vm, a, b, c, d, !0);
}, defineReactive$$1(vm, '$attrs', (parentData = parentVnode && parentVnode.data) && parentData.attrs || emptyObject, function() {
isUpdatingChildComponent || warn("$attrs is readonly.", vm);
}, !0), defineReactive$$1(vm, '$listeners', options1._parentListeners || emptyObject, function() {
isUpdatingChildComponent || warn("$listeners is readonly.", vm);
}, !0), callHook(this, 'beforeCreate'), vm1 = this, (result = resolveInject(vm1.$options.inject, vm1)) && (shouldObserve = !1, Object.keys(result).forEach(function(key) {
defineReactive$$1(vm1, key, result[key], function() {
warn('Avoid mutating an injected value directly since the changes will be overwritten whenever the provided component re-renders. injection being mutated: "' + key + "\"", vm1);
});
}), shouldObserve = !0), this._watchers = [], (opts = this.$options).props && function(vm, propsOptions) {
var propsData = vm.$options.propsData || {}, props = vm._props = {}, keys = vm.$options._propKeys = [], isRoot = !vm.$parent;
// root instance props should be converted
isRoot || (shouldObserve = !1);
var loop = function(key) {
keys.push(key);
var value = validateProp(key, propsOptions, propsData, vm), hyphenatedKey = hyphenate(key);
(isReservedAttribute(hyphenatedKey) || config.isReservedAttr(hyphenatedKey)) && warn("\"" + hyphenatedKey + "\" is a reserved attribute and cannot be used as component prop.", vm), defineReactive$$1(props, key, value, function() {
isRoot || isUpdatingChildComponent || warn("Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: \"" + key + "\"", vm);
}), key in vm || proxy(vm, "_props", key);
};
for(var key in propsOptions)loop(key);
shouldObserve = !0;
}(this, opts.props), opts.methods && function(vm, methods) {
var props = vm.$options.props;
for(var key in methods)'function' != typeof methods[key] && warn("Method \"" + key + "\" has type \"" + typeof methods[key] + '" in the component definition. Did you reference the function correctly?', vm), props && hasOwn(props, key) && warn("Method \"" + key + "\" has already been defined as a prop.", vm), key in vm && isReserved(key) && warn("Method \"" + key + '" conflicts with an existing Vue instance method. Avoid defining component methods that start with _ or $.'), vm[key] = 'function' != typeof methods[key] ? noop : bind(methods[key], vm);
}(this, opts.methods), opts.data ? function(vm) {
var data = vm.$options.data;
isPlainObject(data = vm._data = 'function' == typeof data ? function(data, vm) {
// #7573 disable dep collection when invoking data getters
pushTarget();
try {
return data.call(vm, vm);
} catch (e) {
return handleError(e, vm, "data()"), {};
} finally{
popTarget();
}
}(data, vm) : data || {}) || (data = {}, warn("data functions should return an object:\nhttps://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function", vm));
for(// proxy data on instance
var keys = Object.keys(data), props = vm.$options.props, methods = vm.$options.methods, i = keys.length; i--;){
var key = keys[i];
methods && hasOwn(methods, key) && warn("Method \"" + key + "\" has already been defined as a data property.", vm), props && hasOwn(props, key) ? warn("The data property \"" + key + '" is already declared as a prop. Use prop default value instead.', vm) : isReserved(key) || proxy(vm, "_data", key);
}
// observe data
observe(data, !0);
}(this) : observe(this._data = {}, !0), opts.computed && function(vm, computed) {
// $flow-disable-line
var watchers = vm._computedWatchers = Object.create(null), isSSR = isServerRendering();
for(var key in computed){
var userDef = computed[key], getter = 'function' == typeof userDef ? userDef : userDef.get;
null == getter && warn("Getter is missing for computed property \"" + key + "\".", vm), isSSR || // create internal watcher for the computed property.
(watchers[key] = new Watcher(vm, getter || noop, noop, computedWatcherOptions)), key in vm ? key in vm.$data ? warn("The computed property \"" + key + "\" is already defined in data.", vm) : vm.$options.props && key in vm.$options.props && warn("The computed property \"" + key + "\" is already defined as a prop.", vm) : defineComputed(vm, key, userDef);
}
}(this, opts.computed), opts.watch && opts.watch !== nativeWatch && function(vm, watch) {
for(var key in watch){
var handler = watch[key];
if (Array.isArray(handler)) for(var i = 0; i < handler.length; i++)createWatcher(vm, key, handler[i]);
else createWatcher(vm, key, handler);
}
}(this, opts.watch), (provide = this.$options.provide) && (this._provided = 'function' == typeof provide ? provide.call(this) : provide), callHook(this, 'created'), config.performance && mark && (this._name = formatComponentName(this, !1), mark(endTag), measure("vue " + this._name + " init", startTag, endTag)), this.$options.el && this.$mount(this.$options.el);
}, (dataDef = {}).get = function() {
return this._data;
}, (propsDef = {}).get = function() {
return this._props;
}, dataDef.set = function() {
warn("Avoid replacing instance root $data. Use nested data properties instead.", this);
}, propsDef.set = function() {
warn("$props is readonly.", this);
}, Object.defineProperty(Vue1.prototype, '$data', dataDef), Object.defineProperty(Vue1.prototype, '$props', propsDef), Vue1.prototype.$set = set, Vue1.prototype.$delete = del, Vue1.prototype.$watch = function(expOrFn, cb, options) {
if (isPlainObject(cb)) return createWatcher(this, expOrFn, cb, options);
(options = options || {}).user = !0;
var watcher = new Watcher(this, expOrFn, cb, options);
if (options.immediate) try {
cb.call(this, watcher.value);
} catch (error) {
handleError(error, this, "callback for immediate watcher \"" + watcher.expression + "\"");
}
return function() {
watcher.teardown();
};
}, hookRE = /^hook:/, Vue1.prototype.$on = function(event, fn) {
if (Array.isArray(event)) for(var i = 0, l = event.length; i < l; i++)this.$on(event[i], fn);
else (this._events[event] || (this._events[event] = [])).push(fn), hookRE.test(event) && (this._hasHookEvent = !0);
return this;
}, Vue1.prototype.$once = function(event, fn) {
var vm = this;
function on() {
vm.$off(event, on), fn.apply(vm, arguments);
}
return on.fn = fn, vm.$on(event, on), vm;
}, Vue1.prototype.$off = function(event, fn) {
// all
if (!arguments.length) return this._events = Object.create(null), this;
// array of events
if (Array.isArray(event)) {
for(var cb, i$1 = 0, l = event.length; i$1 < l; i$1++)this.$off(event[i$1], fn);
return this;
}
// specific event
var cbs = this._events[event];
if (!cbs) return this;
if (!fn) return this._events[event] = null, this;
for(var i = cbs.length; i--;)if ((cb = cbs[i]) === fn || cb.fn === fn) {
cbs.splice(i, 1);
break;
}
return this;
}, Vue1.prototype.$emit = function(event) {
var lowerCaseEvent = event.toLowerCase();
lowerCaseEvent !== event && this._events[lowerCaseEvent] && tip("Event \"" + lowerCaseEvent + "\" is emitted in component " + formatComponentName(this) + " but the handler is registered for \"" + event + '". Note that HTML attributes are case-insensitive and you cannot use v-on to listen to camelCase events when using in-DOM templates. You should probably use "' + hyphenate(event) + "\" instead of \"" + event + "\".");
var cbs = this._events[event];
if (cbs) {
cbs = cbs.length > 1 ? toArray(cbs) : cbs;
for(var args = toArray(arguments, 1), info = "event handler for \"" + event + "\"", i = 0, l = cbs.length; i < l; i++)invokeWithErrorHandling(cbs[i], this, args, this, info);
}
return this;
}, Vue1.prototype._update = function(vnode, hydrating) {
var prevEl = this.$el, prevVnode = this._vnode, restoreActiveInstance = setActiveInstance(this);
this._vnode = vnode, prevVnode ? // updates
this.$el = this.__patch__(prevVnode, vnode) : // initial render
this.$el = this.__patch__(this.$el, vnode, hydrating, !1), restoreActiveInstance(), prevEl && (prevEl.__vue__ = null), this.$el && (this.$el.__vue__ = this), this.$vnode && this.$parent && this.$vnode === this.$parent._vnode && (this.$parent.$el = this.$el);
// updated hook is called by the scheduler to ensure that children are
// updated in a parent's updated hook.
}, Vue1.prototype.$forceUpdate = function() {
this._watcher && this._watcher.update();
}, Vue1.prototype.$destroy = function() {
if (!this._isBeingDestroyed) {
callHook(this, 'beforeDestroy'), this._isBeingDestroyed = !0;
// remove self from parent
var parent = this.$parent;
!parent || parent._isBeingDestroyed || this.$options.abstract || remove(parent.$children, this), this._watcher && this._watcher.teardown();
for(var i = this._watchers.length; i--;)this._watchers[i].teardown();
this._data.__ob__ && this._data.__ob__.vmCount--, // call the last hook...
this._isDestroyed = !0, // invoke destroy hooks on current rendered tree
this.__patch__(this._vnode, null), // fire destroyed hook
callHook(this, 'destroyed'), // turn off all instance listeners.
this.$off(), this.$el && (this.$el.__vue__ = null), this.$vnode && (this.$vnode.parent = null);
}
}, // install runtime convenience helpers
installRenderHelpers(Vue1.prototype), Vue1.prototype.$nextTick = function(fn) {
return nextTick(fn, this);
}, Vue1.prototype._render = function() {
var vnode, ref = this.$options, render = ref.render, _parentVnode = ref._parentVnode;
_parentVnode && (this.$scopedSlots = normalizeScopedSlots(_parentVnode.data.scopedSlots, this.$slots, this.$scopedSlots)), // set parent vnode. this allows render functions to have access
// to the data on the placeholder node.
this.$vnode = _parentVnode;
try {
// There's no need to maintain a stack because all render fns are called
// separately from one another. Nested component's render fns are called
// when parent component is patched.
currentRenderingInstance = this, vnode = render.call(this._renderProxy, this.$createElement);
} catch (e) {
// return error render result,
// or previous vnode to prevent render error causing blank component
/* istanbul ignore else */ if (handleError(e, this, "render"), this.$options.renderError) try {
vnode = this.$options.renderError.call(this._renderProxy, this.$createElement, e);
} catch (e) {
handleError(e, this, "renderError"), vnode = this._vnode;
}
else vnode = this._vnode;
} finally{
currentRenderingInstance = null;
}
return Array.isArray(vnode) && 1 === vnode.length && (vnode = vnode[0]), vnode instanceof VNode || (Array.isArray(vnode) && warn("Multiple root nodes returned from render function. Render function should return a single root node.", this), vnode = createEmptyVNode()), // set parent
vnode.parent = _parentVnode, vnode;
};
var patternTypes = [
String,
RegExp,
Array
], builtInComponents = {
KeepAlive: {
name: 'keep-alive',
abstract: !0,
props: {
include: patternTypes,
exclude: patternTypes,
max: [
String,
Number
]
},
created: function() {
this.cache = Object.create(null), this.keys = [];
},
destroyed: function() {
for(var key in this.cache)pruneCacheEntry(this.cache, key, this.keys);
},
mounted: function() {
var this$1 = this;
this.$watch('include', function(val) {
pruneCache(this$1, function(name) {
return matches(val, name);
});
}), this.$watch('exclude', function(val) {
pruneCache(this$1, function(name) {
return !matches(val, name);
});
});
},
render: function() {
var slot = this.$slots.default, vnode = getFirstComponentChild(slot), componentOptions = vnode && vnode.componentOptions;
if (componentOptions) {
// check pattern
var name = getComponentName(componentOptions), include = this.include, exclude = this.exclude;
if (// not included
include && (!name || !matches(include, name)) || // excluded
exclude && name && matches(exclude, name)) return vnode;
var cache = this.cache, keys = this.keys, key = null == vnode.key ? componentOptions.Ctor.cid + (componentOptions.tag ? "::" + componentOptions.tag : '') : vnode.key;
cache[key] ? (vnode.componentInstance = cache[key].componentInstance, // make current key freshest
remove(keys, key), keys.push(key)) : (cache[key] = vnode, keys.push(key), this.max && keys.length > parseInt(this.max) && pruneCacheEntry(cache, keys[0], keys, this._vnode)), vnode.data.keepAlive = !0;
}
return vnode || slot && slot[0];
}
}
};
Vue = Vue1, (configDef = {}).get = function() {
return config;
}, configDef.set = function() {
warn('Do not replace the Vue.config object, set individual fields instead.');
}, Object.defineProperty(Vue, 'config', configDef), // exposed util methods.
// NOTE: these are not considered part of the public API - avoid relying on
// them unless you are aware of the risk.
Vue.util = {
warn: warn,
extend: extend,
mergeOptions: mergeOptions,
defineReactive: defineReactive$$1
}, Vue.set = set, Vue.delete = del, Vue.nextTick = nextTick, // 2.6 explicit observable API
Vue.observable = function(obj) {
return observe(obj), obj;
}, Vue.options = Object.create(null), ASSET_TYPES.forEach(function(type) {
Vue.options[type + 's'] = Object.create(null);
}), // this is used to identify the "base" constructor to extend all plain-object
// components with in Weex's multi-instance scenarios.
Vue.options._base = Vue, extend(Vue.options.components, builtInComponents), Vue.use = function(plugin) {
var installedPlugins = this._installedPlugins || (this._installedPlugins = []);
if (installedPlugins.indexOf(plugin) > -1) return this;
// additional parameters
var args = toArray(arguments, 1);
return args.unshift(this), 'function' == typeof plugin.install ? plugin.install.apply(plugin, args) : 'function' == typeof plugin && plugin.apply(null, args), installedPlugins.push(plugin), this;
}, Vue.mixin = function(mixin) {
return this.options = mergeOptions(this.options, mixin), this;
}, /**
* Each instance constructor, including Vue, has a unique
* cid. This enables us to create wrapped "child
* constructors" for prototypal inheritance and cache them.
*/ Vue.cid = 0, cid = 1, /**
* Class inheritance
*/ Vue.extend = function(extendOptions) {
extendOptions = extendOptions || {};
var Super = this, SuperId = Super.cid, cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {});
if (cachedCtors[SuperId]) return cachedCtors[SuperId];
var name = extendOptions.name || Super.options.name;
name && validateComponentName(name);
var Sub = function(options) {
this._init(options);
};
return Sub.prototype = Object.create(Super.prototype), Sub.prototype.constructor = Sub, Sub.cid = cid++, Sub.options = mergeOptions(Super.options, extendOptions), Sub.super = Super, Sub.options.props && function(Comp) {
var props = Comp.options.props;
for(var key in props)proxy(Comp.prototype, "_props", key);
}(Sub), Sub.options.computed && function(Comp) {
var computed = Comp.options.computed;
for(var key in computed)defineComputed(Comp.prototype, key, computed[key]);
}(Sub), // allow further extension/mixin/plugin usage
Sub.extend = Super.extend, Sub.mixin = Super.mixin, Sub.use = Super.use, // create asset registers, so extended classes
// can have their private assets too.
ASSET_TYPES.forEach(function(type) {
Sub[type] = Super[type];
}), name && (Sub.options.components[name] = Sub), // keep a reference to the super options at extension time.
// later at instantiation we can check if Super's options have
// been updated.
Sub.superOptions = Super.options, Sub.extendOptions = extendOptions, Sub.sealedOptions = extend({}, Sub.options), // cache constructor
cachedCtors[SuperId] = Sub, Sub;
}, /**
* Create asset registration methods.
*/ ASSET_TYPES.forEach(function(type) {
Vue[type] = function(id, definition) {
return definition ? ('component' === type && validateComponentName(id), 'component' === type && isPlainObject(definition) && (definition.name = definition.name || id, definition = this.options._base.extend(definition)), 'directive' === type && 'function' == typeof definition && (definition = {
bind: definition,
update: definition
}), this.options[type + 's'][id] = definition, definition) : this.options[type + 's'][id];
};
}), Object.defineProperty(Vue1.prototype, '$isServer', {
get: isServerRendering
}), Object.defineProperty(Vue1.prototype, '$ssrContext', {
get: function() {
/* istanbul ignore next */ return this.$vnode && this.$vnode.ssrContext;
}
}), // expose FunctionalRenderContext for ssr runtime helper installation
Object.defineProperty(Vue1, 'FunctionalRenderContext', {
value: FunctionalRenderContext
}), Vue1.version = '2.6.12';
/* */ // these are reserved for web because they are directly compiled away
// during template compilation
var isReservedAttr = makeMap('style,class'), acceptValue = makeMap('input,textarea,option,select,progress'), mustUseProp = function(tag, type, attr) {
return 'value' === attr && acceptValue(tag) && 'button' !== type || 'selected' === attr && 'option' === tag || 'checked' === attr && 'input' === tag || 'muted' === attr && 'video' === tag;
}, isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck'), isValidContentEditableValue = makeMap('events,caret,typing,plaintext-only'), isBooleanAttr = makeMap("allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,default,defaultchecked,defaultmuted,defaultselected,defer,disabled,enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,required,reversed,scoped,seamless,selected,sortable,translate,truespeed,typemustmatch,visible"), xlinkNS = 'http://www.w3.org/1999/xlink', isXlink = function(name) {
return ':' === name.charAt(5) && 'xlink' === name.slice(0, 5);
}, getXlinkProp = function(name) {
return isXlink(name) ? name.slice(6, name.length) : '';
}, isFalsyAttrValue = function(val) {
return null == val || !1 === val;
};
function mergeClassData(child, parent) {
return {
staticClass: concat(child.staticClass, parent.staticClass),
class: isDef(child.class) ? [
child.class,
parent.class
] : parent.class
};
}
function concat(a, b) {
return a ? b ? a + ' ' + b : a : b || '';
}
function stringifyClass(value) {
return Array.isArray(value) ? function(value) {
for(var stringified, res = '', i = 0, l = value.length; i < l; i++)isDef(stringified = stringifyClass(value[i])) && '' !== stringified && (res && (res += ' '), res += stringified);
return res;
}(value) : isObject(value) ? function(value) {
var res = '';
for(var key in value)value[key] && (res && (res += ' '), res += key);
return res;
}(value) : 'string' == typeof value ? value : '';
}
/* */ var namespaceMap = {
svg: 'http://www.w3.org/2000/svg',
math: 'http://www.w3.org/1998/Math/MathML'
}, isHTMLTag = makeMap("html,body,base,head,link,meta,style,title,address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,menuitem,summary,content,element,shadow,template,blockquote,iframe,tfoot"), isSVG = makeMap("svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,foreignObject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view", !0), isReservedTag = function(tag) {
return isHTMLTag(tag) || isSVG(tag);
};
function getTagNamespace(tag) {
return isSVG(tag) ? 'svg' : 'math' === tag ? 'math' : void 0;
}
var unknownElementCache = Object.create(null), isTextInputType = makeMap('text,number,password,search,email,tel,url');
/* */ /**
* Query an element selector if it's not an element already.
*/ function query(el) {
return 'string' != typeof el ? el : document.querySelector(el) || (warn('Cannot find element: ' + el), document.createElement('div'));
}
var nodeOps = /*#__PURE__*/ Object.freeze({
createElement: /* */ function(tagName, vnode) {
var elm = document.createElement(tagName);
return 'select' !== tagName || vnode.data && vnode.data.attrs && void 0 !== vnode.data.attrs.multiple && elm.setAttribute('multiple', 'multiple'), elm;
},
createElementNS: function(namespace, tagName) {
return document.createElementNS(namespaceMap[namespace], tagName);
},
createTextNode: function(text) {
return document.createTextNode(text);
},
createComment: function(text) {
return document.createComment(text);
},
insertBefore: function(parentNode, newNode, referenceNode) {
parentNode.insertBefore(newNode, referenceNode);
},
removeChild: function(node, child) {
node.removeChild(child);
},
appendChild: function(node, child) {
node.appendChild(child);
},
parentNode: function(node) {
return node.parentNode;
},
nextSibling: function(node) {
return node.nextSibling;
},
tagName: function(node) {
return node.tagName;
},
setTextContent: function(node, text) {
node.textContent = text;
},
setStyleScope: function(node, scopeId) {
node.setAttribute(scopeId, '');
}
});
function registerRef(vnode, isRemoval) {
var key = vnode.data.ref;
if (isDef(key)) {
var vm = vnode.context, ref = vnode.componentInstance || vnode.elm, refs = vm.$refs;
isRemoval ? Array.isArray(refs[key]) ? remove(refs[key], ref) : refs[key] === ref && (refs[key] = void 0) : vnode.data.refInFor ? Array.isArray(refs[key]) ? 0 > refs[key].indexOf(ref) && // $flow-disable-line
refs[key].push(ref) : refs[key] = [
ref
] : refs[key] = ref;
}
}
/**
* Virtual DOM patching algorithm based on Snabbdom by
* Simon Friis Vindum (@paldepind)
* Licensed under the MIT License
* https://github.com/paldepind/snabbdom/blob/master/LICENSE
*
* modified by Evan You (@yyx990803)
*
* Not type-checking this because this file is perf-critical and the cost
* of making flow understand it is not worth it.
*/ var emptyNode = new VNode('', {}, []), hooks = [
'create',
'activate',
'update',
'remove',
'destroy'
];
function sameVnode(a, b) {
return a.key === b.key && (a.tag === b.tag && a.isComment === b.isComment && isDef(a.data) === isDef(b.data) && function(a, b) {
if ('input' !== a.tag) return !0;
var i, typeA = isDef(i = a.data) && isDef(i = i.attrs) && i.type, typeB = isDef(i = b.data) && isDef(i = i.attrs) && i.type;
return typeA === typeB || isTextInputType(typeA) && isTextInputType(typeB);
}(a, b) || isTrue(a.isAsyncPlaceholder) && a.asyncFactory === b.asyncFactory && isUndef(b.asyncFactory.error));
}
function updateDirectives(oldVnode, vnode) {
(oldVnode.data.directives || vnode.data.directives) && function(oldVnode, vnode) {
var key, oldDir, dir, isCreate = oldVnode === emptyNode, isDestroy = vnode === emptyNode, oldDirs = normalizeDirectives$1(oldVnode.data.directives, oldVnode.context), newDirs = normalizeDirectives$1(vnode.data.directives, vnode.context), dirsWithInsert = [], dirsWithPostpatch = [];
for(key in newDirs)oldDir = oldDirs[key], dir = newDirs[key], oldDir ? (// existing directive, update
dir.oldValue = oldDir.value, dir.oldArg = oldDir.arg, callHook$1(dir, 'update', vnode, oldVnode), dir.def && dir.def.componentUpdated && dirsWithPostpatch.push(dir)) : (// new directive, bind
callHook$1(dir, 'bind', vnode, oldVnode), dir.def && dir.def.inserted && dirsWithInsert.push(dir));
if (dirsWithInsert.length) {
var callInsert = function() {
for(var i = 0; i < dirsWithInsert.length; i++)callHook$1(dirsWithInsert[i], 'inserted', vnode, oldVnode);
};
isCreate ? mergeVNodeHook(vnode, 'insert', callInsert) : callInsert();
}
if (dirsWithPostpatch.length && mergeVNodeHook(vnode, 'postpatch', function() {
for(var i = 0; i < dirsWithPostpatch.length; i++)callHook$1(dirsWithPostpatch[i], 'componentUpdated', vnode, oldVnode);
}), !isCreate) for(key in oldDirs)newDirs[key] || // no longer present, unbind
callHook$1(oldDirs[key], 'unbind', oldVnode, oldVnode, isDestroy);
}(oldVnode, vnode);
}
var emptyModifiers = Object.create(null);
function normalizeDirectives$1(dirs, vm) {
var i, dir, res = Object.create(null);
if (!dirs) // $flow-disable-line
return res;
for(i = 0; i < dirs.length; i++)(dir = dirs[i]).modifiers || // $flow-disable-line
(dir.modifiers = emptyModifiers), res[dir.rawName || dir.name + "." + Object.keys(dir.modifiers || {}).join('.')] = dir, dir.def = resolveAsset(vm.$options, 'directives', dir.name, !0);
// $flow-disable-line
return res;
}
function callHook$1(dir, hook, vnode, oldVnode, isDestroy) {
var fn = dir.def && dir.def[hook];
if (fn) try {
fn(vnode.elm, dir, vnode, oldVnode, isDestroy);
} catch (e) {
handleError(e, vnode.context, "directive " + dir.name + " " + hook + " hook");
}
}
var baseModules = [
{
create: function(_, vnode) {
registerRef(vnode);
},
update: function(oldVnode, vnode) {
oldVnode.data.ref !== vnode.data.ref && (registerRef(oldVnode, !0), registerRef(vnode));
},
destroy: function(vnode) {
registerRef(vnode, !0);
}
},
{
create: updateDirectives,
update: updateDirectives,
destroy: function(vnode) {
updateDirectives(vnode, emptyNode);
}
}
];
/* */ function updateAttrs(oldVnode, vnode) {
var key, cur, opts = vnode.componentOptions;
if (!(isDef(opts) && !1 === opts.Ctor.options.inheritAttrs || isUndef(oldVnode.data.attrs) && isUndef(vnode.data.attrs))) {
var elm = vnode.elm, oldAttrs = oldVnode.data.attrs || {}, attrs = vnode.data.attrs || {};
for(key in isDef(attrs.__ob__) && (attrs = vnode.data.attrs = extend({}, attrs)), attrs)cur = attrs[key], oldAttrs[key] !== cur && setAttr(elm, key, cur);
for(key in (isIE || isEdge) && attrs.value !== oldAttrs.value && setAttr(elm, 'value', attrs.value), oldAttrs)isUndef(attrs[key]) && (isXlink(key) ? elm.removeAttributeNS(xlinkNS, getXlinkProp(key)) : isEnumeratedAttr(key) || elm.removeAttribute(key));
}
}
function setAttr(el, key, value) {
if (el.tagName.indexOf('-') > -1) baseSetAttr(el, key, value);
else if (isBooleanAttr(key)) // set attribute for blank value
// e.g. <option disabled>Select one</option>
isFalsyAttrValue(value) ? el.removeAttribute(key) : (// technically allowfullscreen is a boolean attribute for <iframe>,
// but Flash expects a value of "true" when used on <embed> tag
value = 'allowfullscreen' === key && 'EMBED' === el.tagName ? 'true' : key, el.setAttribute(key, value));
else if (isEnumeratedAttr(key)) {
var value1;
el.setAttribute(key, isFalsyAttrValue(value1 = value) || 'false' === value1 ? 'false' : 'contenteditable' === key && isValidContentEditableValue(value1) ? value1 : 'true');
} else isXlink(key) ? isFalsyAttrValue(value) ? el.removeAttributeNS(xlinkNS, getXlinkProp(key)) : el.setAttributeNS(xlinkNS, key, value) : baseSetAttr(el, key, value);
}
function baseSetAttr(el, key, value) {
if (isFalsyAttrValue(value)) el.removeAttribute(key);
else {
// #7138: IE10 & 11 fires input event when setting placeholder on
// <textarea>... block the first input event and remove the blocker
// immediately.
/* istanbul ignore if */ if (isIE && !isIE9 && 'TEXTAREA' === el.tagName && 'placeholder' === key && '' !== value && !el.__ieph) {
var blocker = function(e) {
e.stopImmediatePropagation(), el.removeEventListener('input', blocker);
};
el.addEventListener('input', blocker), // $flow-disable-line
el.__ieph = !0;
}
el.setAttribute(key, value);
}
}
/* */ function updateClass(oldVnode, vnode) {
var el = vnode.elm, data = vnode.data, oldData = oldVnode.data;
if (!(isUndef(data.staticClass) && isUndef(data.class) && (isUndef(oldData) || isUndef(oldData.staticClass) && isUndef(oldData.class)))) {
var cls = /* */ function(vnode) {
for(var staticClass, dynamicClass, data = vnode.data, parentNode = vnode, childNode = vnode; isDef(childNode.componentInstance);)(childNode = childNode.componentInstance._vnode) && childNode.data && (data = mergeClassData(childNode.data, data));
for(; isDef(parentNode = parentNode.parent);)parentNode && parentNode.data && (data = mergeClassData(data, parentNode.data));
return staticClass = data.staticClass, dynamicClass = data.class, isDef(staticClass) || isDef(dynamicClass) ? concat(staticClass, stringifyClass(dynamicClass)) : '';
}(vnode), transitionClass = el._transitionClasses;
isDef(transitionClass) && (cls = concat(cls, stringifyClass(transitionClass))), cls !== el._prevClass && (el.setAttribute('class', cls), el._prevClass = cls);
}
}
/* */ var validDivisionCharRE = /[\w).+\-_$\]]/;
function parseFilters(exp) {
var c, prev, i, expression, filters, inSingle = !1, inDouble = !1, inTemplateString = !1, inRegex = !1, curly = 0, square = 0, paren = 0, lastFilterIndex = 0;
for(i = 0; i < exp.length; i++)if (prev = c, c = exp.charCodeAt(i), inSingle) 0x27 === c && 0x5C !== prev && (inSingle = !1);
else if (inDouble) 0x22 === c && 0x5C !== prev && (inDouble = !1);
else if (inTemplateString) 0x60 === c && 0x5C !== prev && (inTemplateString = !1);
else if (inRegex) 0x2f === c && 0x5C !== prev && (inRegex = !1);
else if (0x7C !== c || // pipe
0x7C === exp.charCodeAt(i + 1) || 0x7C === exp.charCodeAt(i - 1) || curly || square || paren) {
switch(c){
case 0x22:
inDouble = !0;
break; // "
case 0x27:
inSingle = !0;
break; // '
case 0x60:
inTemplateString = !0;
break; // `
case 0x28:
paren++;
break; // (
case 0x29:
paren--;
break; // )
case 0x5B:
square++;
break; // [
case 0x5D:
square--;
break; // ]
case 0x7B:
curly++;
break; // {
case 0x7D:
curly--;
}
if (0x2f === c) {
// find first non-whitespace prev char
for(var j = i - 1, p = void 0; j >= 0 && ' ' === (p = exp.charAt(j)); j--);
p && validDivisionCharRE.test(p) || (inRegex = !0);
}
} else void 0 === expression ? (// first filter, end of expression
lastFilterIndex = i + 1, expression = exp.slice(0, i).trim()) : pushFilter();
function pushFilter() {
(filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim()), lastFilterIndex = i + 1;
}
if (void 0 === expression ? expression = exp.slice(0, i).trim() : 0 !== lastFilterIndex && pushFilter(), filters) for(i = 0; i < filters.length; i++)expression = function(exp, filter) {
var i = filter.indexOf('(');
if (i < 0) // _f: resolveFilter
return "_f(\"" + filter + "\")(" + exp + ")";
var name = filter.slice(0, i), args = filter.slice(i + 1);
return "_f(\"" + name + "\")(" + exp + (')' !== args ? ',' + args : args);
}(expression, filters[i]);
return expression;
}
/* */ /* eslint-disable no-unused-vars */ function baseWarn(msg, range) {
console.error("[Vue compiler]: " + msg);
}
/* eslint-enable no-unused-vars */ function pluckModuleFunction(modules, key) {
return modules ? modules.map(function(m) {
return m[key];
}).filter(function(_) {
return _;
}) : [];
}
function addProp(el, name, value, range, dynamic) {
(el.props || (el.props = [])).push(rangeSetItem({
name: name,
value: value,
dynamic: dynamic
}, range)), el.plain = !1;
}
function addAttr(el, name, value, range, dynamic) {
(dynamic ? el.dynamicAttrs || (el.dynamicAttrs = []) : el.attrs || (el.attrs = [])).push(rangeSetItem({
name: name,
value: value,
dynamic: dynamic
}, range)), el.plain = !1;
}
// add a raw attr (use this in preTransforms)
function addRawAttr(el, name, value, range) {
el.attrsMap[name] = value, el.attrsList.push(rangeSetItem({
name: name,
value: value
}, range));
}
function prependModifierMarker(symbol, name, dynamic) {
return dynamic ? "_p(" + name + ",\"" + symbol + "\")" : symbol + name // mark the event as captured
;
}
function addHandler(el, name, value, modifiers, important, warn, range, dynamic) {
modifiers = modifiers || emptyObject, warn && modifiers.prevent && modifiers.passive && warn("passive and prevent can't be used together. Passive handler can't prevent default event.", range), modifiers.right ? dynamic ? name = "(" + name + ")==='click'?'contextmenu':(" + name + ")" : 'click' === name && (name = 'contextmenu', delete modifiers.right) : modifiers.middle && (dynamic ? name = "(" + name + ")==='click'?'mouseup':(" + name + ")" : 'click' === name && (name = 'mouseup')), modifiers.capture && (delete modifiers.capture, name = prependModifierMarker('!', name, dynamic)), modifiers.once && (delete modifiers.once, name = prependModifierMarker('~', name, dynamic)), modifiers.passive && (delete modifiers.passive, name = prependModifierMarker('&', name, dynamic)), modifiers.native ? (delete modifiers.native, events = el.nativeEvents || (el.nativeEvents = {})) : events = el.events || (el.events = {});
var events, newHandler = rangeSetItem({
value: value.trim(),
dynamic: dynamic
}, range);
modifiers !== emptyObject && (newHandler.modifiers = modifiers);
var handlers = events[name];
Array.isArray(handlers) ? important ? handlers.unshift(newHandler) : handlers.push(newHandler) : handlers ? events[name] = important ? [
newHandler,
handlers
] : [
handlers,
newHandler
] : events[name] = newHandler, el.plain = !1;
}
function getRawBindingAttr(el, name) {
return el.rawAttrsMap[':' + name] || el.rawAttrsMap['v-bind:' + name] || el.rawAttrsMap[name];
}
function getBindingAttr(el, name, getStatic) {
var dynamicValue = getAndRemoveAttr(el, ':' + name) || getAndRemoveAttr(el, 'v-bind:' + name);
if (null != dynamicValue) return parseFilters(dynamicValue);
if (!1 !== getStatic) {
var staticValue = getAndRemoveAttr(el, name);
if (null != staticValue) return JSON.stringify(staticValue);
}
}
// note: this only removes the attr from the Array (attrsList) so that it
// doesn't get processed by processAttrs.
// By default it does NOT remove it from the map (attrsMap) because the map is
// needed during codegen.
function getAndRemoveAttr(el, name, removeFromMap) {
var val;
if (null != (val = el.attrsMap[name])) {
for(var list = el.attrsList, i = 0, l = list.length; i < l; i++)if (list[i].name === name) {
list.splice(i, 1);
break;
}
}
return removeFromMap && delete el.attrsMap[name], val;
}
function getAndRemoveAttrByRegex(el, name) {
for(var list = el.attrsList, i = 0, l = list.length; i < l; i++){
var attr = list[i];
if (name.test(attr.name)) return list.splice(i, 1), attr;
}
}
function rangeSetItem(item, range) {
return range && (null != range.start && (item.start = range.start), null != range.end && (item.end = range.end)), item;
}
/* */ /**
* Cross-platform code generation for component v-model
*/ function genComponentModel(el, value, modifiers) {
var ref = modifiers || {}, number = ref.number, trim = ref.trim, valueExpression = '$$v';
trim && (valueExpression = "(typeof $$v === 'string'? $$v.trim(): $$v)"), number && (valueExpression = "_n(" + valueExpression + ")");
var assignment = genAssignmentCode(value, valueExpression);
el.model = {
value: "(" + value + ")",
expression: JSON.stringify(value),
callback: "function ($$v) {" + assignment + "}"
};
}
/**
* Cross-platform codegen helper for generating v-model value assignment code.
*/ function genAssignmentCode(value, assignment) {
var res = function(val) {
if (len = // Fix https://github.com/vuejs/vue/pull/7730
// allow v-model="obj.val " (trailing whitespace)
(val = val.trim()).length, 0 > val.indexOf('[') || val.lastIndexOf(']') < len - 1) return (index$1 = val.lastIndexOf('.')) > -1 ? {
exp: val.slice(0, index$1),
key: '"' + val.slice(index$1 + 1) + '"'
} : {
exp: val,
key: null
};
for(str = val, index$1 = expressionPos = expressionEndPos = 0; !(index$1 >= len);)/* istanbul ignore if */ isStringStart(chr = next()) ? parseString(chr) : 0x5B === chr && function(chr) {
var inBracket = 1;
for(expressionPos = index$1; !(index$1 >= len);){
if (isStringStart(chr = next())) {
parseString(chr);
continue;
}
if (0x5B === chr && inBracket++, 0x5D === chr && inBracket--, 0 === inBracket) {
expressionEndPos = index$1;
break;
}
}
}(chr);
return {
exp: val.slice(0, expressionPos),
key: val.slice(expressionPos + 1, expressionEndPos)
};
}(value);
return null === res.key ? value + "=" + assignment : "$set(" + res.exp + ", " + res.key + ", " + assignment + ")";
}
function next() {
return str.charCodeAt(++index$1);
}
function isStringStart(chr) {
return 0x22 === chr || 0x27 === chr;
}
function parseString(chr) {
for(var stringQuote = chr; !(index$1 >= len) && (chr = next()) !== stringQuote;);
}
function createOnceHandler$1(event, handler, capture) {
var _target = target$1; // save current target element in closure
return function onceHandler() {
var res = handler.apply(null, arguments);
null !== res && remove$2(event, onceHandler, capture, _target);
};
}
// #9446: Firefox <= 53 (in particular, ESR 52) has incorrect Event.timeStamp
// implementation and does not fire microtasks in between event propagation, so
// safe to exclude.
var useMicrotaskFix = isUsingMicroTask && !(isFF && 53 >= Number(isFF[1]));
function add$1(name, handler, capture, passive) {
// async edge case #6566: inner click event triggers patch, event handler
// attached to outer element during patch, and triggered again. This
// happens because browsers fire microtask ticks between event propagation.
// the solution is simple: we save the timestamp when a handler is attached,
// and the handler would only fire if the event passed to it was fired
// AFTER it was attached.
if (useMicrotaskFix) {
var attachedTimestamp = currentFlushTimestamp, original = handler;
handler = original._wrapper = function(e) {
if (// no bubbling, should always fire.
// this is just a safety net in case event.timeStamp is unreliable in
// certain weird environments...
e.target === e.currentTarget || // event is fired after handler attachment
e.timeStamp >= attachedTimestamp || // bail for environments that have buggy event.timeStamp implementations
// #9462 iOS 9 bug: event.timeStamp is 0 after history.pushState
// #9681 QtWebEngine event.timeStamp is negative value
e.timeStamp <= 0 || // #9448 bail if event is fired in another document in a multi-page
// electron/nw.js app, since event.timeStamp will be using a different
// starting reference
e.target.ownerDocument !== document) return original.apply(this, arguments);
};
}
target$1.addEventListener(name, handler, supportsPassive ? {
capture: capture,
passive: passive
} : capture);
}
function remove$2(name, handler, capture, _target) {
(_target || target$1).removeEventListener(name, handler._wrapper || handler, capture);
}
function updateDOMListeners(oldVnode, vnode) {
if (!(isUndef(oldVnode.data.on) && isUndef(vnode.data.on))) {
var on = vnode.data.on || {}, oldOn = oldVnode.data.on || {};
target$1 = vnode.elm, /* */ // normalize v-model event tokens that can only be determined at runtime.
// it's important to place the event as the first in the array because
// the whole point is ensuring the v-model callback gets called before
// user-attached handlers.
function(on) {
/* istanbul ignore if */ if (isDef(on.__r)) {
// IE input[type=range] only supports `change` event
var event = isIE ? 'change' : 'input';
on[event] = [].concat(on.__r, on[event] || []), delete on.__r;
}
// This was originally intended to fix #4521 but no longer necessary
// after 2.5. Keeping it for backwards compat with generated code from < 2.4
/* istanbul ignore if */ isDef(on.__c) && (on.change = [].concat(on.__c, on.change || []), delete on.__c);
}(on), updateListeners(on, oldOn, add$1, remove$2, createOnceHandler$1, vnode.context), target$1 = void 0;
}
}
function updateDOMProps(oldVnode, vnode) {
if (!(isUndef(oldVnode.data.domProps) && isUndef(vnode.data.domProps))) {
var key, cur, elm = vnode.elm, oldProps = oldVnode.data.domProps || {}, props = vnode.data.domProps || {};
for(key in isDef(props.__ob__) && (props = vnode.data.domProps = extend({}, props)), oldProps)key in props || (elm[key] = '');
for(key in props){
// ignore children if the node has textContent or innerHTML,
// as these will throw away existing DOM nodes and cause removal errors
// on subsequent patches (#3360)
if (cur = props[key], 'textContent' === key || 'innerHTML' === key) {
if (vnode.children && (vnode.children.length = 0), cur === oldProps[key]) continue;
1 === elm.childNodes.length && elm.removeChild(elm.childNodes[0]);
}
if ('value' === key && 'PROGRESS' !== elm.tagName) {
// store value as _value as well since
// non-string values will be stringified
elm._value = cur;
// avoid resetting cursor position when value is the same
var strCur = isUndef(cur) ? '' : String(cur);
!elm.composing && ('OPTION' === elm.tagName || function(elm, checkVal) {
// return true when textbox (.number and .trim) loses focus and its value is
// not equal to the updated value
var notInFocus = !0;
// #6157
// work around IE bug when accessing document.activeElement in an iframe
try {
notInFocus = document.activeElement !== elm;
} catch (e) {}
return notInFocus && elm.value !== checkVal;
}(elm, strCur) || function(elm, newVal) {
var value = elm.value, modifiers = elm._vModifiers;
if (isDef(modifiers)) {
if (modifiers.number) return toNumber(value) !== toNumber(newVal);
if (modifiers.trim) return value.trim() !== newVal.trim();
}
return value !== newVal;
}(elm, strCur)) && (elm.value = strCur);
} else if ('innerHTML' === key && isSVG(elm.tagName) && isUndef(elm.innerHTML)) {
// IE doesn't support innerHTML for SVG elements
(svgContainer = svgContainer || document.createElement('div')).innerHTML = "<svg>" + cur + "</svg>";
for(var svg = svgContainer.firstChild; elm.firstChild;)elm.removeChild(elm.firstChild);
for(; svg.firstChild;)elm.appendChild(svg.firstChild);
} else if (// skip the update if old and new VDOM state is the same.
// `value` is handled separately because the DOM value may be temporarily
// out of sync with VDOM state due to focus, composition and modifiers.
// This #4521 by skipping the unnecessary `checked` update.
cur !== oldProps[key]) // some property updates can throw
// e.g. `value` on <progress> w/ non-finite value
try {
elm[key] = cur;
} catch (e) {}
}
}
}
/* */ var parseStyleText = cached(function(cssText) {
var res = {}, propertyDelimiter = /:(.+)/;
return cssText.split(/;(?![^(]*\))/g).forEach(function(item) {
if (item) {
var tmp = item.split(propertyDelimiter);
tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim());
}
}), res;
});
// merge static and dynamic style data on the same vnode
function normalizeStyleData(data) {
var style = normalizeStyleBinding(data.style);
// static style is pre-processed into an object during compilation
// and is always a fresh object, so it's safe to merge into it
return data.staticStyle ? extend(data.staticStyle, style) : style;
}
// normalize possible array / string values into Object
function normalizeStyleBinding(bindingStyle) {
return Array.isArray(bindingStyle) ? toObject(bindingStyle) : 'string' == typeof bindingStyle ? parseStyleText(bindingStyle) : bindingStyle;
}
/* */ var cssVarRE = /^--/, importantRE = /\s*!important$/, setProp = function(el, name, val) {
/* istanbul ignore if */ if (cssVarRE.test(name)) el.style.setProperty(name, val);
else if (importantRE.test(val)) el.style.setProperty(hyphenate(name), val.replace(importantRE, ''), 'important');
else {
var normalizedName = normalize(name);
if (Array.isArray(val)) // Support values array created by autoprefixer, e.g.
// {display: ["-webkit-box", "-ms-flexbox", "flex"]}
// Set them one by one, and the browser will only set those it can recognize
for(var i = 0, len = val.length; i < len; i++)el.style[normalizedName] = val[i];
else el.style[normalizedName] = val;
}
}, vendorNames = [
'Webkit',
'Moz',
'ms'
], normalize = cached(function(prop) {
if (emptyStyle = emptyStyle || document.createElement('div').style, 'filter' !== (prop = camelize(prop)) && prop in emptyStyle) return prop;
for(var capName = prop.charAt(0).toUpperCase() + prop.slice(1), i = 0; i < vendorNames.length; i++){
var name = vendorNames[i] + capName;
if (name in emptyStyle) return name;
}
});
function updateStyle(oldVnode, vnode) {
var cur, name, data = vnode.data, oldData = oldVnode.data;
if (!(isUndef(data.staticStyle) && isUndef(data.style) && isUndef(oldData.staticStyle) && isUndef(oldData.style))) {
var el = vnode.elm, oldStaticStyle = oldData.staticStyle, oldStyleBinding = oldData.normalizedStyle || oldData.style || {}, oldStyle = oldStaticStyle || oldStyleBinding, style = normalizeStyleBinding(vnode.data.style) || {};
// store normalized style under a different key for next diff
// make sure to clone it if it's reactive, since the user likely wants
// to mutate it.
vnode.data.normalizedStyle = isDef(style.__ob__) ? extend({}, style) : style;
var newStyle = /**
* parent component style should be after child's
* so that parent component's style could override it
*/ function(vnode, checkChild) {
var styleData, res = {};
if (checkChild) for(var childNode = vnode; childNode.componentInstance;)(childNode = childNode.componentInstance._vnode) && childNode.data && (styleData = normalizeStyleData(childNode.data)) && extend(res, styleData);
(styleData = normalizeStyleData(vnode.data)) && extend(res, styleData);
for(var parentNode = vnode; parentNode = parentNode.parent;)parentNode.data && (styleData = normalizeStyleData(parentNode.data)) && extend(res, styleData);
return res;
}(vnode, !0);
for(name in oldStyle)isUndef(newStyle[name]) && setProp(el, name, '');
for(name in newStyle)(cur = newStyle[name]) !== oldStyle[name] && // ie9 setting to null has no effect, must use empty string
setProp(el, name, null == cur ? '' : cur);
}
}
/* */ var whitespaceRE = /\s+/;
/**
* Add class with compatibility for SVG since classList is not supported on
* SVG elements in IE
*/ function addClass(el, cls) {
/* istanbul ignore if */ if (cls && (cls = cls.trim())) {
/* istanbul ignore else */ if (el.classList) cls.indexOf(' ') > -1 ? cls.split(whitespaceRE).forEach(function(c) {
return el.classList.add(c);
}) : el.classList.add(cls);
else {
var cur = " " + (el.getAttribute('class') || '') + " ";
0 > cur.indexOf(' ' + cls + ' ') && el.setAttribute('class', (cur + cls).trim());
}
}
}
/**
* Remove class with compatibility for SVG since classList is not supported on
* SVG elements in IE
*/ function removeClass(el, cls) {
/* istanbul ignore if */ if (cls && (cls = cls.trim())) {
/* istanbul ignore else */ if (el.classList) cls.indexOf(' ') > -1 ? cls.split(whitespaceRE).forEach(function(c) {
return el.classList.remove(c);
}) : el.classList.remove(cls), el.classList.length || el.removeAttribute('class');
else {
for(var cur = " " + (el.getAttribute('class') || '') + " ", tar = ' ' + cls + ' '; cur.indexOf(tar) >= 0;)cur = cur.replace(tar, ' ');
(cur = cur.trim()) ? el.setAttribute('class', cur) : el.removeAttribute('class');
}
}
}
/* */ function resolveTransition(def$$1) {
if (def$$1) {
/* istanbul ignore else */ if ('object' == typeof def$$1) {
var res = {};
return !1 !== def$$1.css && extend(res, autoCssTransition(def$$1.name || 'v')), extend(res, def$$1), res;
}
if ('string' == typeof def$$1) return autoCssTransition(def$$1);
}
}
var autoCssTransition = cached(function(name) {
return {
enterClass: name + "-enter",
enterToClass: name + "-enter-to",
enterActiveClass: name + "-enter-active",
leaveClass: name + "-leave",
leaveToClass: name + "-leave-to",
leaveActiveClass: name + "-leave-active"
};
}), hasTransition = inBrowser && !isIE9, TRANSITION = 'transition', ANIMATION = 'animation', transitionProp = 'transition', transitionEndEvent = 'transitionend', animationProp = 'animation', animationEndEvent = 'animationend';
hasTransition && (void 0 === window.ontransitionend && void 0 !== window.onwebkittransitionend && (transitionProp = 'WebkitTransition', transitionEndEvent = 'webkitTransitionEnd'), void 0 === window.onanimationend && void 0 !== window.onwebkitanimationend && (animationProp = 'WebkitAnimation', animationEndEvent = 'webkitAnimationEnd'));
// binding to window is necessary to make hot reload work in IE in strict mode
var raf = inBrowser ? window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : setTimeout : /* istanbul ignore next */ function(fn) {
return fn();
};
function nextFrame(fn) {
raf(function() {
raf(fn);
});
}
function addTransitionClass(el, cls) {
var transitionClasses = el._transitionClasses || (el._transitionClasses = []);
0 > transitionClasses.indexOf(cls) && (transitionClasses.push(cls), addClass(el, cls));
}
function removeTransitionClass(el, cls) {
el._transitionClasses && remove(el._transitionClasses, cls), removeClass(el, cls);
}
function whenTransitionEnds(el, expectedType, cb) {
var ref = getTransitionInfo(el, expectedType), type = ref.type, timeout = ref.timeout, propCount = ref.propCount;
if (!type) return cb();
var event = type === TRANSITION ? transitionEndEvent : animationEndEvent, ended = 0, end = function() {
el.removeEventListener(event, onEnd), cb();
}, onEnd = function(e) {
e.target === el && ++ended >= propCount && end();
};
setTimeout(function() {
ended < propCount && end();
}, timeout + 1), el.addEventListener(event, onEnd);
}
var transformRE = /\b(transform|all)(,|$)/;
function getTransitionInfo(el, expectedType) {
var type, styles = window.getComputedStyle(el), transitionDelays = (styles[transitionProp + 'Delay'] || '').split(', '), transitionDurations = (styles[transitionProp + 'Duration'] || '').split(', '), transitionTimeout = getTimeout(transitionDelays, transitionDurations), animationDelays = (styles[animationProp + 'Delay'] || '').split(', '), animationDurations = (styles[animationProp + 'Duration'] || '').split(', '), animationTimeout = getTimeout(animationDelays, animationDurations), timeout = 0, propCount = 0;
/* istanbul ignore if */ expectedType === TRANSITION ? transitionTimeout > 0 && (type = TRANSITION, timeout = transitionTimeout, propCount = transitionDurations.length) : expectedType === ANIMATION ? animationTimeout > 0 && (type = ANIMATION, timeout = animationTimeout, propCount = animationDurations.length) : propCount = (type = (timeout = Math.max(transitionTimeout, animationTimeout)) > 0 ? transitionTimeout > animationTimeout ? TRANSITION : ANIMATION : null) ? type === TRANSITION ? transitionDurations.length : animationDurations.length : 0;
var hasTransform = type === TRANSITION && transformRE.test(styles[transitionProp + 'Property']);
return {
type: type,
timeout: timeout,
propCount: propCount,
hasTransform: hasTransform
};
}
function getTimeout(delays, durations) {
/* istanbul ignore next */ for(; delays.length < durations.length;)delays = delays.concat(delays);
return Math.max.apply(null, durations.map(function(d, i) {
return toMs(d) + toMs(delays[i]);
}));
}
// Old versions of Chromium (below 61.0.3163.100) formats floating pointer numbers
// in a locale-dependent way, using a comma instead of a dot.
// If comma is not replaced with a dot, the input will be rounded down (i.e. acting
// as a floor function) causing unexpected behaviors
function toMs(s) {
return 1000 * Number(s.slice(0, -1).replace(',', '.'));
}
/* */ function enter(vnode, toggleDisplay) {
var el = vnode.elm;
isDef(el._leaveCb) && (el._leaveCb.cancelled = !0, el._leaveCb());
var data = resolveTransition(vnode.data.transition);
if (!(isUndef(data) || isDef(el._enterCb)) && 1 === el.nodeType) {
for(var css = data.css, type = data.type, enterClass = data.enterClass, enterToClass = data.enterToClass, enterActiveClass = data.enterActiveClass, appearClass = data.appearClass, appearToClass = data.appearToClass, appearActiveClass = data.appearActiveClass, beforeEnter = data.beforeEnter, enter = data.enter, afterEnter = data.afterEnter, enterCancelled = data.enterCancelled, beforeAppear = data.beforeAppear, appear = data.appear, afterAppear = data.afterAppear, appearCancelled = data.appearCancelled, duration = data.duration, context = activeInstance, transitionNode = activeInstance.$vnode; transitionNode && transitionNode.parent;)context = transitionNode.context, transitionNode = transitionNode.parent;
var isAppear = !context._isMounted || !vnode.isRootInsert;
if (!isAppear || appear || '' === appear) {
var startClass = isAppear && appearClass ? appearClass : enterClass, activeClass = isAppear && appearActiveClass ? appearActiveClass : enterActiveClass, toClass = isAppear && appearToClass ? appearToClass : enterToClass, beforeEnterHook = isAppear && beforeAppear || beforeEnter, enterHook = isAppear && 'function' == typeof appear ? appear : enter, afterEnterHook = isAppear && afterAppear || afterEnter, enterCancelledHook = isAppear && appearCancelled || enterCancelled, explicitEnterDuration = toNumber(isObject(duration) ? duration.enter : duration);
null != explicitEnterDuration && checkDuration(explicitEnterDuration, 'enter', vnode);
var expectsCSS = !1 !== css && !isIE9, userWantsControl = getHookArgumentsLength(enterHook), cb = el._enterCb = once(function() {
expectsCSS && (removeTransitionClass(el, toClass), removeTransitionClass(el, activeClass)), cb.cancelled ? (expectsCSS && removeTransitionClass(el, startClass), enterCancelledHook && enterCancelledHook(el)) : afterEnterHook && afterEnterHook(el), el._enterCb = null;
});
vnode.data.show || // remove pending leave element on enter by injecting an insert hook
mergeVNodeHook(vnode, 'insert', function() {
var parent = el.parentNode, pendingNode = parent && parent._pending && parent._pending[vnode.key];
pendingNode && pendingNode.tag === vnode.tag && pendingNode.elm._leaveCb && pendingNode.elm._leaveCb(), enterHook && enterHook(el, cb);
}), // start enter transition
beforeEnterHook && beforeEnterHook(el), expectsCSS && (addTransitionClass(el, startClass), addTransitionClass(el, activeClass), nextFrame(function() {
removeTransitionClass(el, startClass), cb.cancelled || (addTransitionClass(el, toClass), userWantsControl || (isValidDuration(explicitEnterDuration) ? setTimeout(cb, explicitEnterDuration) : whenTransitionEnds(el, type, cb)));
})), vnode.data.show && (toggleDisplay && toggleDisplay(), enterHook && enterHook(el, cb)), expectsCSS || userWantsControl || cb();
}
}
}
function leave(vnode, rm) {
var el = vnode.elm;
isDef(el._enterCb) && (el._enterCb.cancelled = !0, el._enterCb());
var data = resolveTransition(vnode.data.transition);
if (isUndef(data) || 1 !== el.nodeType) return rm();
/* istanbul ignore if */ if (!isDef(el._leaveCb)) {
var css = data.css, type = data.type, leaveClass = data.leaveClass, leaveToClass = data.leaveToClass, leaveActiveClass = data.leaveActiveClass, beforeLeave = data.beforeLeave, leave = data.leave, afterLeave = data.afterLeave, leaveCancelled = data.leaveCancelled, delayLeave = data.delayLeave, duration = data.duration, expectsCSS = !1 !== css && !isIE9, userWantsControl = getHookArgumentsLength(leave), explicitLeaveDuration = toNumber(isObject(duration) ? duration.leave : duration);
isDef(explicitLeaveDuration) && checkDuration(explicitLeaveDuration, 'leave', vnode);
var cb = el._leaveCb = once(function() {
el.parentNode && el.parentNode._pending && (el.parentNode._pending[vnode.key] = null), expectsCSS && (removeTransitionClass(el, leaveToClass), removeTransitionClass(el, leaveActiveClass)), cb.cancelled ? (expectsCSS && removeTransitionClass(el, leaveClass), leaveCancelled && leaveCancelled(el)) : (rm(), afterLeave && afterLeave(el)), el._leaveCb = null;
});
delayLeave ? delayLeave(performLeave) : performLeave();
}
function performLeave() {
// the delayed leave may have already been cancelled
!cb.cancelled && (!vnode.data.show && el.parentNode && ((el.parentNode._pending || (el.parentNode._pending = {}))[vnode.key] = vnode), beforeLeave && beforeLeave(el), expectsCSS && (addTransitionClass(el, leaveClass), addTransitionClass(el, leaveActiveClass), nextFrame(function() {
removeTransitionClass(el, leaveClass), cb.cancelled || (addTransitionClass(el, leaveToClass), userWantsControl || (isValidDuration(explicitLeaveDuration) ? setTimeout(cb, explicitLeaveDuration) : whenTransitionEnds(el, type, cb)));
})), leave && leave(el, cb), expectsCSS || userWantsControl || cb());
}
}
// only used in dev mode
function checkDuration(val, name, vnode) {
'number' != typeof val ? warn("<transition> explicit " + name + " duration is not a valid number - got " + JSON.stringify(val) + ".", vnode.context) : isNaN(val) && warn("<transition> explicit " + name + " duration is NaN - the duration expression might be incorrect.", vnode.context);
}
function isValidDuration(val) {
return 'number' == typeof val && !isNaN(val);
}
/**
* Normalize a transition hook's argument length. The hook may be:
* - a merged hook (invoker) with the original in .fns
* - a wrapped component method (check ._length)
* - a plain function (.length)
*/ function getHookArgumentsLength(fn) {
if (isUndef(fn)) return !1;
var invokerFns = fn.fns;
return isDef(invokerFns) ? getHookArgumentsLength(Array.isArray(invokerFns) ? invokerFns[0] : invokerFns) : (fn._length || fn.length) > 1;
}
function _enter(_, vnode) {
!0 !== vnode.data.show && enter(vnode);
}
var patch = function(backend) {
var i, j, cbs = {}, modules = backend.modules, nodeOps = backend.nodeOps;
for(i = 0; i < hooks.length; ++i)for(j = 0, cbs[hooks[i]] = []; j < modules.length; ++j)isDef(modules[j][hooks[i]]) && cbs[hooks[i]].push(modules[j][hooks[i]]);
function removeNode(el) {
var parent = nodeOps.parentNode(el);
// element may have already been removed due to v-html / v-text
isDef(parent) && nodeOps.removeChild(parent, el);
}
function isUnknownElement$$1(vnode, inVPre) {
return !inVPre && !vnode.ns && !(config.ignoredElements.length && config.ignoredElements.some(function(ignore) {
return isRegExp(ignore) ? ignore.test(vnode.tag) : ignore === vnode.tag;
})) && config.isUnknownElement(vnode.tag);
}
var creatingElmInVPre = 0;
function createElm(vnode, insertedVnodeQueue, parentElm, refElm, nested, ownerArray, index) {
if (isDef(vnode.elm) && isDef(ownerArray) && // This vnode was used in a previous render!
// now it's used as a new node, overwriting its elm would cause
// potential patch errors down the road when it's used as an insertion
// reference node. Instead, we clone the node on-demand before creating
// associated DOM element for it.
(vnode = ownerArray[index] = cloneVNode(vnode)), vnode.isRootInsert = !nested, !function(vnode, insertedVnodeQueue, parentElm, refElm) {
var i = vnode.data;
if (isDef(i)) {
var isReactivated = isDef(vnode.componentInstance) && i.keepAlive;
// after calling the init hook, if the vnode is a child component
// it should've created a child instance and mounted it. the child
// component also has set the placeholder vnode's elm.
// in that case we can just return the element and be done.
if (isDef(i = i.hook) && isDef(i = i.init) && i(vnode, !1), isDef(vnode.componentInstance)) return initComponent(vnode, insertedVnodeQueue), insert(parentElm, vnode.elm, refElm), isTrue(isReactivated) && function(vnode, insertedVnodeQueue, parentElm, refElm) {
for(// hack for #4339: a reactivated component with inner transition
// does not trigger because the inner node's created hooks are not called
// again. It's not ideal to involve module-specific logic in here but
// there doesn't seem to be a better way to do it.
var i, innerNode = vnode; innerNode.componentInstance;)if (isDef(i = (innerNode = innerNode.componentInstance._vnode).data) && isDef(i = i.transition)) {
for(i = 0; i < cbs.activate.length; ++i)cbs.activate[i](emptyNode, innerNode);
insertedVnodeQueue.push(innerNode);
break;
}
// unlike a newly created component,
// a reactivated keep-alive component doesn't insert itself
insert(parentElm, vnode.elm, refElm);
}(vnode, insertedVnodeQueue, parentElm, refElm), !0;
}
}(vnode, insertedVnodeQueue, parentElm, refElm)) {
var data = vnode.data, children = vnode.children, tag = vnode.tag;
isDef(tag) ? (data && data.pre && creatingElmInVPre++, isUnknownElement$$1(vnode, creatingElmInVPre) && warn('Unknown custom element: <' + tag + '> - did you register the component correctly? For recursive components, make sure to provide the "name" option.', vnode.context), vnode.elm = vnode.ns ? nodeOps.createElementNS(vnode.ns, tag) : nodeOps.createElement(tag, vnode), setScope(vnode), createChildren(vnode, children, insertedVnodeQueue), isDef(data) && invokeCreateHooks(vnode, insertedVnodeQueue), insert(parentElm, vnode.elm, refElm), data && data.pre && creatingElmInVPre--) : (isTrue(vnode.isComment) ? vnode.elm = nodeOps.createComment(vnode.text) : vnode.elm = nodeOps.createTextNode(vnode.text), insert(parentElm, vnode.elm, refElm));
}
}
function initComponent(vnode, insertedVnodeQueue) {
isDef(vnode.data.pendingInsert) && (insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert), vnode.data.pendingInsert = null), vnode.elm = vnode.componentInstance.$el, isPatchable(vnode) ? (invokeCreateHooks(vnode, insertedVnodeQueue), setScope(vnode)) : (// empty component root.
// skip all element-related modules except for ref (#3455)
registerRef(vnode), // make sure to invoke the insert hook
insertedVnodeQueue.push(vnode));
}
function insert(parent, elm, ref$$1) {
isDef(parent) && (isDef(ref$$1) ? nodeOps.parentNode(ref$$1) === parent && nodeOps.insertBefore(parent, elm, ref$$1) : nodeOps.appendChild(parent, elm));
}
function createChildren(vnode, children, insertedVnodeQueue) {
if (Array.isArray(children)) {
checkDuplicateKeys(children);
for(var i = 0; i < children.length; ++i)createElm(children[i], insertedVnodeQueue, vnode.elm, null, !0, children, i);
} else isPrimitive(vnode.text) && nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(String(vnode.text)));
}
function isPatchable(vnode) {
for(; vnode.componentInstance;)vnode = vnode.componentInstance._vnode;
return isDef(vnode.tag);
}
function invokeCreateHooks(vnode, insertedVnodeQueue) {
for(var i$1 = 0; i$1 < cbs.create.length; ++i$1)cbs.create[i$1](emptyNode, vnode);
isDef(i = vnode.data.hook) && (isDef(i.create) && i.create(emptyNode, vnode), isDef(i.insert) && insertedVnodeQueue.push(vnode));
}
// set scope id attribute for scoped CSS.
// this is implemented as a special case to avoid the overhead
// of going through the normal attribute patching process.
function setScope(vnode) {
var i;
if (isDef(i = vnode.fnScopeId)) nodeOps.setStyleScope(vnode.elm, i);
else for(var ancestor = vnode; ancestor;)isDef(i = ancestor.context) && isDef(i = i.$options._scopeId) && nodeOps.setStyleScope(vnode.elm, i), ancestor = ancestor.parent;
// for slot content they should also get the scopeId from the host instance.
isDef(i = activeInstance) && i !== vnode.context && i !== vnode.fnContext && isDef(i = i.$options._scopeId) && nodeOps.setStyleScope(vnode.elm, i);
}
function addVnodes(parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) {
for(; startIdx <= endIdx; ++startIdx)createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm, !1, vnodes, startIdx);
}
function invokeDestroyHook(vnode) {
var i, j, data = vnode.data;
if (isDef(data)) for(isDef(i = data.hook) && isDef(i = i.destroy) && i(vnode), i = 0; i < cbs.destroy.length; ++i)cbs.destroy[i](vnode);
if (isDef(i = vnode.children)) for(j = 0; j < vnode.children.length; ++j)invokeDestroyHook(vnode.children[j]);
}
function removeVnodes(vnodes, startIdx, endIdx) {
for(; startIdx <= endIdx; ++startIdx){
var ch = vnodes[startIdx];
isDef(ch) && (isDef(ch.tag) ? (function removeAndInvokeRemoveHook(vnode, rm) {
if (isDef(rm) || isDef(vnode.data)) {
var i, listeners = cbs.remove.length + 1;
for(isDef(rm) ? // we have a recursively passed down rm callback
// increase the listeners count
rm.listeners += listeners : // directly removing
rm = function(childElm, listeners) {
function remove$$1() {
0 == --remove$$1.listeners && removeNode(childElm);
}
return remove$$1.listeners = listeners, remove$$1;
}(vnode.elm, listeners), isDef(i = vnode.componentInstance) && isDef(i = i._vnode) && isDef(i.data) && removeAndInvokeRemoveHook(i, rm), i = 0; i < cbs.remove.length; ++i)cbs.remove[i](vnode, rm);
isDef(i = vnode.data.hook) && isDef(i = i.remove) ? i(vnode, rm) : rm();
} else removeNode(vnode.elm);
}(ch), invokeDestroyHook(ch)) : removeNode(ch.elm));
}
}
function checkDuplicateKeys(children) {
for(var seenKeys = {}, i = 0; i < children.length; i++){
var vnode = children[i], key = vnode.key;
isDef(key) && (seenKeys[key] ? warn("Duplicate keys detected: '" + key + "'. This may cause an update error.", vnode.context) : seenKeys[key] = !0);
}
}
function invokeInsertHook(vnode, queue, initial) {
// delay insert hooks for component root nodes, invoke them after the
// element is really inserted
if (isTrue(initial) && isDef(vnode.parent)) vnode.parent.data.pendingInsert = queue;
else for(var i = 0; i < queue.length; ++i)queue[i].data.hook.insert(queue[i]);
}
var hydrationBailed = !1, isRenderedModule = makeMap('attrs,class,staticClass,staticStyle,key');
// Note: this is a browser-only function so we can assume elms are DOM nodes.
function hydrate(elm, vnode, insertedVnodeQueue, inVPre) {
var inVPre1, i, tag = vnode.tag, data = vnode.data, children = vnode.children;
if (inVPre = inVPre || data && data.pre, vnode.elm = elm, isTrue(vnode.isComment) && isDef(vnode.asyncFactory)) return vnode.isAsyncPlaceholder = !0, !0;
if (inVPre1 = inVPre, isDef(vnode.tag) ? 0 !== vnode.tag.indexOf('vue-component') && (!!isUnknownElement$$1(vnode, inVPre1) || vnode.tag.toLowerCase() !== (elm.tagName && elm.tagName.toLowerCase())) : elm.nodeType !== (vnode.isComment ? 8 : 3)) return !1;
if (isDef(data) && (isDef(i = data.hook) && isDef(i = i.init) && i(vnode, !0), isDef(i = vnode.componentInstance))) return(// child component. it should have hydrated its own tree.
initComponent(vnode, insertedVnodeQueue), !0);
if (isDef(tag)) {
if (isDef(children)) {
// empty element, allow client to pick up and populate children
if (elm.hasChildNodes()) {
// v-html and domProps: innerHTML
if (isDef(i = data) && isDef(i = i.domProps) && isDef(i = i.innerHTML)) {
if (i !== elm.innerHTML) return 'undefined' == typeof console || hydrationBailed || (hydrationBailed = !0, console.warn('Parent: ', elm), console.warn('server innerHTML: ', i), console.warn('client innerHTML: ', elm.innerHTML)), !1;
} else {
for(var childrenMatch = !0, childNode = elm.firstChild, i$1 = 0; i$1 < children.length; i$1++){
if (!childNode || !hydrate(childNode, children[i$1], insertedVnodeQueue, inVPre)) {
childrenMatch = !1;
break;
}
childNode = childNode.nextSibling;
}
// if childNode is not null, it means the actual childNodes list is
// longer than the virtual children list.
if (!childrenMatch || childNode) return 'undefined' == typeof console || hydrationBailed || (hydrationBailed = !0, console.warn('Parent: ', elm), console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children)), !1;
}
} else createChildren(vnode, children, insertedVnodeQueue);
}
if (isDef(data)) {
var fullInvoke = !1;
for(var key in data)if (!isRenderedModule(key)) {
fullInvoke = !0, invokeCreateHooks(vnode, insertedVnodeQueue);
break;
}
!fullInvoke && data.class && // ensure collecting deps for deep class bindings for future updates
traverse(data.class);
}
} else elm.data !== vnode.text && (elm.data = vnode.text);
return !0;
}
return function(oldVnode, vnode, hydrating, removeOnly) {
if (isUndef(vnode)) {
isDef(oldVnode) && invokeDestroyHook(oldVnode);
return;
}
var isInitialPatch = !1, insertedVnodeQueue = [];
if (isUndef(oldVnode)) // empty mount (likely as component), create new root element
isInitialPatch = !0, createElm(vnode, insertedVnodeQueue);
else {
var elm, isRealElement = isDef(oldVnode.nodeType);
if (!isRealElement && sameVnode(oldVnode, vnode)) // patch existing root node
!function patchVnode(oldVnode, vnode, insertedVnodeQueue, ownerArray, index, removeOnly) {
if (oldVnode !== vnode) {
isDef(vnode.elm) && isDef(ownerArray) && // clone reused vnode
(vnode = ownerArray[index] = cloneVNode(vnode));
var i, elm = vnode.elm = oldVnode.elm;
if (isTrue(oldVnode.isAsyncPlaceholder)) {
isDef(vnode.asyncFactory.resolved) ? hydrate(oldVnode.elm, vnode, insertedVnodeQueue) : vnode.isAsyncPlaceholder = !0;
return;
}
// reuse element for static trees.
// note we only do this if the vnode is cloned -
// if the new node is not cloned it means the render functions have been
// reset by the hot-reload-api and we need to do a proper re-render.
if (isTrue(vnode.isStatic) && isTrue(oldVnode.isStatic) && vnode.key === oldVnode.key && (isTrue(vnode.isCloned) || isTrue(vnode.isOnce))) {
vnode.componentInstance = oldVnode.componentInstance;
return;
}
var data = vnode.data;
isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch) && i(oldVnode, vnode);
var oldCh = oldVnode.children, ch = vnode.children;
if (isDef(data) && isPatchable(vnode)) {
for(i = 0; i < cbs.update.length; ++i)cbs.update[i](oldVnode, vnode);
isDef(i = data.hook) && isDef(i = i.update) && i(oldVnode, vnode);
}
isUndef(vnode.text) ? isDef(oldCh) && isDef(ch) ? oldCh !== ch && function(parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) {
var oldKeyToIdx, idxInOld, vnodeToMove, oldStartIdx = 0, newStartIdx = 0, oldEndIdx = oldCh.length - 1, oldStartVnode = oldCh[0], oldEndVnode = oldCh[oldEndIdx], newEndIdx = newCh.length - 1, newStartVnode = newCh[0], newEndVnode = newCh[newEndIdx], canMove = !removeOnly;
for(checkDuplicateKeys(newCh); oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx;)isUndef(oldStartVnode) ? oldStartVnode = oldCh[++oldStartIdx] : isUndef(oldEndVnode) ? oldEndVnode = oldCh[--oldEndIdx] : sameVnode(oldStartVnode, newStartVnode) ? (patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx), oldStartVnode = oldCh[++oldStartIdx], newStartVnode = newCh[++newStartIdx]) : sameVnode(oldEndVnode, newEndVnode) ? (patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx), oldEndVnode = oldCh[--oldEndIdx], newEndVnode = newCh[--newEndIdx]) : sameVnode(oldStartVnode, newEndVnode) ? (patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue, newCh, newEndIdx), canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm)), oldStartVnode = oldCh[++oldStartIdx], newEndVnode = newCh[--newEndIdx]) : (sameVnode(oldEndVnode, newStartVnode) ? (patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue, newCh, newStartIdx), canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm), oldEndVnode = oldCh[--oldEndIdx]) : (isUndef(oldKeyToIdx) && (oldKeyToIdx = function(children, beginIdx, endIdx) {
var i, key, map = {};
for(i = beginIdx; i <= endIdx; ++i)isDef(key = children[i].key) && (map[key] = i);
return map;
}(oldCh, oldStartIdx, oldEndIdx)), isUndef(idxInOld = isDef(newStartVnode.key) ? oldKeyToIdx[newStartVnode.key] : function(node, oldCh, start, end) {
for(var i = start; i < end; i++){
var c = oldCh[i];
if (isDef(c) && sameVnode(node, c)) return i;
}
}(newStartVnode, oldCh, oldStartIdx, oldEndIdx)) ? createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, !1, newCh, newStartIdx) : sameVnode(vnodeToMove = oldCh[idxInOld], newStartVnode) ? (patchVnode(vnodeToMove, newStartVnode, insertedVnodeQueue, newCh, newStartIdx), oldCh[idxInOld] = void 0, canMove && nodeOps.insertBefore(parentElm, vnodeToMove.elm, oldStartVnode.elm)) : // same key but different element. treat as new element
createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm, !1, newCh, newStartIdx)), newStartVnode = newCh[++newStartIdx]);
oldStartIdx > oldEndIdx ? addVnodes(parentElm, isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue) : newStartIdx > newEndIdx && removeVnodes(oldCh, oldStartIdx, oldEndIdx);
}(elm, oldCh, ch, insertedVnodeQueue, removeOnly) : isDef(ch) ? (checkDuplicateKeys(ch), isDef(oldVnode.text) && nodeOps.setTextContent(elm, ''), addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue)) : isDef(oldCh) ? removeVnodes(oldCh, 0, oldCh.length - 1) : isDef(oldVnode.text) && nodeOps.setTextContent(elm, '') : oldVnode.text !== vnode.text && nodeOps.setTextContent(elm, vnode.text), isDef(data) && isDef(i = data.hook) && isDef(i = i.postpatch) && i(oldVnode, vnode);
}
}(oldVnode, vnode, insertedVnodeQueue, null, null, removeOnly);
else {
if (isRealElement) {
if (1 === oldVnode.nodeType && oldVnode.hasAttribute(SSR_ATTR) && (oldVnode.removeAttribute(SSR_ATTR), hydrating = !0), isTrue(hydrating)) {
if (hydrate(oldVnode, vnode, insertedVnodeQueue)) return invokeInsertHook(vnode, insertedVnodeQueue, !0), oldVnode;
warn("The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside <p>, or missing <tbody>. Bailing hydration and performing full client-side render.");
}
elm = oldVnode, // either not server-rendered, or hydration failed.
// create an empty node and replace it
oldVnode = new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], void 0, elm);
}
// replacing existing element
var oldElm = oldVnode.elm, parentElm = nodeOps.parentNode(oldElm);
// update parent placeholder node element, recursively
if (// create new node
createElm(vnode, insertedVnodeQueue, // extremely rare edge case: do not insert if old element is in a
// leaving transition. Only happens when combining transition +
// keep-alive + HOCs. (#4590)
oldElm._leaveCb ? null : parentElm, nodeOps.nextSibling(oldElm)), isDef(vnode.parent)) for(var ancestor = vnode.parent, patchable = isPatchable(vnode); ancestor;){
for(var i = 0; i < cbs.destroy.length; ++i)cbs.destroy[i](ancestor);
if (ancestor.elm = vnode.elm, patchable) {
for(var i$1 = 0; i$1 < cbs.create.length; ++i$1)cbs.create[i$1](emptyNode, ancestor);
// #6513
// invoke insert hooks that may have been merged by create hooks.
// e.g. for directives that uses the "inserted" hook.
var insert = ancestor.data.hook.insert;
if (insert.merged) // start at index 1 to avoid re-invoking component mounted hook
for(var i$2 = 1; i$2 < insert.fns.length; i$2++)insert.fns[i$2]();
} else registerRef(ancestor);
ancestor = ancestor.parent;
}
isDef(parentElm) ? removeVnodes([
oldVnode
], 0, 0) : isDef(oldVnode.tag) && invokeDestroyHook(oldVnode);
}
}
return invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch), vnode.elm;
};
}({
nodeOps: nodeOps,
modules: [
{
create: updateAttrs,
update: updateAttrs
},
{
create: updateClass,
update: updateClass
},
{
create: updateDOMListeners,
update: updateDOMListeners
},
{
create: updateDOMProps,
update: updateDOMProps
},
{
create: updateStyle,
update: updateStyle
},
inBrowser ? {
create: _enter,
activate: _enter,
remove: function(vnode, rm) {
/* istanbul ignore else */ !0 !== vnode.data.show ? leave(vnode, rm) : rm();
}
} : {}
].concat(baseModules)
});
isIE9 && // http://www.matts411.com/post/internet-explorer-9-oninput/
document.addEventListener('selectionchange', function() {
var el = document.activeElement;
el && el.vmodel && trigger(el, 'input');
});
var directive = {
inserted: function(el, binding, vnode, oldVnode) {
'select' === vnode.tag ? (oldVnode.elm && !oldVnode.elm._vOptions ? mergeVNodeHook(vnode, 'postpatch', function() {
directive.componentUpdated(el, binding, vnode);
}) : setSelected(el, binding, vnode.context), el._vOptions = [].map.call(el.options, getValue)) : ('textarea' === vnode.tag || isTextInputType(el.type)) && (el._vModifiers = binding.modifiers, !binding.modifiers.lazy && (el.addEventListener('compositionstart', onCompositionStart), el.addEventListener('compositionend', onCompositionEnd), // Safari < 10.2 & UIWebView doesn't fire compositionend when
// switching focus before confirming composition choice
// this also fixes the issue where some browsers e.g. iOS Chrome
// fires "change" instead of "input" on autocomplete.
el.addEventListener('change', onCompositionEnd), isIE9 && (el.vmodel = !0)));
},
componentUpdated: function(el, binding, vnode) {
if ('select' === vnode.tag) {
setSelected(el, binding, vnode.context);
// in case the options rendered by v-for have changed,
// it's possible that the value is out-of-sync with the rendered options.
// detect such cases and filter out values that no longer has a matching
// option in the DOM.
var prevOptions = el._vOptions, curOptions = el._vOptions = [].map.call(el.options, getValue);
curOptions.some(function(o, i) {
return !looseEqual(o, prevOptions[i]);
}) && (el.multiple ? binding.value.some(function(v) {
return hasNoMatchingOption(v, curOptions);
}) : binding.value !== binding.oldValue && hasNoMatchingOption(binding.value, curOptions)) && trigger(el, 'change');
}
}
};
function setSelected(el, binding, vm) {
actuallySetSelected(el, binding, vm), (isIE || isEdge) && setTimeout(function() {
actuallySetSelected(el, binding, vm);
}, 0);
}
function actuallySetSelected(el, binding, vm) {
var selected, option, value = binding.value, isMultiple = el.multiple;
if (isMultiple && !Array.isArray(value)) {
warn("<select multiple v-model=\"" + binding.expression + '"> expects an Array value for its binding, but got ' + Object.prototype.toString.call(value).slice(8, -1), vm);
return;
}
for(var i = 0, l = el.options.length; i < l; i++)if (option = el.options[i], isMultiple) selected = looseIndexOf(value, getValue(option)) > -1, option.selected !== selected && (option.selected = selected);
else if (looseEqual(getValue(option), value)) {
el.selectedIndex !== i && (el.selectedIndex = i);
return;
}
isMultiple || (el.selectedIndex = -1);
}
function hasNoMatchingOption(value, options) {
return options.every(function(o) {
return !looseEqual(o, value);
});
}
function getValue(option) {
return '_value' in option ? option._value : option.value;
}
function onCompositionStart(e) {
e.target.composing = !0;
}
function onCompositionEnd(e) {
// prevent triggering an input event for no reason
e.target.composing && (e.target.composing = !1, trigger(e.target, 'input'));
}
function trigger(el, type) {
var e = document.createEvent('HTMLEvents');
e.initEvent(type, !0, !0), el.dispatchEvent(e);
}
/* */ // recursively search for possible transition defined inside the component root
function locateNode(vnode) {
return !vnode.componentInstance || vnode.data && vnode.data.transition ? vnode : locateNode(vnode.componentInstance._vnode);
}
/* */ var transitionProps = {
name: String,
appear: Boolean,
css: Boolean,
mode: String,
type: String,
enterClass: String,
leaveClass: String,
enterToClass: String,
leaveToClass: String,
enterActiveClass: String,
leaveActiveClass: String,
appearClass: String,
appearActiveClass: String,
appearToClass: String,
duration: [
Number,
String,
Object
]
};
// in case the child is also an abstract component, e.g. <keep-alive>
// we want to recursively retrieve the real component to be rendered
function getRealChild(vnode) {
var compOptions = vnode && vnode.componentOptions;
return compOptions && compOptions.Ctor.options.abstract ? getRealChild(getFirstComponentChild(compOptions.children)) : vnode;
}
function extractTransitionData(comp) {
var data = {}, options = comp.$options;
// props
for(var key in options.propsData)data[key] = comp[key];
// events.
// extract listeners and pass them directly to the transition methods
var listeners = options._parentListeners;
for(var key$1 in listeners)data[camelize(key$1)] = listeners[key$1];
return data;
}
function placeholder(h, rawChild) {
if (/\d-keep-alive$/.test(rawChild.tag)) return h('keep-alive', {
props: rawChild.componentOptions.propsData
});
}
var isNotTextNode = function(c) {
return c.tag || isAsyncPlaceholder(c);
}, isVShowDirective = function(d) {
return 'show' === d.name;
}, props = extend({
tag: String,
moveClass: String
}, transitionProps);
function callPendingCbs(c) {
c.elm._moveCb && c.elm._moveCb(), c.elm._enterCb && c.elm._enterCb();
}
function recordPosition(c) {
c.data.newPos = c.elm.getBoundingClientRect();
}
function applyTranslation(c) {
var oldPos = c.data.pos, newPos = c.data.newPos, dx = oldPos.left - newPos.left, dy = oldPos.top - newPos.top;
if (dx || dy) {
c.data.moved = !0;
var s = c.elm.style;
s.transform = s.WebkitTransform = "translate(" + dx + "px," + dy + "px)", s.transitionDuration = '0s';
}
}
delete props.mode, /* */ // install platform specific utils
Vue1.config.mustUseProp = mustUseProp, Vue1.config.isReservedTag = isReservedTag, Vue1.config.isReservedAttr = isReservedAttr, Vue1.config.getTagNamespace = getTagNamespace, Vue1.config.isUnknownElement = function(tag) {
/* istanbul ignore if */ if (!inBrowser) return !0;
if (isReservedTag(tag)) return !1;
/* istanbul ignore if */ if (null != unknownElementCache[tag = tag.toLowerCase()]) return unknownElementCache[tag];
var el = document.createElement(tag);
return tag.indexOf('-') > -1 ? unknownElementCache[tag] = el.constructor === window.HTMLUnknownElement || el.constructor === window.HTMLElement : unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString());
}, // install platform runtime directives & components
extend(Vue1.options.directives, {
model: directive,
show: {
bind: function(el, ref, vnode) {
var value = ref.value, transition$$1 = (vnode = locateNode(vnode)).data && vnode.data.transition, originalDisplay = el.__vOriginalDisplay = 'none' === el.style.display ? '' : el.style.display;
value && transition$$1 ? (vnode.data.show = !0, enter(vnode, function() {
el.style.display = originalDisplay;
})) : el.style.display = value ? originalDisplay : 'none';
},
update: function(el, ref, vnode) {
var value = ref.value;
/* istanbul ignore if */ !value != !ref.oldValue && ((vnode = locateNode(vnode)).data && vnode.data.transition ? (vnode.data.show = !0, value ? enter(vnode, function() {
el.style.display = el.__vOriginalDisplay;
}) : leave(vnode, function() {
el.style.display = 'none';
})) : el.style.display = value ? el.__vOriginalDisplay : 'none');
},
unbind: function(el, binding, vnode, oldVnode, isDestroy) {
isDestroy || (el.style.display = el.__vOriginalDisplay);
}
}
}), extend(Vue1.options.components, {
Transition: {
name: 'transition',
props: transitionProps,
abstract: !0,
render: function(h) {
var this$1 = this, children = this.$slots.default;
if (children && // filter out text nodes (possible whitespaces)
(children = children.filter(isNotTextNode)).length) {
children.length > 1 && warn("<transition> can only be used on a single element. Use <transition-group> for lists.", this.$parent);
var mode = this.mode;
mode && 'in-out' !== mode && 'out-in' !== mode && warn('invalid <transition> mode: ' + mode, this.$parent);
var rawChild = children[0];
// if this is a component root node and the component's
// parent container node also has transition, skip.
if (function(vnode) {
for(; vnode = vnode.parent;)if (vnode.data.transition) return !0;
}(this.$vnode)) return rawChild;
// apply transition data to child
// use getRealChild() to ignore abstract components e.g. keep-alive
var child = getRealChild(rawChild);
/* istanbul ignore if */ if (!child) return rawChild;
if (this._leaving) return placeholder(h, rawChild);
// ensure a key that is unique to the vnode type and to this transition
// component instance. This key will be used to remove pending leaving nodes
// during entering.
var id = "__transition-" + this._uid + "-";
child.key = null == child.key ? child.isComment ? id + 'comment' : id + child.tag : isPrimitive(child.key) ? 0 === String(child.key).indexOf(id) ? child.key : id + child.key : child.key;
var data = (child.data || (child.data = {})).transition = extractTransitionData(this), oldRawChild = this._vnode, oldChild = getRealChild(oldRawChild);
if (child.data.directives && child.data.directives.some(isVShowDirective) && (child.data.show = !0), oldChild && oldChild.data && (oldChild.key !== child.key || oldChild.tag !== child.tag) && !isAsyncPlaceholder(oldChild) && // #6687 component root is a comment node
!(oldChild.componentInstance && oldChild.componentInstance._vnode.isComment)) {
// replace old child transition data with fresh one
// important for dynamic transitions!
var oldData = oldChild.data.transition = extend({}, data);
// handle transition mode
if ('out-in' === mode) return(// return placeholder node and queue update when leave finishes
this._leaving = !0, mergeVNodeHook(oldData, 'afterLeave', function() {
this$1._leaving = !1, this$1.$forceUpdate();
}), placeholder(h, rawChild));
if ('in-out' === mode) {
if (isAsyncPlaceholder(child)) return oldRawChild;
var delayedLeave, performLeave = function() {
delayedLeave();
};
mergeVNodeHook(data, 'afterEnter', performLeave), mergeVNodeHook(data, 'enterCancelled', performLeave), mergeVNodeHook(oldData, 'delayLeave', function(leave) {
delayedLeave = leave;
});
}
}
return rawChild;
}
}
},
TransitionGroup: {
props: props,
beforeMount: function() {
var this$1 = this, update = this._update;
this._update = function(vnode, hydrating) {
var restoreActiveInstance = setActiveInstance(this$1);
// force removing pass
this$1.__patch__(this$1._vnode, this$1.kept, !1, !0 // removeOnly (!important, avoids unnecessary moves)
), this$1._vnode = this$1.kept, restoreActiveInstance(), update.call(this$1, vnode, hydrating);
};
},
render: function(h) {
for(var tag = this.tag || this.$vnode.data.tag || 'span', map = Object.create(null), prevChildren = this.prevChildren = this.children, rawChildren = this.$slots.default || [], children = this.children = [], transitionData = extractTransitionData(this), i = 0; i < rawChildren.length; i++){
var c = rawChildren[i];
if (c.tag) {
if (null != c.key && 0 !== String(c.key).indexOf('__vlist')) children.push(c), map[c.key] = c, (c.data || (c.data = {})).transition = transitionData;
else {
var opts = c.componentOptions, name = opts ? opts.Ctor.options.name || opts.tag || '' : c.tag;
warn("<transition-group> children must be keyed: <" + name + ">");
}
}
}
if (prevChildren) {
for(var kept = [], removed = [], i$1 = 0; i$1 < prevChildren.length; i$1++){
var c$1 = prevChildren[i$1];
c$1.data.transition = transitionData, c$1.data.pos = c$1.elm.getBoundingClientRect(), map[c$1.key] ? kept.push(c$1) : removed.push(c$1);
}
this.kept = h(tag, null, kept), this.removed = removed;
}
return h(tag, null, children);
},
updated: function() {
var children = this.prevChildren, moveClass = this.moveClass || (this.name || 'v') + '-move';
children.length && this.hasMove(children[0].elm, moveClass) && (// we divide the work into three loops to avoid mixing DOM reads and writes
// in each iteration - which helps prevent layout thrashing.
children.forEach(callPendingCbs), children.forEach(recordPosition), children.forEach(applyTranslation), // force reflow to put everything in position
// assign to this to avoid being removed in tree-shaking
// $flow-disable-line
this._reflow = document.body.offsetHeight, children.forEach(function(c) {
if (c.data.moved) {
var el = c.elm, s = el.style;
addTransitionClass(el, moveClass), s.transform = s.WebkitTransform = s.transitionDuration = '', el.addEventListener(transitionEndEvent, el._moveCb = function cb(e) {
(!e || e.target === el) && (!e || /transform$/.test(e.propertyName)) && (el.removeEventListener(transitionEndEvent, cb), el._moveCb = null, removeTransitionClass(el, moveClass));
});
}
}));
},
methods: {
hasMove: function(el, moveClass) {
/* istanbul ignore if */ if (!hasTransition) return !1;
/* istanbul ignore if */ if (this._hasMove) return this._hasMove;
// Detect whether an element with the move class applied has
// CSS transitions. Since the element may be inside an entering
// transition at this very moment, we make a clone of it and remove
// all other transition classes applied to ensure only the move class
// is applied.
var clone = el.cloneNode();
el._transitionClasses && el._transitionClasses.forEach(function(cls) {
removeClass(clone, cls);
}), addClass(clone, moveClass), clone.style.display = 'none', this.$el.appendChild(clone);
var info = getTransitionInfo(clone);
return this.$el.removeChild(clone), this._hasMove = info.hasTransform;
}
}
}
}), // install platform patch function
Vue1.prototype.__patch__ = inBrowser ? patch : noop, // public mount method
Vue1.prototype.$mount = function(el, hydrating) {
var vm, el1, hydrating1, updateComponent;
return el = el && inBrowser ? query(el) : void 0, vm = this, el1 = el, hydrating1 = hydrating, vm.$el = el1, vm.$options.render || (vm.$options.render = createEmptyVNode, vm.$options.template && '#' !== vm.$options.template.charAt(0) || vm.$options.el || el1 ? warn("You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.", vm) : warn('Failed to mount component: template or render function not defined.', vm)), callHook(vm, 'beforeMount'), updateComponent = config.performance && mark ? function() {
var name = vm._name, id = vm._uid, startTag = "vue-perf-start:" + id, endTag = "vue-perf-end:" + id;
mark(startTag);
var vnode = vm._render();
mark(endTag), measure("vue " + name + " render", startTag, endTag), mark(startTag), vm._update(vnode, hydrating1), mark(endTag), measure("vue " + name + " patch", startTag, endTag);
} : function() {
vm._update(vm._render(), hydrating1);
}, // we set this to vm._watcher inside the watcher's constructor
// since the watcher's initial patch may call $forceUpdate (e.g. inside child
// component's mounted hook), which relies on vm._watcher being already defined
new Watcher(vm, updateComponent, noop, {
before: function() {
vm._isMounted && !vm._isDestroyed && callHook(vm, 'beforeUpdate');
}
}, !0), hydrating1 = !1, null == vm.$vnode && (vm._isMounted = !0, callHook(vm, 'mounted')), vm;
}, inBrowser && setTimeout(function() {
config.devtools && (devtools ? devtools.emit('init', Vue1) : console[console.info ? 'info' : 'log']("Download the Vue Devtools extension for a better development experience:\nhttps://github.com/vuejs/vue-devtools")), !1 !== config.productionTip && 'undefined' != typeof console && console[console.info ? 'info' : 'log']("You are running Vue in development mode.\nMake sure to turn on production mode when deploying for production.\nSee more tips at https://vuejs.org/guide/deployment.html");
}, 0);
/* */ var defaultTagRE = /\{\{((?:.|\r?\n)+?)\}\}/g, regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g, buildRegex = cached(function(delimiters) {
return RegExp(delimiters[0].replace(regexEscapeRE, '\\$&') + '((?:.|\\n)+?)' + delimiters[1].replace(regexEscapeRE, '\\$&'), 'g');
});
function parseText(text, delimiters) {
var match, index, tokenValue, tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE;
if (tagRE.test(text)) {
for(var tokens = [], rawTokens = [], lastIndex = tagRE.lastIndex = 0; match = tagRE.exec(text);){
(index = match.index) > lastIndex && (rawTokens.push(tokenValue = text.slice(lastIndex, index)), tokens.push(JSON.stringify(tokenValue)));
// tag token
var exp = parseFilters(match[1].trim());
tokens.push("_s(" + exp + ")"), rawTokens.push({
'@binding': exp
}), lastIndex = index + match[0].length;
}
return lastIndex < text.length && (rawTokens.push(tokenValue = text.slice(lastIndex)), tokens.push(JSON.stringify(tokenValue))), {
expression: tokens.join('+'),
tokens: rawTokens
};
}
}
/* */ var isUnaryTag = makeMap("area,base,br,col,embed,frame,hr,img,input,isindex,keygen,link,meta,param,source,track,wbr"), canBeLeftOpenTag = makeMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source'), isNonPhrasingTag = makeMap("address,article,aside,base,blockquote,body,caption,col,colgroup,dd,details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,title,tr,track"), attribute = /^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/, dynamicArgAttribute = /^\s*((?:v-[\w-]+:|@|:|#)\[[^=]+\][^\s"'<>\/=]*)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/, ncname = "[a-zA-Z_][\\-\\.0-9_a-zA-Z" + unicodeRegExp.source + "]*", qnameCapture = "((?:" + ncname + "\\:)?" + ncname + ")", startTagOpen = RegExp("^<" + qnameCapture), startTagClose = /^\s*(\/?)>/, endTag = RegExp("^<\\/" + qnameCapture + "[^>]*>"), doctype = /^<!DOCTYPE [^>]+>/i, comment = /^<!\--/, conditionalComment = /^<!\[/, isPlainTextElement = makeMap('script,style,textarea', !0), reCache = {}, decodingMap = {
'<': '<',
'>': '>',
'"': '"',
'&': '&',
' ': '\n',
'	': '\t',
''': "'"
}, encodedAttr = /&(?:lt|gt|quot|amp|#39);/g, encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#39|#10|#9);/g, isIgnoreNewlineTag = makeMap('pre,textarea', !0), shouldIgnoreFirstNewline = function(tag, html) {
return tag && isIgnoreNewlineTag(tag) && '\n' === html[0];
}, onRE = /^@|^v-on:/, dirRE = /^v-|^@|^:|^#/, forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/, forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/, stripParensRE = /^\(|\)$/g, dynamicArgRE = /^\[.*\]$/, argRE = /:(.*)$/, bindRE = /^:|^\.|^v-bind:/, modifierRE = /\.[^.\]]+(?=[^\]]*$)/g, slotRE = /^v-slot(:|$)|^#/, lineBreakRE = /[\r\n]/, whitespaceRE$1 = /\s+/g, invalidAttributeRE = /[\s"'<>\/=]/, decodeHTMLCached = cached(function(html) {
return (decoder = decoder || document.createElement('div')).innerHTML = html, decoder.textContent;
}), emptySlotScopeToken = "_empty_";
function createASTElement(tag, attrs, parent) {
return {
type: 1,
tag: tag,
attrsList: attrs,
attrsMap: function(attrs) {
for(var map = {}, i = 0, l = attrs.length; i < l; i++)!map[attrs[i].name] || isIE || isEdge || warn$2('duplicate attribute: ' + attrs[i].name, attrs[i]), map[attrs[i].name] = attrs[i].value;
return map;
}(attrs),
rawAttrsMap: {},
parent: parent,
children: []
};
}
function processElement(element, options) {
(function(el) {
var exp = getBindingAttr(el, 'key');
if (exp) {
if ('template' === el.tag && warn$2("<template> cannot be keyed. Place the key on real elements instead.", getRawBindingAttr(el, 'key')), el.for) {
var iterator = el.iterator2 || el.iterator1, parent = el.parent;
iterator && iterator === exp && parent && 'transition-group' === parent.tag && warn$2("Do not use v-for index as key on <transition-group> children, this is the same as not using keys.", getRawBindingAttr(el, 'key'), !0);
}
el.key = exp;
}
})(element), // determine whether this is a plain element after
// removing structural attributes
element.plain = !element.key && !element.scopedSlots && !element.attrsList.length, (ref = getBindingAttr(el = element, 'ref')) && (el.ref = ref, el.refInFor = function(el) {
for(var parent = el; parent;){
if (void 0 !== parent.for) return !0;
parent = parent.parent;
}
return !1;
}(el)), // handle content being passed to a component as slot,
// e.g. <template slot="xxx">, <div slot-scope="xxx">
function(el) {
'template' === el.tag ? ((slotScope = getAndRemoveAttr(el, 'scope')) && warn$2('the "scope" attribute for scoped slots have been deprecated and replaced by "slot-scope" since 2.5. The new "slot-scope" attribute can also be used on plain elements in addition to <template> to denote scoped slots.', el.rawAttrsMap.scope, !0), el.slotScope = slotScope || getAndRemoveAttr(el, 'slot-scope')) : (slotScope = getAndRemoveAttr(el, 'slot-scope')) && (el.attrsMap['v-for'] && warn$2("Ambiguous combined usage of slot-scope and v-for on <" + el.tag + "> (v-for takes higher priority). Use a wrapper <template> for the scoped slot to make it clearer.", el.rawAttrsMap['slot-scope'], !0), el.slotScope = slotScope);
// slot="xxx"
var slotScope, slotTarget = getBindingAttr(el, 'slot');
if (slotTarget && (el.slotTarget = '""' === slotTarget ? '"default"' : slotTarget, el.slotTargetDynamic = !!(el.attrsMap[':slot'] || el.attrsMap['v-bind:slot']), 'template' === el.tag || el.slotScope || addAttr(el, 'slot', slotTarget, getRawBindingAttr(el, 'slot'))), 'template' === el.tag) {
// v-slot on <template>
var slotBinding = getAndRemoveAttrByRegex(el, slotRE);
if (slotBinding) {
(el.slotTarget || el.slotScope) && warn$2("Unexpected mixed usage of different slot syntaxes.", el), el.parent && !maybeComponent(el.parent) && warn$2("<template v-slot> can only appear at the root level inside the receiving component", el);
var ref = getSlotName(slotBinding), name = ref.name, dynamic = ref.dynamic;
el.slotTarget = name, el.slotTargetDynamic = dynamic, el.slotScope = slotBinding.value || emptySlotScopeToken;
}
} else {
// v-slot on component, denotes default slot
var slotBinding$1 = getAndRemoveAttrByRegex(el, slotRE);
if (slotBinding$1) {
maybeComponent(el) || warn$2("v-slot can only be used on components or <template>.", slotBinding$1), (el.slotScope || el.slotTarget) && warn$2("Unexpected mixed usage of different slot syntaxes.", el), el.scopedSlots && warn$2("To avoid scope ambiguity, the default slot should also use <template> syntax when there are other named slots.", slotBinding$1);
// add the component's children to its default slot
var slots = el.scopedSlots || (el.scopedSlots = {}), ref$1 = getSlotName(slotBinding$1), name$1 = ref$1.name, dynamic$1 = ref$1.dynamic, slotContainer = slots[name$1] = createASTElement('template', [], el);
slotContainer.slotTarget = name$1, slotContainer.slotTargetDynamic = dynamic$1, slotContainer.children = el.children.filter(function(c) {
if (!c.slotScope) return c.parent = slotContainer, !0;
}), slotContainer.slotScope = slotBinding$1.value || emptySlotScopeToken, // remove children as they are returned from scopedSlots now
el.children = [], // mark el non-plain so data gets generated
el.plain = !1;
}
}
}(element), 'slot' === (el1 = element).tag && (el1.slotName = getBindingAttr(el1, 'name'), el1.key && warn$2("`key` does not work on <slot> because slots are abstract outlets and can possibly expand into multiple elements. Use the key on a wrapping element instead.", getRawBindingAttr(el1, 'key'))), (binding = getBindingAttr(el2 = element, 'is')) && (el2.component = binding), null != getAndRemoveAttr(el2, 'inline-template') && (el2.inlineTemplate = !0);
for(var el, ref, el1, el2, binding, i = 0; i < transforms.length; i++)element = transforms[i](element, options) || element;
return function(el) {
var i, l, name, rawName, value, modifiers, syncGen, isDynamic, list = el.attrsList;
for(i = 0, l = list.length; i < l; i++)if (name = rawName = list[i].name, value = list[i].value, dirRE.test(name)) {
if (// mark element as dynamic
el.hasBindings = !0, // modifiers
(modifiers = function(name) {
var match = name.match(modifierRE);
if (match) {
var ret = {};
return match.forEach(function(m) {
ret[m.slice(1)] = !0;
}), ret;
}
}(name.replace(dirRE, ''))) && (name = name.replace(modifierRE, '')), bindRE.test(name)) name = name.replace(bindRE, ''), value = parseFilters(value), (isDynamic = dynamicArgRE.test(name)) && (name = name.slice(1, -1)), 0 === value.trim().length && warn$2("The value for a v-bind expression cannot be empty. Found in \"v-bind:" + name + "\""), modifiers && (modifiers.prop && !isDynamic && 'innerHtml' === (name = camelize(name)) && (name = 'innerHTML'), modifiers.camel && !isDynamic && (name = camelize(name)), modifiers.sync && (syncGen = genAssignmentCode(value, "$event"), isDynamic ? // handler w/ dynamic event name
addHandler(el, "\"update:\"+(" + name + ")", syncGen, null, !1, warn$2, list[i], !0 // dynamic
) : (addHandler(el, "update:" + camelize(name), syncGen, null, !1, warn$2, list[i]), hyphenate(name) !== camelize(name) && addHandler(el, "update:" + hyphenate(name), syncGen, null, !1, warn$2, list[i])))), modifiers && modifiers.prop || !el.component && platformMustUseProp(el.tag, el.attrsMap.type, name) ? addProp(el, name, value, list[i], isDynamic) : addAttr(el, name, value, list[i], isDynamic);
else if (onRE.test(name)) name = name.replace(onRE, ''), (isDynamic = dynamicArgRE.test(name)) && (name = name.slice(1, -1)), addHandler(el, name, value, modifiers, !1, warn$2, list[i], isDynamic);
else {
// parse arg
var name1, value1, arg, isDynamicArg, range, argMatch = (name = name.replace(dirRE, '')).match(argRE), arg1 = argMatch && argMatch[1];
isDynamic = !1, arg1 && (name = name.slice(0, -(arg1.length + 1)), dynamicArgRE.test(arg1) && (arg1 = arg1.slice(1, -1), isDynamic = !0)), name1 = name, value1 = value, arg = arg1, isDynamicArg = isDynamic, range = list[i], (el.directives || (el.directives = [])).push(rangeSetItem({
name: name1,
rawName: rawName,
value: value1,
arg: arg,
isDynamicArg: isDynamicArg,
modifiers: modifiers
}, range)), el.plain = !1, 'model' === name && function(el, value) {
for(var _el = el; _el;)_el.for && _el.alias === value && warn$2("<" + el.tag + " v-model=\"" + value + '">: You are binding v-model directly to a v-for iteration alias. This will not be able to modify the v-for source array because writing to the alias is like modifying a function local variable. Consider using an array of objects and use v-model on an object property instead.', el.rawAttrsMap['v-model']), _el = _el.parent;
}(el, value);
}
} else parseText(value, delimiters) && warn$2(name + "=\"" + value + '": Interpolation inside attributes has been removed. Use v-bind or the colon shorthand instead. For example, instead of <div id="{{ val }}">, use <div :id="val">.', list[i]), addAttr(el, name, JSON.stringify(value), list[i]), !el.component && 'muted' === name && platformMustUseProp(el.tag, el.attrsMap.type, name) && addProp(el, name, 'true', list[i]);
}(element), element;
}
function processFor(el) {
var exp;
if (exp = getAndRemoveAttr(el, 'v-for')) {
var res = function(exp) {
var inMatch = exp.match(forAliasRE);
if (inMatch) {
var res = {};
res.for = inMatch[2].trim();
var alias = inMatch[1].trim().replace(stripParensRE, ''), iteratorMatch = alias.match(forIteratorRE);
return iteratorMatch ? (res.alias = alias.replace(forIteratorRE, '').trim(), res.iterator1 = iteratorMatch[1].trim(), iteratorMatch[2] && (res.iterator2 = iteratorMatch[2].trim())) : res.alias = alias, res;
}
}(exp);
res ? extend(el, res) : warn$2("Invalid v-for expression: " + exp, el.rawAttrsMap['v-for']);
}
}
function addIfCondition(el, condition) {
el.ifConditions || (el.ifConditions = []), el.ifConditions.push(condition);
}
function getSlotName(binding) {
var name = binding.name.replace(slotRE, '');
return name || ('#' !== binding.name[0] ? name = 'default' : warn$2("v-slot shorthand syntax requires a slot name.", binding)), dynamicArgRE.test(name) ? {
name: name.slice(1, -1),
dynamic: !0
} : {
name: "\"" + name + "\"",
dynamic: !1
};
}
var ieNSBug = /^xmlns:NS\d+/, ieNSPrefix = /^NS\d+:/;
function cloneASTElement(el) {
return createASTElement(el.tag, el.attrsList.slice(), el.parent);
}
var modules$1 = [
{
staticKeys: [
'staticClass'
],
transformNode: /* */ function(el, options) {
var warn = options.warn || baseWarn, staticClass = getAndRemoveAttr(el, 'class');
staticClass && parseText(staticClass, options.delimiters) && warn("class=\"" + staticClass + '": Interpolation inside attributes has been removed. Use v-bind or the colon shorthand instead. For example, instead of <div class="{{ val }}">, use <div :class="val">.', el.rawAttrsMap.class), staticClass && (el.staticClass = JSON.stringify(staticClass));
var classBinding = getBindingAttr(el, 'class', !1);
classBinding && (el.classBinding = classBinding);
},
genData: function(el) {
var data = '';
return el.staticClass && (data += "staticClass:" + el.staticClass + ","), el.classBinding && (data += "class:" + el.classBinding + ","), data;
}
},
{
staticKeys: [
'staticStyle'
],
transformNode: /* */ function(el, options) {
var warn = options.warn || baseWarn, staticStyle = getAndRemoveAttr(el, 'style');
staticStyle && (parseText(staticStyle, options.delimiters) && warn("style=\"" + staticStyle + '": Interpolation inside attributes has been removed. Use v-bind or the colon shorthand instead. For example, instead of <div style="{{ val }}">, use <div :style="val">.', el.rawAttrsMap.style), el.staticStyle = JSON.stringify(parseStyleText(staticStyle)));
var styleBinding = getBindingAttr(el, 'style', !1);
styleBinding && (el.styleBinding = styleBinding);
},
genData: function(el) {
var data = '';
return el.staticStyle && (data += "staticStyle:" + el.staticStyle + ","), el.styleBinding && (data += "style:(" + el.styleBinding + "),"), data;
}
},
{
preTransformNode: /* */ function(el, options) {
if ('input' === el.tag) {
var typeBinding, map = el.attrsMap;
if (map['v-model'] && ((map[':type'] || map['v-bind:type']) && (typeBinding = getBindingAttr(el, 'type')), map.type || typeBinding || !map['v-bind'] || (typeBinding = "(" + map['v-bind'] + ").type"), typeBinding)) {
var ifCondition = getAndRemoveAttr(el, 'v-if', !0), ifConditionExtra = ifCondition ? "&&(" + ifCondition + ")" : "", hasElse = null != getAndRemoveAttr(el, 'v-else', !0), elseIfCondition = getAndRemoveAttr(el, 'v-else-if', !0), branch0 = cloneASTElement(el);
// process for on the main node
processFor(branch0), addRawAttr(branch0, 'type', 'checkbox'), processElement(branch0, options), branch0.processed = !0, branch0.if = "(" + typeBinding + ")==='checkbox'" + ifConditionExtra, addIfCondition(branch0, {
exp: branch0.if,
block: branch0
});
// 2. add radio else-if condition
var branch1 = cloneASTElement(el);
getAndRemoveAttr(branch1, 'v-for', !0), addRawAttr(branch1, 'type', 'radio'), processElement(branch1, options), addIfCondition(branch0, {
exp: "(" + typeBinding + ")==='radio'" + ifConditionExtra,
block: branch1
});
// 3. other
var branch2 = cloneASTElement(el);
return getAndRemoveAttr(branch2, 'v-for', !0), addRawAttr(branch2, ':type', typeBinding), processElement(branch2, options), addIfCondition(branch0, {
exp: ifCondition,
block: branch2
}), hasElse ? branch0.else = !0 : elseIfCondition && (branch0.elseif = elseIfCondition), branch0;
}
}
}
}
], baseOptions = {
expectHTML: !0,
modules: modules$1,
directives: {
model: function(el, dir, _warn) {
warn$1 = _warn;
var code, number, valueBinding, trueValueBinding, falseValueBinding, number1, valueBinding1, value = dir.value, modifiers = dir.modifiers, tag = el.tag, type = el.attrsMap.type;
if ('input' === tag && 'file' === type && warn$1("<" + el.tag + " v-model=\"" + value + '" type="file">:\nFile inputs are read only. Use a v-on:change listener instead.', el.rawAttrsMap['v-model']), el.component) // component v-model doesn't need extra runtime
return genComponentModel(el, value, modifiers), !1;
if ('select' === tag) addHandler(el, 'change', 'var $$selectedVal = Array.prototype.filter.call($event.target.options,function(o){return o.selected}).map(function(o){var val = "_value" in o ? o._value : o.value;return ' + (modifiers && modifiers.number ? '_n(val)' : 'val') + "}); " + genAssignmentCode(value, '$event.target.multiple ? $$selectedVal : $$selectedVal[0]'), null, !0);
else if ('input' === tag && 'checkbox' === type) number = modifiers && modifiers.number, valueBinding = getBindingAttr(el, 'value') || 'null', trueValueBinding = getBindingAttr(el, 'true-value') || 'true', falseValueBinding = getBindingAttr(el, 'false-value') || 'false', addProp(el, 'checked', "Array.isArray(" + value + ")?_i(" + value + "," + valueBinding + ")>-1" + ('true' === trueValueBinding ? ":(" + value + ")" : ":_q(" + value + "," + trueValueBinding + ")")), addHandler(el, 'change', "var $$a=" + value + ",$$el=$event.target,$$c=$$el.checked?(" + trueValueBinding + "):(" + falseValueBinding + ");if(Array.isArray($$a)){var $$v=" + (number ? '_n(' + valueBinding + ')' : valueBinding) + ",$$i=_i($$a,$$v);if($$el.checked){$$i<0&&(" + genAssignmentCode(value, '$$a.concat([$$v])') + ")}else{$$i>-1&&(" + genAssignmentCode(value, '$$a.slice(0,$$i).concat($$a.slice($$i+1))') + ")}}else{" + genAssignmentCode(value, '$$c') + "}", null, !0);
else if ('input' === tag && 'radio' === type) number1 = modifiers && modifiers.number, valueBinding1 = getBindingAttr(el, 'value') || 'null', addProp(el, 'checked', "_q(" + value + "," + (valueBinding1 = number1 ? "_n(" + valueBinding1 + ")" : valueBinding1) + ")"), addHandler(el, 'change', genAssignmentCode(value, valueBinding1), null, !0);
else if ('input' === tag || 'textarea' === tag) !function(el, value, modifiers) {
var type = el.attrsMap.type, value$1 = el.attrsMap['v-bind:value'] || el.attrsMap[':value'], typeBinding = el.attrsMap['v-bind:type'] || el.attrsMap[':type'];
if (value$1 && !typeBinding) {
var binding = el.attrsMap['v-bind:value'] ? 'v-bind:value' : ':value';
warn$1(binding + "=\"" + value$1 + '" conflicts with v-model on the same element because the latter already expands to a value binding internally', el.rawAttrsMap[binding]);
}
var ref = modifiers || {}, lazy = ref.lazy, number = ref.number, trim = ref.trim, valueExpression = '$event.target.value';
trim && (valueExpression = "$event.target.value.trim()"), number && (valueExpression = "_n(" + valueExpression + ")");
var code = genAssignmentCode(value, valueExpression);
lazy || 'range' === type || (code = "if($event.target.composing)return;" + code), addProp(el, 'value', "(" + value + ")"), addHandler(el, lazy ? 'change' : 'range' === type ? '__r' : 'input', code, null, !0), (trim || number) && addHandler(el, 'blur', '$forceUpdate()');
}(el, value, modifiers);
else {
if (!config.isReservedTag(tag)) // component v-model doesn't need extra runtime
return genComponentModel(el, value, modifiers), !1;
warn$1("<" + el.tag + " v-model=\"" + value + "\">: v-model is not supported on this element type. If you are working with contenteditable, it's recommended to wrap a library dedicated for that purpose inside a custom component.", el.rawAttrsMap['v-model']);
}
// ensure runtime directive metadata
return !0;
},
text: /* */ function(el, dir) {
dir.value && addProp(el, 'textContent', "_s(" + dir.value + ")", dir);
},
html: /* */ function(el, dir) {
dir.value && addProp(el, 'innerHTML', "_s(" + dir.value + ")", dir);
}
},
isPreTag: function(tag) {
return 'pre' === tag;
},
isUnaryTag: isUnaryTag,
mustUseProp: mustUseProp,
canBeLeftOpenTag: canBeLeftOpenTag,
isReservedTag: isReservedTag,
getTagNamespace: getTagNamespace,
staticKeys: modules$1.reduce(function(keys, m) {
return keys.concat(m.staticKeys || []);
}, []).join(',')
}, genStaticKeysCached = cached(function(keys) {
return makeMap('type,tag,attrsList,attrsMap,plain,parent,children,attrs,start,end,rawAttrsMap' + (keys ? ',' + keys : ''));
}), fnExpRE = /^([\w$_]+|\([^)]*?\))\s*=>|^function(?:\s+[\w$]+)?\s*\(/, fnInvokeRE = /\([^)]*?\);*$/, simplePathRE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['[^']*?']|\["[^"]*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*$/, keyCodes = {
esc: 27,
tab: 9,
enter: 13,
space: 32,
up: 38,
left: 37,
right: 39,
down: 40,
delete: [
8,
46
]
}, keyNames = {
// #7880: IE11 and Edge use `Esc` for Escape key name.
esc: [
'Esc',
'Escape'
],
tab: 'Tab',
enter: 'Enter',
// #9112: IE11 uses `Spacebar` for Space key name.
space: [
' ',
'Spacebar'
],
// #7806: IE11 uses key names without `Arrow` prefix for arrow keys.
up: [
'Up',
'ArrowUp'
],
left: [
'Left',
'ArrowLeft'
],
right: [
'Right',
'ArrowRight'
],
down: [
'Down',
'ArrowDown'
],
// #9112: IE11 uses `Del` for Delete key name.
delete: [
'Backspace',
'Delete',
'Del'
]
}, genGuard = function(condition) {
return "if(" + condition + ")return null;";
}, modifierCode = {
stop: '$event.stopPropagation();',
prevent: '$event.preventDefault();',
self: genGuard("$event.target !== $event.currentTarget"),
ctrl: genGuard("!$event.ctrlKey"),
shift: genGuard("!$event.shiftKey"),
alt: genGuard("!$event.altKey"),
meta: genGuard("!$event.metaKey"),
left: genGuard("'button' in $event && $event.button !== 0"),
middle: genGuard("'button' in $event && $event.button !== 1"),
right: genGuard("'button' in $event && $event.button !== 2")
};
function genHandlers(events, isNative) {
var prefix = isNative ? 'nativeOn:' : 'on:', staticHandlers = "", dynamicHandlers = "";
for(var name in events){
var handlerCode = function genHandler(handler) {
if (!handler) return 'function(){}';
if (Array.isArray(handler)) return "[" + handler.map(function(handler) {
return genHandler(handler);
}).join(',') + "]";
var isMethodPath = simplePathRE.test(handler.value), isFunctionExpression = fnExpRE.test(handler.value), isFunctionInvocation = simplePathRE.test(handler.value.replace(fnInvokeRE, ''));
if (handler.modifiers) {
var code = '', genModifierCode = '', keys = [];
for(var key in handler.modifiers)if (modifierCode[key]) genModifierCode += modifierCode[key], keyCodes[key] && keys.push(key);
else if ('exact' === key) {
var modifiers = handler.modifiers;
genModifierCode += genGuard([
'ctrl',
'shift',
'alt',
'meta'
].filter(function(keyModifier) {
return !modifiers[keyModifier];
}).map(function(keyModifier) {
return "$event." + keyModifier + "Key";
}).join('||'));
} else keys.push(key);
return keys.length && (code += // make sure the key filters only apply to KeyboardEvents
// #9441: can't use 'keyCode' in $event because Chrome autofill fires fake
// key events that do not have keyCode property...
"if(!$event.type.indexOf('key')&&" + keys.map(genFilterCode).join('&&') + ")return null;"), genModifierCode && (code += genModifierCode), "function($event){" + code + (isMethodPath ? "return " + handler.value + "($event)" : isFunctionExpression ? "return (" + handler.value + ")($event)" : isFunctionInvocation ? "return " + handler.value : handler.value) + "}";
}
return isMethodPath || isFunctionExpression ? handler.value : "function($event){" + (isFunctionInvocation ? "return " + handler.value : handler.value) + "}" // inline statement
;
}(events[name]);
events[name] && events[name].dynamic ? dynamicHandlers += name + "," + handlerCode + "," : staticHandlers += "\"" + name + "\":" + handlerCode + ",";
}
return (staticHandlers = "{" + staticHandlers.slice(0, -1) + "}", dynamicHandlers) ? prefix + "_d(" + staticHandlers + ",[" + dynamicHandlers.slice(0, -1) + "])" : prefix + staticHandlers;
}
function genFilterCode(key) {
var keyVal = parseInt(key, 10);
if (keyVal) return "$event.keyCode!==" + keyVal;
var keyCode = keyCodes[key], keyName = keyNames[key];
return "_k($event.keyCode," + JSON.stringify(key) + "," + JSON.stringify(keyCode) + ",$event.key," + JSON.stringify(keyName) + ")";
}
/* */ var baseDirectives = {
on: /* */ function(el, dir) {
dir.modifiers && warn("v-on without argument does not support modifiers."), el.wrapListeners = function(code) {
return "_g(" + code + "," + dir.value + ")";
};
},
bind: /* */ function(el, dir) {
el.wrapData = function(code) {
return "_b(" + code + ",'" + el.tag + "'," + dir.value + "," + (dir.modifiers && dir.modifiers.prop ? 'true' : 'false') + (dir.modifiers && dir.modifiers.sync ? ',true' : '') + ")";
};
},
cloak: noop
}, CodegenState = function(options) {
this.options = options, this.warn = options.warn || baseWarn, this.transforms = pluckModuleFunction(options.modules, 'transformCode'), this.dataGenFns = pluckModuleFunction(options.modules, 'genData'), this.directives = extend(extend({}, baseDirectives), options.directives);
var isReservedTag = options.isReservedTag || no;
this.maybeComponent = function(el) {
return !!el.component || !isReservedTag(el.tag);
}, this.onceId = 0, this.staticRenderFns = [], this.pre = !1;
};
function generate(ast, options) {
var state = new CodegenState(options);
return {
render: "with(this){return " + (ast ? genElement(ast, state) : '_c("div")') + "}",
staticRenderFns: state.staticRenderFns
};
}
function genElement(el, state) {
if (el.parent && (el.pre = el.pre || el.parent.pre), el.staticRoot && !el.staticProcessed) return genStatic(el, state);
if (el.once && !el.onceProcessed) return genOnce(el, state);
if (el.for && !el.forProcessed) return genFor(el, state);
if (el.if && !el.ifProcessed) return genIf(el, state);
if ('template' === el.tag && !el.slotTarget && !state.pre) return genChildren(el, state) || 'void 0';
if ('slot' === el.tag) return res = "_t(" + (el.slotName || '"default"') + ((children = genChildren(el, state)) ? "," + children : ''), attrs = el.attrs || el.dynamicAttrs ? genProps((el.attrs || []).concat(el.dynamicAttrs || []).map(function(attr) {
return {
// slot props are camelized
name: camelize(attr.name),
value: attr.value,
dynamic: attr.dynamic
};
})) : null, bind$$1 = el.attrsMap['v-bind'], (attrs || bind$$1) && !children && (res += ",null"), attrs && (res += "," + attrs), bind$$1 && (res += (attrs ? '' : ',null') + "," + bind$$1), res + ')';
if (el.component) componentName = el.component, children1 = el.inlineTemplate ? null : genChildren(el, state, !0), code = "_c(" + componentName + "," + genData$2(el, state) + (children1 ? "," + children1 : '') + ")";
else {
(!el.plain || el.pre && state.maybeComponent(el)) && (data = genData$2(el, state));
var children, res, attrs, bind$$1, code, componentName, children1, data, children2 = el.inlineTemplate ? null : genChildren(el, state, !0);
code = "_c('" + el.tag + "'" + (data ? "," + data : '') + (children2 ? "," + children2 : '') + ")";
}
// module transforms
for(var i = 0; i < state.transforms.length; i++)code = state.transforms[i](el, code);
return code;
}
// hoist static sub-trees out
function genStatic(el, state) {
el.staticProcessed = !0;
// Some elements (templates) need to behave differently inside of a v-pre
// node. All pre nodes are static roots, so we can use this as a location to
// wrap a state change and reset it upon exiting the pre node.
var originalPreState = state.pre;
return el.pre && (state.pre = el.pre), state.staticRenderFns.push("with(this){return " + genElement(el, state) + "}"), state.pre = originalPreState, "_m(" + (state.staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + ")";
}
// v-once
function genOnce(el, state) {
if (el.onceProcessed = !0, el.if && !el.ifProcessed) return genIf(el, state);
if (!el.staticInFor) return genStatic(el, state);
for(var key = '', parent = el.parent; parent;){
if (parent.for) {
key = parent.key;
break;
}
parent = parent.parent;
}
return key ? "_o(" + genElement(el, state) + "," + state.onceId++ + "," + key + ")" : (state.warn("v-once can only be used inside v-for that is keyed. ", el.rawAttrsMap['v-once']), genElement(el, state));
}
function genIf(el, state, altGen, altEmpty) {
return el.ifProcessed = !0, function genIfConditions(conditions, state, altGen, altEmpty) {
if (!conditions.length) return altEmpty || '_e()';
var condition = conditions.shift();
if (condition.exp) return "(" + condition.exp + ")?" + genTernaryExp(condition.block) + ":" + genIfConditions(conditions, state, altGen, altEmpty);
return "" + genTernaryExp(condition.block);
// v-if with v-once should generate code like (a)?_m(0):_m(1)
function genTernaryExp(el) {
return altGen ? altGen(el, state) : el.once ? genOnce(el, state) : genElement(el, state);
}
}(el.ifConditions.slice(), state, altGen, altEmpty);
}
function genFor(el, state, altGen, altHelper) {
var exp = el.for, alias = el.alias, iterator1 = el.iterator1 ? "," + el.iterator1 : '', iterator2 = el.iterator2 ? "," + el.iterator2 : '';
return state.maybeComponent(el) && 'slot' !== el.tag && 'template' !== el.tag && !el.key && state.warn("<" + el.tag + " v-for=\"" + alias + " in " + exp + '">: component lists rendered with v-for should have explicit keys. See https://vuejs.org/guide/list.html#key for more info.', el.rawAttrsMap['v-for'], !0), el.forProcessed = !0, (altHelper || '_l') + "((" + exp + "),function(" + alias + iterator1 + iterator2 + "){return " + (altGen || genElement)(el, state) + '})';
}
function genData$2(el, state) {
var data = '{', dirs = function(el, state) {
var i, l, dir, needRuntime, dirs = el.directives;
if (dirs) {
var res = 'directives:[', hasRuntime = !1;
for(i = 0, l = dirs.length; i < l; i++){
dir = dirs[i], needRuntime = !0;
var gen = state.directives[dir.name];
gen && // compile-time directive that manipulates AST.
// returns true if it also needs a runtime counterpart.
(needRuntime = !!gen(el, dir, state.warn)), needRuntime && (hasRuntime = !0, res += "{name:\"" + dir.name + "\",rawName:\"" + dir.rawName + "\"" + (dir.value ? ",value:(" + dir.value + "),expression:" + JSON.stringify(dir.value) : '') + (dir.arg ? ",arg:" + (dir.isDynamicArg ? dir.arg : "\"" + dir.arg + "\"") : '') + (dir.modifiers ? ",modifiers:" + JSON.stringify(dir.modifiers) : '') + "},");
}
if (hasRuntime) return res.slice(0, -1) + ']';
}
}(el, state);
dirs && (data += dirs + ','), el.key && (data += "key:" + el.key + ","), el.ref && (data += "ref:" + el.ref + ","), el.refInFor && (data += "refInFor:true,"), el.pre && (data += "pre:true,"), el.component && (data += "tag:\"" + el.tag + "\",");
// module data generation functions
for(var i = 0; i < state.dataGenFns.length; i++)data += state.dataGenFns[i](el);
// inline-template
if (el.attrs && (data += "attrs:" + genProps(el.attrs) + ","), el.props && (data += "domProps:" + genProps(el.props) + ","), el.events && (data += genHandlers(el.events, !1) + ","), el.nativeEvents && (data += genHandlers(el.nativeEvents, !0) + ","), el.slotTarget && !el.slotScope && (data += "slot:" + el.slotTarget + ","), el.scopedSlots && (data += function(el, slots, state) {
// by default scoped slots are considered "stable", this allows child
// components with only scoped slots to skip forced updates from parent.
// but in some cases we have to bail-out of this optimization
// for example if the slot contains dynamic names, has v-if or v-for on them...
var needsForceUpdate = el.for || Object.keys(slots).some(function(key) {
var slot = slots[key];
return slot.slotTargetDynamic || slot.if || slot.for || function containsSlotChild(el) {
return 1 === el.type && ('slot' === el.tag || el.children.some(containsSlotChild));
}(slot) // is passing down slot from parent which may be dynamic
;
}), needsKey = !!el.if;
// OR when it is inside another scoped slot or v-for (the reactivity may be
// disconnected due to the intermediate scope variable)
// #9438, #9506
// TODO: this can be further optimized by properly analyzing in-scope bindings
// and skip force updating ones that do not actually use scope variables.
if (!needsForceUpdate) for(var parent = el.parent; parent;){
if (parent.slotScope && parent.slotScope !== emptySlotScopeToken || parent.for) {
needsForceUpdate = !0;
break;
}
parent.if && (needsKey = !0), parent = parent.parent;
}
var generatedSlots = Object.keys(slots).map(function(key) {
return function genScopedSlot(el, state) {
var isLegacySyntax = el.attrsMap['slot-scope'];
if (el.if && !el.ifProcessed && !isLegacySyntax) return genIf(el, state, genScopedSlot, "null");
if (el.for && !el.forProcessed) return genFor(el, state, genScopedSlot);
var slotScope = el.slotScope === emptySlotScopeToken ? "" : String(el.slotScope), fn = "function(" + slotScope + "){return " + ('template' === el.tag ? el.if && isLegacySyntax ? "(" + el.if + ")?" + (genChildren(el, state) || 'undefined') + ":undefined" : genChildren(el, state) || 'undefined' : genElement(el, state)) + "}";
return "{key:" + (el.slotTarget || "\"default\"") + ",fn:" + fn + (slotScope ? "" : ",proxy:true") + "}";
}(slots[key], state);
}).join(',');
return "scopedSlots:_u([" + generatedSlots + "]" + (needsForceUpdate ? ",null,true" : "") + (!needsForceUpdate && needsKey ? ",null,false," + function(str) {
for(var hash = 5381, i = str.length; i;)hash = 33 * hash ^ str.charCodeAt(--i);
return hash >>> 0;
}(generatedSlots) : "") + ")";
}(el, el.scopedSlots, state) + ","), el.model && (data += "model:{value:" + el.model.value + ",callback:" + el.model.callback + ",expression:" + el.model.expression + "},"), el.inlineTemplate) {
var inlineTemplate = function(el, state) {
var ast = el.children[0];
if ((1 !== el.children.length || 1 !== ast.type) && state.warn('Inline-template components must have exactly one child element.', {
start: el.start
}), ast && 1 === ast.type) {
var inlineRenderFns = generate(ast, state.options);
return "inlineTemplate:{render:function(){" + inlineRenderFns.render + "},staticRenderFns:[" + inlineRenderFns.staticRenderFns.map(function(code) {
return "function(){" + code + "}";
}).join(',') + "]}";
}
}(el, state);
inlineTemplate && (data += inlineTemplate + ",");
}
return data = data.replace(/,$/, '') + '}', el.dynamicAttrs && (data = "_b(" + data + ",\"" + el.tag + "\"," + genProps(el.dynamicAttrs) + ")"), el.wrapData && (data = el.wrapData(data)), el.wrapListeners && (data = el.wrapListeners(data)), data;
}
function genChildren(el, state, checkSkip, altGenElement, altGenNode) {
var children = el.children;
if (children.length) {
var el$1 = children[0];
// optimize single v-for
if (1 === children.length && el$1.for && 'template' !== el$1.tag && 'slot' !== el$1.tag) {
var normalizationType = checkSkip ? state.maybeComponent(el$1) ? ",1" : ",0" : "";
return "" + (altGenElement || genElement)(el$1, state) + normalizationType;
}
var normalizationType$1 = checkSkip ? // determine the normalization needed for the children array.
// 0: no normalization needed
// 1: simple normalization needed (possible 1-level deep nested array)
// 2: full normalization needed
function(children, maybeComponent) {
for(var res = 0, i = 0; i < children.length; i++){
var el = children[i];
if (1 === el.type) {
if (needsNormalization(el) || el.ifConditions && el.ifConditions.some(function(c) {
return needsNormalization(c.block);
})) {
res = 2;
break;
}
(maybeComponent(el) || el.ifConditions && el.ifConditions.some(function(c) {
return maybeComponent(c.block);
})) && (res = 1);
}
}
return res;
}(children, state.maybeComponent) : 0, gen = altGenNode || genNode;
return "[" + children.map(function(c) {
return gen(c, state);
}).join(',') + "]" + (normalizationType$1 ? "," + normalizationType$1 : '');
}
}
function needsNormalization(el) {
return void 0 !== el.for || 'template' === el.tag || 'slot' === el.tag;
}
function genNode(node, state) {
return 1 === node.type ? genElement(node, state) : 3 === node.type && node.isComment ? "_e(" + JSON.stringify(node.text) + ")" : "_v(" + (2 === node.type ? node.expression // no need for () because already wrapped in _s()
: transformSpecialNewlines(JSON.stringify(node.text))) + ")";
}
function genProps(props) {
for(var staticProps = "", dynamicProps = "", i = 0; i < props.length; i++){
var prop = props[i], value = transformSpecialNewlines(prop.value);
prop.dynamic ? dynamicProps += prop.name + "," + value + "," : staticProps += "\"" + prop.name + "\":" + value + ",";
}
return (staticProps = "{" + staticProps.slice(0, -1) + "}", dynamicProps) ? "_d(" + staticProps + ",[" + dynamicProps.slice(0, -1) + "])" : staticProps;
}
// #3895, #4268
function transformSpecialNewlines(text) {
return text.replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029');
}
/* */ // these keywords should not appear inside expressions, but operators like
// typeof, instanceof and in are allowed
var prohibitedKeywordRE = RegExp('\\b' + "do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,super,throw,while,yield,delete,export,import,return,switch,default,extends,finally,continue,debugger,function,arguments".split(',').join('\\b|\\b') + '\\b'), unaryOperatorsRE = RegExp('\\b' + 'delete,typeof,void'.split(',').join('\\s*\\([^\\)]*\\)|\\b') + '\\s*\\([^\\)]*\\)'), stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
function checkIdentifier(ident, type, text, warn, range) {
if ('string' == typeof ident) try {
Function("var " + ident + "=_");
} catch (e) {
warn("invalid " + type + " \"" + ident + "\" in expression: " + text.trim(), range);
}
}
function checkExpression(exp, text, warn, range) {
try {
Function("return " + exp);
} catch (e) {
var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE);
warn(keywordMatch ? 'avoid using JavaScript keyword as property name: "' + keywordMatch[0] + "\"\n Raw expression: " + text.trim() : "invalid expression: " + e.message + " in\n\n " + exp + "\n\n Raw expression: " + text.trim() + "\n", range);
}
}
function repeat$1(str, n) {
var result = '';
if (n > 0) for(; 1 & n && (result += str), !((n >>>= 1) <= 0);)str += str;
return result;
}
/* */ function createFunction(code, errors) {
try {
return Function(code);
} catch (err) {
return errors.push({
err: err,
code: code
}), noop;
}
}
/* */ var ref$1 = (baseCompile = function(template, options) {
var ast = /**
* Convert HTML string to AST.
*/ function(template, options) {
warn$2 = options.warn || baseWarn, platformIsPreTag = options.isPreTag || no, platformMustUseProp = options.mustUseProp || no, platformGetTagNamespace = options.getTagNamespace || no;
var root, currentParent, isReservedTag = options.isReservedTag || no;
maybeComponent = function(el) {
return !!el.component || !isReservedTag(el.tag);
}, transforms = pluckModuleFunction(options.modules, 'transformNode'), preTransforms = pluckModuleFunction(options.modules, 'preTransformNode'), postTransforms = pluckModuleFunction(options.modules, 'postTransformNode'), delimiters = options.delimiters;
var stack = [], preserveWhitespace = !1 !== options.preserveWhitespace, whitespaceOption = options.whitespace, inVPre = !1, inPre = !1, warned = !1;
function warnOnce(msg, range) {
warned || (warned = !0, warn$2(msg, range));
}
function closeElement(element) {
if (trimEndingWhitespace(element), inVPre || element.processed || (element = processElement(element, options)), stack.length || element === root || (root.if && (element.elseif || element.else) ? (checkRootConstraints(element), addIfCondition(root, {
exp: element.elseif,
block: element
})) : warnOnce("Component template should contain exactly one root element. If you are using v-if on multiple elements, use v-else-if to chain them instead.", {
start: element.start
})), currentParent && !element.forbidden) {
if (element.elseif || element.else) {
var el, prev;
el = element, (prev = function(children) {
for(var i = children.length; i--;){
if (1 === children[i].type) return children[i];
' ' !== children[i].text && warn$2("text \"" + children[i].text.trim() + '" between v-if and v-else(-if) will be ignored.', children[i]), children.pop();
}
}(currentParent.children)) && prev.if ? addIfCondition(prev, {
exp: el.elseif,
block: el
}) : warn$2("v-" + (el.elseif ? 'else-if="' + el.elseif + '"' : 'else') + " used on element <" + el.tag + "> without corresponding v-if.", el.rawAttrsMap[el.elseif ? 'v-else-if' : 'v-else']);
} else {
if (element.slotScope) {
// scoped slot
// keep it in the children list so that v-else(-if) conditions can
// find it as the prev node.
var name = element.slotTarget || '"default"';
(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element;
}
currentParent.children.push(element), element.parent = currentParent;
}
}
// final children cleanup
// filter out scoped slots
element.children = element.children.filter(function(c) {
return !c.slotScope;
}), // remove trailing whitespace node again
trimEndingWhitespace(element), element.pre && (inVPre = !1), platformIsPreTag(element.tag) && (inPre = !1);
// apply post-transforms
for(var i = 0; i < postTransforms.length; i++)postTransforms[i](element, options);
}
function trimEndingWhitespace(el) {
// remove trailing whitespace node
if (!inPre) for(var lastNode; (lastNode = el.children[el.children.length - 1]) && 3 === lastNode.type && ' ' === lastNode.text;)el.children.pop();
}
function checkRootConstraints(el) {
('slot' === el.tag || 'template' === el.tag) && warnOnce("Cannot use <" + el.tag + "> as component root element because it may contain multiple nodes.", {
start: el.start
}), el.attrsMap.hasOwnProperty('v-for') && warnOnce("Cannot use v-for on stateful component root element because it renders multiple elements.", el.rawAttrsMap['v-for']);
}
return function(html, options) {
for(var last, lastTag, stack = [], expectHTML = options.expectHTML, isUnaryTag$$1 = options.isUnaryTag || no, canBeLeftOpenTag$$1 = options.canBeLeftOpenTag || no, index = 0; html;){
// Make sure we're not in a plaintext content element like script/style
if (last = html, lastTag && isPlainTextElement(lastTag)) {
var endTagLength = 0, stackedTag = lastTag.toLowerCase(), reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i')), rest$1 = html.replace(reStackedTag, function(all, text, endTag) {
return endTagLength = endTag.length, isPlainTextElement(stackedTag) || 'noscript' === stackedTag || (text = text.replace(/<!\--([\s\S]*?)-->/g, '$1') // #7298
.replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1')), shouldIgnoreFirstNewline(stackedTag, text) && (text = text.slice(1)), options.chars && options.chars(text), '';
});
index += html.length - rest$1.length, html = rest$1, parseEndTag(stackedTag, index - endTagLength, index);
} else {
var textEnd = html.indexOf('<');
if (0 === textEnd) {
// Comment:
if (comment.test(html)) {
var commentEnd = html.indexOf('-->');
if (commentEnd >= 0) {
options.shouldKeepComment && options.comment(html.substring(4, commentEnd), index, index + commentEnd + 3), advance(commentEnd + 3);
continue;
}
}
// http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment
if (conditionalComment.test(html)) {
var conditionalEnd = html.indexOf(']>');
if (conditionalEnd >= 0) {
advance(conditionalEnd + 2);
continue;
}
}
// Doctype:
var doctypeMatch = html.match(doctype);
if (doctypeMatch) {
advance(doctypeMatch[0].length);
continue;
}
// End tag:
var endTagMatch = html.match(endTag);
if (endTagMatch) {
var curIndex = index;
advance(endTagMatch[0].length), parseEndTag(endTagMatch[1], curIndex, index);
continue;
}
// Start tag:
var startTagMatch = function() {
var start = html.match(startTagOpen);
if (start) {
var end, attr, match = {
tagName: start[1],
attrs: [],
start: index
};
for(advance(start[0].length); !(end = html.match(startTagClose)) && (attr = html.match(dynamicArgAttribute) || html.match(attribute));)attr.start = index, advance(attr[0].length), attr.end = index, match.attrs.push(attr);
if (end) return match.unarySlash = end[1], advance(end[0].length), match.end = index, match;
}
}();
if (startTagMatch) {
(function(match) {
var tagName = match.tagName, unarySlash = match.unarySlash;
expectHTML && ('p' === lastTag && isNonPhrasingTag(tagName) && parseEndTag(lastTag), canBeLeftOpenTag$$1(tagName) && lastTag === tagName && parseEndTag(tagName));
for(var unary = isUnaryTag$$1(tagName) || !!unarySlash, l = match.attrs.length, attrs = Array(l), i = 0; i < l; i++){
var args = match.attrs[i], value = args[3] || args[4] || args[5] || '', shouldDecodeNewlines = 'a' === tagName && 'href' === args[1] ? options.shouldDecodeNewlinesForHref : options.shouldDecodeNewlines;
attrs[i] = {
name: args[1],
value: value.replace(shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr, function(match) {
return decodingMap[match];
})
}, options.outputSourceRange && (attrs[i].start = args.start + args[0].match(/^\s*/).length, attrs[i].end = args.end);
}
unary || (stack.push({
tag: tagName,
lowerCasedTag: tagName.toLowerCase(),
attrs: attrs,
start: match.start,
end: match.end
}), lastTag = tagName), options.start && options.start(tagName, attrs, unary, match.start, match.end);
})(startTagMatch), shouldIgnoreFirstNewline(startTagMatch.tagName, html) && advance(1);
continue;
}
}
var text = void 0, rest = void 0, next = void 0;
if (textEnd >= 0) {
for(rest = html.slice(textEnd); !endTag.test(rest) && !startTagOpen.test(rest) && !comment.test(rest) && !conditionalComment.test(rest) && !(// < in plain text, be forgiving and treat it as text
(next = rest.indexOf('<', 1)) < 0);)textEnd += next, rest = html.slice(textEnd);
text = html.substring(0, textEnd);
}
textEnd < 0 && (text = html), text && advance(text.length), options.chars && text && options.chars(text, index - text.length, index);
}
if (html === last) {
options.chars && options.chars(html), !stack.length && options.warn && options.warn("Mal-formatted tag at end of template: \"" + html + "\"", {
start: index + html.length
});
break;
}
}
function advance(n) {
index += n, html = html.substring(n);
}
function parseEndTag(tagName, start, end) {
var pos, lowerCasedTagName;
// Find the closest opened tag of the same type
if (null == start && (start = index), null == end && (end = index), tagName) for(lowerCasedTagName = tagName.toLowerCase(), pos = stack.length - 1; pos >= 0 && stack[pos].lowerCasedTag !== lowerCasedTagName; pos--);
else // If no tag name is provided, clean shop
pos = 0;
if (pos >= 0) {
// Close all the open elements, up the stack
for(var i = stack.length - 1; i >= pos; i--)(i > pos || !tagName && options.warn) && options.warn("tag <" + stack[i].tag + "> has no matching end tag.", {
start: stack[i].start,
end: stack[i].end
}), options.end && options.end(stack[i].tag, start, end);
// Remove the open elements from the stack
stack.length = pos, lastTag = pos && stack[pos - 1].tag;
} else 'br' === lowerCasedTagName ? options.start && options.start(tagName, [], !0, start, end) : 'p' === lowerCasedTagName && (options.start && options.start(tagName, [], !1, start, end), options.end && options.end(tagName, start, end));
}
// Clean up any remaining tags
parseEndTag();
}(template, {
warn: warn$2,
expectHTML: options.expectHTML,
isUnaryTag: options.isUnaryTag,
canBeLeftOpenTag: options.canBeLeftOpenTag,
shouldDecodeNewlines: options.shouldDecodeNewlines,
shouldDecodeNewlinesForHref: options.shouldDecodeNewlinesForHref,
shouldKeepComment: options.comments,
outputSourceRange: options.outputSourceRange,
start: function(tag, attrs, unary, start$1, end) {
// check namespace.
// inherit parent ns if there is one
var el, el1, el2, ns = currentParent && currentParent.ns || platformGetTagNamespace(tag);
isIE && 'svg' === ns && (attrs = /* istanbul ignore next */ function(attrs) {
for(var res = [], i = 0; i < attrs.length; i++){
var attr = attrs[i];
ieNSBug.test(attr.name) || (attr.name = attr.name.replace(ieNSPrefix, ''), res.push(attr));
}
return res;
}(attrs));
var element = createASTElement(tag, attrs, currentParent);
ns && (element.ns = ns), options.outputSourceRange && (element.start = start$1, element.end = end, element.rawAttrsMap = element.attrsList.reduce(function(cumulated, attr) {
return cumulated[attr.name] = attr, cumulated;
}, {})), attrs.forEach(function(attr) {
invalidAttributeRE.test(attr.name) && warn$2("Invalid dynamic argument expression: attribute names cannot contain spaces, quotes, <, >, / or =.", {
start: attr.start + attr.name.indexOf("["),
end: attr.start + attr.name.length
});
}), 'style' !== (el = element).tag && ('script' !== el.tag || el.attrsMap.type && 'text/javascript' !== el.attrsMap.type) || isServerRendering() || (element.forbidden = !0, warn$2("Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <" + tag + ">, as they will not be parsed.", {
start: element.start
}));
// apply pre-transforms
for(var i = 0; i < preTransforms.length; i++)element = preTransforms[i](element, options) || element;
!inVPre && (null != getAndRemoveAttr(el1 = element, 'v-pre') && (el1.pre = !0), element.pre && (inVPre = !0)), platformIsPreTag(element.tag) && (inPre = !0), inVPre ? function(el) {
var list = el.attrsList, len = list.length;
if (len) for(var attrs = el.attrs = Array(len), i = 0; i < len; i++)attrs[i] = {
name: list[i].name,
value: JSON.stringify(list[i].value)
}, null != list[i].start && (attrs[i].start = list[i].start, attrs[i].end = list[i].end);
else el.pre || // non root node in pre blocks with no attributes
(el.plain = !0);
}(element) : element.processed || (// structural directives
processFor(element), function(el) {
var exp = getAndRemoveAttr(el, 'v-if');
if (exp) el.if = exp, addIfCondition(el, {
exp: exp,
block: el
});
else {
null != getAndRemoveAttr(el, 'v-else') && (el.else = !0);
var elseif = getAndRemoveAttr(el, 'v-else-if');
elseif && (el.elseif = elseif);
}
}(element), null != getAndRemoveAttr(el2 = element, 'v-once') && (el2.once = !0)), root || checkRootConstraints(root = element), unary ? closeElement(element) : (currentParent = element, stack.push(element));
},
end: function(tag, start, end$1) {
var element = stack[stack.length - 1];
// pop stack
stack.length -= 1, currentParent = stack[stack.length - 1], options.outputSourceRange && (element.end = end$1), closeElement(element);
},
chars: function(text, start, end) {
if (!currentParent) {
text === template ? warnOnce('Component template requires a root element, rather than just text.', {
start: start
}) : (text = text.trim()) && warnOnce("text \"" + text + "\" outside root element will be ignored.", {
start: start
});
return;
}
// IE textarea placeholder bug
/* istanbul ignore if */ if (!isIE || 'textarea' !== currentParent.tag || currentParent.attrsMap.placeholder !== text) {
var el, res, child, children = currentParent.children;
(text = inPre || text.trim() ? 'script' === (el = currentParent).tag || 'style' === el.tag ? text : decodeHTMLCached(text) : children.length ? whitespaceOption ? 'condense' === whitespaceOption && lineBreakRE.test(text) ? '' : ' ' : preserveWhitespace ? ' ' : '' : '') && (inPre || 'condense' !== whitespaceOption || // condense consecutive whitespaces into single space
(text = text.replace(whitespaceRE$1, ' ')), !inVPre && ' ' !== text && (res = parseText(text, delimiters)) ? child = {
type: 2,
expression: res.expression,
tokens: res.tokens,
text: text
} : ' ' === text && children.length && ' ' === children[children.length - 1].text || (child = {
type: 3,
text: text
}), child && (options.outputSourceRange && (child.start = start, child.end = end), children.push(child)));
}
},
comment: function(text, start, end) {
// adding anything as a sibling to the root node is forbidden
// comments should still be allowed, but ignored
if (currentParent) {
var child = {
type: 3,
text: text,
isComment: !0
};
options.outputSourceRange && (child.start = start, child.end = end), currentParent.children.push(child);
}
}
}), root;
}(template.trim(), options);
!1 !== options.optimize && ast && (isStaticKey = genStaticKeysCached(options.staticKeys || ''), isPlatformReservedTag = options.isReservedTag || no, // first pass: mark all non-static nodes.
function markStatic$1(node) {
if (node.static = 2 !== node.type && (3 === node.type || !!(node.pre || !node.hasBindings && // no dynamic bindings
!node.if && !node.for && // not v-if or v-for or v-else
!isBuiltInTag(node.tag) && // not a built-in
isPlatformReservedTag(node.tag) && // not a component
!function(node) {
for(; node.parent && 'template' === (node = node.parent).tag;)if (node.for) return !0;
return !1;
}(node) && Object.keys(node).every(isStaticKey))), 1 === node.type && (isPlatformReservedTag(node.tag) || 'slot' === node.tag || null != node.attrsMap['inline-template'])) {
for(var i = 0, l = node.children.length; i < l; i++){
var child = node.children[i];
markStatic$1(child), child.static || (node.static = !1);
}
if (node.ifConditions) for(var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++){
var block = node.ifConditions[i$1].block;
markStatic$1(block), block.static || (node.static = !1);
}
}
}(ast), // second pass: mark static roots.
function markStaticRoots(node, isInFor) {
if (1 === node.type) {
// For a node to qualify as a static root, it should have children that
// are not just static text. Otherwise the cost of hoisting out will
// outweigh the benefits and it's better off to just always render it fresh.
if ((node.static || node.once) && (node.staticInFor = isInFor), node.static && node.children.length && (1 !== node.children.length || 3 !== node.children[0].type)) {
node.staticRoot = !0;
return;
}
if (node.staticRoot = !1, node.children) for(var i = 0, l = node.children.length; i < l; i++)markStaticRoots(node.children[i], isInFor || !!node.for);
if (node.ifConditions) for(var i$1 = 1, l$1 = node.ifConditions.length; i$1 < l$1; i$1++)markStaticRoots(node.ifConditions[i$1].block, isInFor);
}
}(ast, !1));
var code = generate(ast, options);
return {
ast: ast,
render: code.render,
staticRenderFns: code.staticRenderFns
};
}, function(baseOptions) {
var cache;
function compile(template, options) {
var ast, warn, finalOptions = Object.create(baseOptions), errors = [], tips = [], warn1 = function(msg, range, tip) {
(tip ? tips : errors).push(msg);
};
if (options) {
if (options.outputSourceRange) {
// $flow-disable-line
var leadingSpaceLength = template.match(/^\s*/)[0].length;
warn1 = function(msg, range, tip) {
var data = {
msg: msg
};
range && (null != range.start && (data.start = range.start + leadingSpaceLength), null != range.end && (data.end = range.end + leadingSpaceLength)), (tip ? tips : errors).push(data);
};
}
// copy other options
for(var key in options.modules && (finalOptions.modules = (baseOptions.modules || []).concat(options.modules)), options.directives && (finalOptions.directives = extend(Object.create(baseOptions.directives || null), options.directives)), options)'modules' !== key && 'directives' !== key && (finalOptions[key] = options[key]);
}
finalOptions.warn = warn1;
var compiled = baseCompile(template.trim(), finalOptions);
return ast = compiled.ast, warn = warn1, ast && function checkNode(node, warn) {
if (1 === node.type) {
for(var name in node.attrsMap)if (dirRE.test(name)) {
var value = node.attrsMap[name];
if (value) {
var text, range = node.rawAttrsMap[name];
'v-for' === name ? (text = "v-for=\"" + value + "\"", checkExpression(node.for || '', text, warn, range), checkIdentifier(node.alias, 'v-for alias', text, warn, range), checkIdentifier(node.iterator1, 'v-for iterator', text, warn, range), checkIdentifier(node.iterator2, 'v-for iterator', text, warn, range)) : 'v-slot' === name || '#' === name[0] ? function(exp, text, warn, range) {
try {
Function(exp, '');
} catch (e) {
warn("invalid function parameter expression: " + e.message + " in\n\n " + exp + "\n\n Raw expression: " + text.trim() + "\n", range);
}
}(value, name + "=\"" + value + "\"", warn, range) : onRE.test(name) ? function(exp, text, warn, range) {
var stripped = exp.replace(stripStringRE, ''), keywordMatch = stripped.match(unaryOperatorsRE);
keywordMatch && '$' !== stripped.charAt(keywordMatch.index - 1) && warn('avoid using JavaScript unary operator as property name: "' + keywordMatch[0] + "\" in expression " + text.trim(), range), checkExpression(exp, text, warn, range);
}(value, name + "=\"" + value + "\"", warn, range) : checkExpression(value, name + "=\"" + value + "\"", warn, range);
}
}
if (node.children) for(var i = 0; i < node.children.length; i++)checkNode(node.children[i], warn);
} else 2 === node.type && checkExpression(node.expression, node.text, warn, node);
}(ast, warn), compiled.errors = errors, compiled.tips = tips, compiled;
}
return {
compile: compile,
compileToFunctions: (cache = Object.create(null), function(template, options, vm) {
var warn$$1 = (options = extend({}, options)).warn || warn;
delete options.warn;
// detect possible CSP restriction
try {
Function('return 1');
} catch (e) {
e.toString().match(/unsafe-eval|CSP/) && warn$$1("It seems you are using the standalone build of Vue.js in an environment with Content Security Policy that prohibits unsafe-eval. The template compiler cannot work in this environment. Consider relaxing the policy to allow unsafe-eval or pre-compiling your templates into render functions.");
}
// check cache
var key = options.delimiters ? String(options.delimiters) + template : template;
if (cache[key]) return cache[key];
// compile
var compiled = compile(template, options);
compiled.errors && compiled.errors.length && (options.outputSourceRange ? compiled.errors.forEach(function(e) {
warn$$1("Error compiling template:\n\n" + e.msg + "\n\n" + function(source, start, end) {
void 0 === start && (start = 0), void 0 === end && (end = source.length);
for(var lines = source.split(/\r?\n/), count = 0, res = [], i = 0; i < lines.length; i++)if ((count += lines[i].length + 1) >= start) {
for(var j = i - 2; j <= i + 2 || end > count; j++)if (!(j < 0) && !(j >= lines.length)) {
res.push("" + (j + 1) + repeat$1(" ", 3 - String(j + 1).length) + "| " + lines[j]);
var lineLength = lines[j].length;
if (j === i) {
// push underline
var pad = start - (count - lineLength) + 1, length = end > count ? lineLength - pad : end - start;
res.push(" | " + repeat$1(" ", pad) + repeat$1("^", length));
} else if (j > i) {
if (end > count) {
var length$1 = Math.min(end - count, lineLength);
res.push(" | " + repeat$1("^", length$1));
}
count += lineLength + 1;
}
}
break;
}
return res.join('\n');
}(template, e.start, e.end), vm);
}) : warn$$1("Error compiling template:\n\n" + template + "\n\n" + compiled.errors.map(function(e) {
return "- " + e;
}).join('\n') + '\n', vm)), compiled.tips && compiled.tips.length && (options.outputSourceRange ? compiled.tips.forEach(function(e) {
return tip(e.msg, vm);
}) : compiled.tips.forEach(function(msg) {
return tip(msg, vm);
}));
// turn code into functions
var res = {}, fnGenErrors = [];
return res.render = createFunction(compiled.render, fnGenErrors), res.staticRenderFns = compiled.staticRenderFns.map(function(code) {
return createFunction(code, fnGenErrors);
}), compiled.errors && compiled.errors.length || !fnGenErrors.length || warn$$1("Failed to generate render function:\n\n" + fnGenErrors.map(function(ref) {
var err = ref.err, code = ref.code;
return err.toString() + " in\n\n" + code + "\n";
}).join('\n'), vm), cache[key] = res;
})
};
})(baseOptions);
ref$1.compile;
var compileToFunctions = ref$1.compileToFunctions;
function getShouldDecode(href) {
return (div = div || document.createElement('div')).innerHTML = href ? "<a href=\"\n\"/>" : "<div a=\"\n\"/>", div.innerHTML.indexOf(' ') > 0;
}
// #3663: IE encodes newlines inside attribute values while other browsers don't
var shouldDecodeNewlines = !!inBrowser && getShouldDecode(!1), shouldDecodeNewlinesForHref = !!inBrowser && getShouldDecode(!0), idToTemplate = cached(function(id) {
var el = query(id);
return el && el.innerHTML;
}), mount = Vue1.prototype.$mount;
return Vue1.prototype.$mount = function(el, hydrating) {
/* istanbul ignore if */ if ((el = el && query(el)) === document.body || el === document.documentElement) return warn("Do not mount Vue to <html> or <body> - mount to normal elements instead."), this;
var options = this.$options;
// resolve template/el and convert to render function
if (!options.render) {
var template = options.template;
if (template) {
if ('string' == typeof template) '#' !== template.charAt(0) || (template = idToTemplate(template)) || warn("Template element not found or is empty: " + options.template, this);
else {
if (!template.nodeType) return warn('invalid template option:' + template, this), this;
template = template.innerHTML;
}
} else el && (template = /**
* Get outerHTML of elements, taking care
* of SVG elements in IE as well.
*/ function(el) {
if (el.outerHTML) return el.outerHTML;
var container = document.createElement('div');
return container.appendChild(el.cloneNode(!0)), container.innerHTML;
}(el));
if (template) {
config.performance && mark && mark('compile');
var ref = compileToFunctions(template, {
outputSourceRange: !0,
shouldDecodeNewlines: shouldDecodeNewlines,
shouldDecodeNewlinesForHref: shouldDecodeNewlinesForHref,
delimiters: options.delimiters,
comments: options.comments
}, this), render = ref.render, staticRenderFns = ref.staticRenderFns;
options.render = render, options.staticRenderFns = staticRenderFns, config.performance && mark && (mark('compile end'), measure("vue " + this._name + " compile", 'compile', 'compile end'));
}
}
return mount.call(this, el, hydrating);
}, Vue1.compile = compileToFunctions, Vue1;
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/compress.rs | Rust | #![deny(warnings)]
extern crate swc_malloc;
use std::{
env,
fmt::Debug,
fs::read_to_string,
panic::catch_unwind,
path::{Path, PathBuf},
time::Instant,
};
use ansi_term::Color;
use anyhow::Error;
use once_cell::sync::Lazy;
use serde::Deserialize;
use swc_common::{
comments::{Comments, SingleThreadedComments},
errors::{Handler, HANDLER},
input::SourceFileInput,
sync::Lrc,
util::take::Take,
EqIgnoreSpan, FileName, Mark, SourceMap,
};
use swc_ecma_ast::*;
use swc_ecma_codegen::{
text_writer::{omit_trailing_semi, JsWriter, WriteJs},
Emitter,
};
use swc_ecma_minifier::{
optimize,
option::{
terser::TerserCompressorOptions, CompressOptions, ExtraOptions, MangleOptions,
MinifyOptions, TopLevelOptions,
},
};
use swc_ecma_parser::{lexer::Lexer, EsSyntax, Parser, Syntax};
use swc_ecma_testing::{exec_node_js, JsExecOptions};
use swc_ecma_transforms_base::{
fixer::{fixer, paren_remover},
hygiene::hygiene,
resolver,
};
use swc_ecma_utils::drop_span;
use swc_ecma_visit::{VisitMut, VisitMutWith};
use testing::{assert_eq, unignore_fixture, DebugUsingDisplay, NormalizedOutput};
fn load_txt(filename: &str) -> Vec<String> {
let lines = read_to_string(filename).unwrap();
lines
.lines()
.filter(|v| !v.trim().is_empty())
.map(|v| v.to_string())
.collect()
}
fn is_ignored(path: &Path) -> bool {
static IGNORED: Lazy<Vec<String>> = Lazy::new(|| {
load_txt("tests/TODO.txt")
.into_iter()
.chain(load_txt("tests/postponed.txt"))
.collect()
});
static GOLDEN: Lazy<Vec<String>> = Lazy::new(|| load_txt("tests/passing.txt"));
let s = path.to_string_lossy().replace('-', "_").replace('\\', "/");
if IGNORED.iter().any(|ignored| s.contains(&**ignored)) {
return true;
}
if env::var("SKIP_GOLDEN").unwrap_or_default() == "1"
&& GOLDEN.iter().any(|ignored| s.contains(&**ignored))
{
return true;
}
if let Ok(one) = env::var("GOLDEN_ONLY") {
if one == "1" && GOLDEN.iter().all(|golden| !s.contains(&**golden)) {
return true;
}
}
false
}
#[derive(Debug, Default, Clone, Deserialize)]
struct TopLevelOnly {
#[serde(default, alias = "toplevel")]
top_level: bool,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(untagged)]
enum TestMangleOptions {
Bool(bool),
Normal(MangleOptions),
}
impl TestMangleOptions {
fn parse(s: &str) -> Self {
let top_level = serde_json::from_str::<TopLevelOnly>(s).unwrap_or_default();
let mut data = serde_json::from_str::<Self>(s).expect("failed to deserialize mangle.json");
if let TestMangleOptions::Normal(v) = &mut data {
v.top_level = Some(top_level.top_level);
}
data
}
}
#[derive(Debug, Clone, Deserialize)]
struct TestOptions {
#[serde(default)]
defaults: bool,
#[serde(default)]
passes: usize,
}
fn parse_compressor_config(cm: Lrc<SourceMap>, s: &str) -> (bool, CompressOptions) {
let opts: TestOptions =
serde_json::from_str(s).expect("failed to deserialize value into a compressor config");
let mut c: TerserCompressorOptions =
serde_json::from_str(s).expect("failed to deserialize value into a compressor config");
c.defaults = opts.defaults;
c.const_to_let = Some(false);
c.pristine_globals = Some(true);
c.passes = opts.passes;
(c.module, c.into_config(cm))
}
fn run(
cm: Lrc<SourceMap>,
handler: &Handler,
input: &Path,
config: &str,
comments: Option<&dyn Comments>,
mangle: Option<TestMangleOptions>,
skip_hygiene: bool,
) -> Option<Program> {
HANDLER.set(handler, || {
let disable_hygiene = mangle.is_some() || skip_hygiene;
let (_module, mut config) = parse_compressor_config(cm.clone(), config);
let fm = cm.load_file(input).expect("failed to load input.js");
eprintln!("---- {} -----\n{}", Color::Green.paint("Input"), fm.src);
if env::var("SWC_RUN").unwrap_or_default() == "1" {
let stdout = stdout_of(&fm.src);
match stdout {
Ok(stdout) => {
eprintln!(
"---- {} -----\n{}",
Color::Green.paint("Stdout (expected)"),
stdout
);
}
Err(err) => {
eprintln!(
"---- {} -----\n{:?}",
Color::Green.paint("Error (of original source code)"),
err
);
}
}
}
let unresolved_mark = Mark::new();
let top_level_mark = Mark::new();
let minification_start = Instant::now();
let lexer = Lexer::new(
Syntax::Es(EsSyntax {
jsx: true,
..Default::default()
}),
Default::default(),
SourceFileInput::from(&*fm),
Some(&comments),
);
let mut parser = Parser::new_from(lexer);
let program = parser
.parse_program()
.map_err(|err| {
err.into_diagnostic(handler).emit();
})
.map(|mut program| {
program.visit_mut_with(&mut paren_remover(Some(&comments)));
program.visit_mut_with(&mut resolver(unresolved_mark, top_level_mark, false));
program
});
// Ignore parser errors.
//
// This is typically related to strict mode caused by module context.
let program = match program {
Ok(v) => v,
_ => return None,
};
if config.top_level.is_none() {
if program.is_module() {
config.top_level = Some(TopLevelOptions { functions: true });
} else {
config.top_level = Some(TopLevelOptions { functions: false });
}
}
let optimization_start = Instant::now();
let mut output = optimize(
program,
cm,
Some(&comments),
None,
&MinifyOptions {
compress: Some(config),
mangle: mangle.and_then(|v| match v {
TestMangleOptions::Bool(v) => {
if v {
Some(MangleOptions {
top_level: Some(false),
..Default::default()
})
} else {
None
}
}
TestMangleOptions::Normal(v) => Some(v),
}),
..Default::default()
},
&ExtraOptions {
unresolved_mark,
top_level_mark,
mangle_name_cache: None,
},
);
let end = Instant::now();
tracing::info!(
"optimize({}) took {:?}",
input.display(),
end - optimization_start
);
if !disable_hygiene {
output.visit_mut_with(&mut hygiene())
}
let output = output.apply(&mut fixer(None));
let end = Instant::now();
tracing::info!(
"process({}) took {:?}",
input.display(),
end - minification_start
);
Some(output)
})
}
fn stdout_of(code: &str) -> Result<String, Error> {
exec_node_js(
&format!(
"
{}
{}",
include_str!("./terser_exec_base.js"),
code
),
JsExecOptions {
cache: true,
module: false,
..Default::default()
},
)
}
fn find_config(dir: &Path) -> String {
let mut cur = Some(dir);
while let Some(dir) = cur {
let config = dir.join("config.json");
if config.exists() {
let config = read_to_string(&config).expect("failed to read config.json");
return config;
}
cur = dir.parent();
}
panic!("failed to find config file for {}", dir.display())
}
#[testing::fixture("tests/fixture/**/input.js")]
#[testing::fixture("tests/pass-1/**/input.js")]
#[testing::fixture("tests/pass-default/**/input.js")]
fn custom_fixture(input: PathBuf) {
let dir = input.parent().unwrap();
let config = find_config(dir);
eprintln!("---- {} -----\n{}", Color::Green.paint("Config"), config);
testing::run_test2(false, |cm, handler| {
let comments = SingleThreadedComments::default();
let mangle = dir.join("mangle.json");
let mangle = read_to_string(mangle).ok();
if let Some(mangle) = &mangle {
eprintln!(
"---- {} -----\n{}",
Color::Green.paint("Mangle config"),
mangle
);
}
let mangle: Option<TestMangleOptions> =
mangle.map(|s| serde_json::from_str(&s).expect("failed to deserialize mangle.json"));
let output = run(
cm.clone(),
&handler,
&input,
&config,
Some(&comments),
mangle,
false,
);
let output_module = match output {
Some(v) => v,
None => return Ok(()),
};
let output = print(cm, &[output_module], Some(&comments), false, false);
eprintln!("---- {} -----\n{}", Color::Green.paint("Output"), output);
println!("{}", input.display());
NormalizedOutput::from(output)
.compare_to_file(dir.join("output.js"))
.unwrap();
Ok(())
})
.unwrap()
}
#[testing::fixture("tests/projects/files/*.js")]
fn projects(input: PathBuf) {
let dir = input.parent().unwrap();
let config = dir.join("config.json");
let config = read_to_string(config).expect("failed to read config.json");
eprintln!("---- {} -----\n{}", Color::Green.paint("Config"), config);
testing::run_test2(false, |cm, handler| {
let comments = SingleThreadedComments::default();
let output = run(
cm.clone(),
&handler,
&input,
&config,
Some(&comments),
None,
false,
);
let output_module = match output {
Some(v) => v,
None => return Ok(()),
};
let output = print(cm.clone(), &[output_module], Some(&comments), false, false);
eprintln!("---- {} -----\n{}", Color::Green.paint("Output"), output);
println!("{}", input.display());
let minified = {
let output = run(
cm.clone(),
&handler,
&input,
r#"{ "defaults": true, "toplevel": true, "passes": 3 }"#,
Some(&comments),
Some(TestMangleOptions::Normal(MangleOptions {
top_level: Some(true),
..Default::default()
})),
false,
);
let output_module = match output {
Some(v) => v,
None => return Ok(()),
};
print(cm, &[output_module], Some(&comments), true, true)
};
eprintln!(
"---- {} -----\n{}",
Color::Green.paint("Size"),
minified.len()
);
NormalizedOutput::from(output)
.compare_to_file(
dir.parent()
.unwrap()
.join("output")
.join(input.file_name().unwrap()),
)
.unwrap();
Ok(())
})
.unwrap()
}
/// antd and typescript test is way too slow
#[testing::fixture("benches/full/*.js", exclude("typescript", "antd"))]
fn projects_bench(input: PathBuf) {
let dir = input
.parent()
.unwrap()
.parent()
.unwrap()
.parent()
.unwrap()
.join("tests")
.join("benches-full");
testing::run_test2(false, |cm, handler| {
let comments = SingleThreadedComments::default();
let output = run(
cm.clone(),
&handler,
&input,
r#"{ "defaults": true, "toplevel": false, "passes": 3 }"#,
Some(&comments),
None,
false,
);
let output_module = match output {
Some(v) => v,
None => return Ok(()),
};
let output = print(cm, &[output_module], Some(&comments), false, false);
eprintln!("---- {} -----\n{}", Color::Green.paint("Output"), output);
println!("{}", input.display());
NormalizedOutput::from(output)
.compare_to_file(dir.join(input.file_name().unwrap()))
.unwrap();
Ok(())
})
.unwrap();
}
/// Tests ported from terser.
#[testing::fixture("tests/terser/compress/**/input.js")]
fn fixture(input: PathBuf) {
if is_ignored(&input) {
return;
}
let dir = input.parent().unwrap();
let config = dir.join("config.json");
let config = read_to_string(config).expect("failed to read config.json");
eprintln!("---- {} -----\n{}", Color::Green.paint("Config"), config);
testing::run_test2(false, |cm, handler| {
let mangle = dir.join("mangle.json");
let mangle = read_to_string(mangle).ok();
if let Some(mangle) = &mangle {
eprintln!(
"---- {} -----\n{}",
Color::Green.paint("Mangle config"),
mangle
);
}
let comments = SingleThreadedComments::default();
let mangle: Option<TestMangleOptions> = mangle.map(|s| TestMangleOptions::parse(&s));
let output = run(
cm.clone(),
&handler,
&input,
&config,
Some(&comments),
mangle,
false,
);
let output_program = match output {
Some(v) => v,
None => return Ok(()),
};
let output = print(
cm.clone(),
&[output_program.clone()],
Some(&comments),
false,
false,
);
eprintln!("---- {} -----\n{}", Color::Green.paint("Output"), output);
let expected = {
let expected = read_to_string(dir.join("output.js")).unwrap();
let fm = cm.new_source_file(FileName::Custom("expected.js".into()).into(), expected);
let lexer = Lexer::new(
Default::default(),
Default::default(),
SourceFileInput::from(&*fm),
None,
);
let mut parser = Parser::new_from(lexer);
let expected = parser.parse_program().map_err(|err| {
err.into_diagnostic(&handler).emit();
})?;
let mut expected = expected.apply(&mut fixer(None));
expected = drop_span(expected);
match &mut expected {
Program::Module(m) => {
m.body
.retain(|s| !matches!(s, ModuleItem::Stmt(Stmt::Empty(..))));
}
Program::Script(s) => s.body.retain(|s| !matches!(s, Stmt::Empty(..))),
}
let mut normalized_expected = expected.clone();
normalized_expected.visit_mut_with(&mut DropParens);
let mut actual = output_program.clone();
actual.visit_mut_with(&mut DropParens);
if actual.eq_ignore_span(&normalized_expected)
|| drop_span(actual.clone()) == normalized_expected
{
return Ok(());
}
if print(cm.clone(), &[actual], Some(&comments), false, false)
== print(
cm.clone(),
&[normalized_expected],
Some(&comments),
false,
false,
)
{
return Ok(());
}
print(cm.clone(), &[expected], Some(&comments), false, false)
};
{
// Check output.teraer.js
let identical = (|| -> Option<()> {
let expected = {
let expected = read_to_string(dir.join("output.terser.js")).ok()?;
let fm = cm.new_source_file(FileName::Anon.into(), expected);
let lexer = Lexer::new(
Default::default(),
Default::default(),
SourceFileInput::from(&*fm),
None,
);
let mut parser = Parser::new_from(lexer);
let expected = parser
.parse_program()
.map_err(|err| {
err.into_diagnostic(&handler).emit();
})
.ok()?;
let mut expected = expected.apply(fixer(None));
expected = drop_span(expected);
match &mut expected {
Program::Module(m) => {
m.body
.retain(|s| !matches!(s, ModuleItem::Stmt(Stmt::Empty(..))));
}
Program::Script(s) => s.body.retain(|s| !matches!(s, Stmt::Empty(..))),
}
let mut normalized_expected = expected.clone();
normalized_expected.visit_mut_with(&mut DropParens);
let mut actual = output_program.clone();
actual.visit_mut_with(&mut DropParens);
if actual.eq_ignore_span(&normalized_expected)
|| drop_span(actual.clone()) == normalized_expected
{
return Some(());
}
if print(cm.clone(), &[actual], Some(&comments), false, false)
== print(
cm.clone(),
&[normalized_expected],
Some(&comments),
false,
false,
)
{
return Some(());
}
print(cm.clone(), &[expected], Some(&comments), false, false)
};
if output == expected {
return Some(());
}
None
})()
.is_some();
if identical {
let s = read_to_string(dir.join("output.terser.js"))
.expect("failed to read output.terser.js");
std::fs::write(dir.join("output.js"), s.as_bytes())
.expect("failed to update output.js");
}
}
if output == expected {
return Ok(());
}
eprintln!(
"---- {} -----\n{}",
Color::Green.paint("Expected"),
expected
);
println!("{}", input.display());
if let Ok(expected_stdout) = read_to_string(dir.join("expected.stdout")) {
eprintln!(
"---- {} -----\n{}",
Color::Green.paint("Expected stdout"),
expected_stdout
);
let actual = stdout_of(&output).expect("failed to execute the optimized code");
assert_eq!(
DebugUsingDisplay(&actual),
DebugUsingDisplay(&expected_stdout)
);
if expected.trim().is_empty() {
return Ok(());
}
}
let output_str = print(
cm,
&[drop_span(output_program)],
Some(&comments),
false,
false,
);
if env::var("UPDATE").map(|s| s == "1").unwrap_or(false) {
let _ = catch_unwind(|| {
NormalizedOutput::from(output_str.clone())
.compare_to_file(dir.join("output.js"))
.unwrap();
});
}
assert_eq!(DebugUsingDisplay(&output_str), DebugUsingDisplay(&expected));
Ok(())
})
.unwrap()
}
fn print<N: swc_ecma_codegen::Node>(
cm: Lrc<SourceMap>,
nodes: &[N],
comments: Option<&dyn Comments>,
minify: bool,
skip_semi: bool,
) -> String {
let mut buf = Vec::new();
{
let mut wr: Box<dyn WriteJs> = Box::new(JsWriter::new(cm.clone(), "\n", &mut buf, None));
if minify || skip_semi {
wr = Box::new(omit_trailing_semi(wr));
}
let mut emitter = Emitter {
cfg: swc_ecma_codegen::Config::default().with_minify(minify),
cm,
comments,
wr,
};
for n in nodes {
n.emit_with(&mut emitter).unwrap();
}
}
String::from_utf8(buf).unwrap()
}
#[testing::fixture("tests/full/**/input.js")]
fn full(input: PathBuf) {
let dir = input.parent().unwrap();
let config = find_config(dir);
eprintln!("---- {} -----\n{}", Color::Green.paint("Config"), config);
let comments = SingleThreadedComments::default();
testing::run_test2(false, |cm, handler| {
let output = run(
cm.clone(),
&handler,
&input,
&config,
Some(&comments),
Some(TestMangleOptions::Normal(MangleOptions {
top_level: Some(true),
..Default::default()
})),
false,
);
let output_module = match output {
Some(v) => v,
None => return Ok(()),
};
let output = print(cm, &[output_module], Some(&comments), true, true);
eprintln!("---- {} -----\n{}", Color::Green.paint("Output"), output);
println!("{}", input.display());
NormalizedOutput::from(output)
.compare_to_file(dir.join("output.js"))
.unwrap();
Ok(())
})
.unwrap();
unignore_fixture(&input);
}
struct DropParens;
impl VisitMut for DropParens {
fn visit_mut_expr(&mut self, e: &mut Expr) {
e.visit_mut_children_with(self);
if let Expr::Paren(p) = e {
*e = *p.expr.take();
}
}
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/eval.rs | Rust | #![deny(warnings)]
use swc_atoms::Atom;
use swc_common::{sync::Lrc, FileName, Mark, SourceMap};
use swc_ecma_ast::*;
use swc_ecma_codegen::{text_writer::JsWriter, Emitter};
use swc_ecma_minifier::{
eval::{EvalResult, Evaluator},
marks::Marks,
};
use swc_ecma_parser::{parse_file_as_expr, parse_file_as_module, EsSyntax, Syntax};
use swc_ecma_transforms_base::resolver;
use swc_ecma_visit::{noop_visit_mut_type, VisitMut, VisitMutWith};
use testing::{assert_eq, DebugUsingDisplay};
fn eval(module: &str, expr: &str) -> Option<String> {
testing::run_test2(false, |cm, _handler| {
let fm = cm.new_source_file(FileName::Anon.into(), module.to_string());
let marks = Marks::new();
let module_ast = parse_file_as_module(
&fm,
Default::default(),
EsVersion::latest(),
None,
&mut Vec::new(),
)
.unwrap();
let expr_ast = {
let fm = cm.new_source_file(FileName::Anon.into(), expr.to_string());
parse_file_as_expr(
&fm,
Default::default(),
EsVersion::latest(),
None,
&mut Vec::new(),
)
.unwrap()
};
let mut evaluator = Evaluator::new(module_ast, marks);
let res = evaluator.eval(&expr_ast);
match res {
Some(res) => match res {
EvalResult::Lit(l) => match l {
swc_ecma_ast::Lit::Str(v) => Ok(Some(v.value.to_string())),
swc_ecma_ast::Lit::Bool(v) => Ok(Some(v.value.to_string())),
swc_ecma_ast::Lit::Num(v) => Ok(Some(v.value.to_string())),
swc_ecma_ast::Lit::Null(_) => Ok(Some("null".into())),
_ => unreachable!(),
},
EvalResult::Undefined => Ok(Some("undefined".into())),
},
None => Ok(None),
}
})
.unwrap()
}
#[test]
fn simple() {
assert_eq!(eval("const foo = 4", "foo").unwrap(), "4");
}
#[test]
fn eval_lit() {
assert_eq!(eval("", "true").unwrap(), "true");
assert_eq!(eval("", "false").unwrap(), "false");
}
struct PartialInliner {
marks: Marks,
eval: Option<Evaluator>,
}
impl PartialInliner {
fn run_test<F>(src: &str, op: F)
where
F: FnOnce(Lrc<SourceMap>, Module, &mut PartialInliner),
{
testing::run_test2(false, |cm, _handler| {
let fm = cm.new_source_file(FileName::Anon.into(), src.to_string());
let marks = Marks::new();
let mut module = parse_file_as_module(
&fm,
Syntax::Es(EsSyntax {
jsx: true,
..Default::default()
}),
EsVersion::latest(),
None,
&mut Vec::new(),
)
.unwrap();
module.visit_mut_with(&mut resolver(Mark::new(), Mark::new(), false));
let mut inliner = PartialInliner {
marks,
eval: Default::default(),
};
op(cm, module, &mut inliner);
Ok(())
})
.unwrap();
}
fn expect(src: &str, expected: &str) {
PartialInliner::run_test(src, |cm, mut module, inliner| {
//
module.visit_mut_with(inliner);
let expected_module = {
let fm = cm.new_source_file(FileName::Anon.into(), expected.to_string());
parse_file_as_module(
&fm,
Syntax::Es(EsSyntax {
jsx: true,
..Default::default()
}),
EsVersion::latest(),
None,
&mut Vec::new(),
)
.unwrap()
};
let expected = {
let mut buf = Vec::new();
{
let mut emitter = Emitter {
cfg: Default::default(),
cm: cm.clone(),
comments: None,
wr: Box::new(JsWriter::new(cm.clone(), "\n", &mut buf, None)),
};
emitter.emit_module(&expected_module).unwrap();
}
String::from_utf8(buf).unwrap()
};
let actual = {
let mut buf = Vec::new();
{
let mut emitter = Emitter {
cfg: Default::default(),
cm: cm.clone(),
comments: None,
wr: Box::new(JsWriter::new(cm, "\n", &mut buf, None)),
};
emitter.emit_module(&module).unwrap();
}
String::from_utf8(buf).unwrap()
};
assert_eq!(DebugUsingDisplay(&expected), DebugUsingDisplay(&actual));
});
}
}
impl VisitMut for PartialInliner {
noop_visit_mut_type!(fail);
fn visit_mut_expr(&mut self, e: &mut Expr) {
e.visit_mut_children_with(self);
if let Some(evaluator) = self.eval.as_mut() {
if let Expr::TaggedTpl(tt) = e {
if let Expr::Ident(ref tag) = &*tt.tag {
if &*tag.sym == "css" {
let res = evaluator.eval_tpl(&tt.tpl);
let res = match res {
Some(v) => v,
None => return,
};
match res {
EvalResult::Lit(Lit::Str(s)) => {
let el = TplElement {
span: s.span,
tail: true,
// TODO possible bug for quotes
raw: Atom::new(&*s.value),
cooked: Some(Atom::new(&*s.value)),
};
tt.tpl = Box::new(Tpl {
span: el.span,
exprs: Default::default(),
quasis: vec![el],
});
}
_ => {
unreachable!()
}
}
}
}
}
}
}
fn visit_mut_module(&mut self, module: &mut Module) {
self.eval = Some(Evaluator::new(module.clone(), self.marks));
module.visit_mut_children_with(self);
}
}
#[test]
fn partial_1() {
PartialInliner::expect(
"
const color = 'red'
export const foo = css`
div {
color: ${color};
}
`
",
"
const color = 'red'
export const foo = css`
div {
color: red;
}
`
",
);
}
#[test]
fn partial_2() {
PartialInliner::expect(
"
export default css`
div {
font-size: 3em;
}
p {
color: ${props.color};
}
`
",
"
export default css`
div {
font-size: 3em;
}
p {
color: ${props.color};
}
`
",
);
}
#[test]
fn partial_3() {
PartialInliner::expect(
"
const darken = c => c
const color = 'red'
const otherColor = 'green'
const mediumScreen = '680px'
const animationDuration = '200ms'
const animationName = 'my-cool-animation'
const obj = { display: 'block' }
export const s1 = css`
p.${color} {
color: ${otherColor};
display: ${obj.display};
}
`;
",
"
const darken = c => c
const color = 'red'
const otherColor = 'green'
const mediumScreen = '680px'
const animationDuration = '200ms'
const animationName = 'my-cool-animation'
const obj = { display: 'block' }
export const s1 = css`
p.red {
color: green;
display: block;
}
`
",
);
}
#[test]
#[ignore]
fn partial_4() {
PartialInliner::expect(
"
const darken = c => c
const color = 'red'
const otherColor = 'green'
const mediumScreen = '680px'
const animationDuration = '200ms'
const animationName = 'my-cool-animation'
const obj = { display: 'block' }
export const s2 = css`
p.${color} {
color: ${darken(color)};
}
`;
",
"
const darken = c => c
const color = 'red'
const otherColor = 'green'
const mediumScreen = '680px'
const animationDuration = '200ms'
const animationName = 'my-cool-animation'
const obj = { display: 'block' }
export const s2 = css`
p.red {
color: 'red';
}
`
",
);
}
#[test]
#[ignore]
fn partial_5() {
PartialInliner::expect(
"
const darken = c => c
const color = 'red'
const otherColor = 'green'
const mediumScreen = '680px'
const animationDuration = '200ms'
const animationName = 'my-cool-animation'
const obj = { display: 'block' }
export const s3 = css`
p.${color} {
color: ${darken(color) + 2};
}
`;
",
"
const darken = c => c
const color = 'red'
const otherColor = 'green'
const mediumScreen = '680px'
const animationDuration = '200ms'
const animationName = 'my-cool-animation'
const obj = { display: 'block' }
export const s3 = css`
p.red {
color: 'red2';
}
`;
",
);
}
#[test]
fn partial_6() {
PartialInliner::expect(
"
const darken = c => c
const color = 'red'
const otherColor = 'green'
const mediumScreen = '680px'
const animationDuration = '200ms'
const animationName = 'my-cool-animation'
const obj = { display: 'block' }
export const s4 = css`
@media (min-width: ${mediumScreen}) {
p {
color: green;
}
p {
color: ${`red`};
}
}
p {
color: red;
}
`;
",
"
const darken = c => c
const color = 'red'
const otherColor = 'green'
const mediumScreen = '680px'
const animationDuration = '200ms'
const animationName = 'my-cool-animation'
const obj = { display: 'block' }
export const s4 = css`
@media (min-width: 680px) {
p {
color: green;
}
p {
color: red;
}
}
p {
color: red;
}
`;
",
);
}
#[test]
fn partial_7() {
PartialInliner::expect(
"
const darken = c => c
const color = 'red'
const otherColor = 'green'
const mediumScreen = '680px'
const animationDuration = '200ms'
const animationName = 'my-cool-animation'
const obj = { display: 'block' }
export default ({ display }) => (
css`
span {
display: ${display ? 'block' : 'none'};
}
`
)
",
"
const darken = c => c
const color = 'red'
const otherColor = 'green'
const mediumScreen = '680px'
const animationDuration = '200ms'
const animationName = 'my-cool-animation'
const obj = { display: 'block' }
export default ({ display }) => (
css`
span {
display: ${display ? 'block' : 'none'};
}
`
)
",
);
}
#[test]
fn partial_8() {
PartialInliner::expect(
"const darken = c => c
const color = 'red'
const otherColor = 'green'
const mediumScreen = '680px'
const animationDuration = '200ms'
const animationName = 'my-cool-animation'
const obj = { display: 'block' }
export default ({ display }) => (
css`
p.${color} {
color: ${otherColor};
display: ${obj.display};
}
`
)
",
"
const darken = c => c
const color = 'red'
const otherColor = 'green'
const mediumScreen = '680px'
const animationDuration = '200ms'
const animationName = 'my-cool-animation'
const obj = { display: 'block' }
export default ({ display }) => (
css`
p.red {
color: green;
display: block;
}
`
)
",
)
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/exec.rs | Rust | #![deny(warnings)]
extern crate swc_malloc;
use ansi_term::Color;
use anyhow::Error;
use serde::Deserialize;
use swc_common::{
comments::SingleThreadedComments,
errors::{Handler, HANDLER},
sync::Lrc,
FileName, Mark, SourceMap,
};
use swc_ecma_ast::Program;
use swc_ecma_codegen::{
text_writer::{omit_trailing_semi, JsWriter, WriteJs},
Emitter,
};
use swc_ecma_minifier::{
optimize,
option::{
terser::TerserCompressorOptions, CompressOptions, ExtraOptions, MangleOptions,
MinifyOptions,
},
};
use swc_ecma_parser::{parse_file_as_module, EsSyntax, Syntax};
use swc_ecma_testing::{exec_node_js, JsExecOptions};
use swc_ecma_transforms_base::{fixer::fixer, hygiene::hygiene, resolver};
use swc_ecma_visit::VisitMutWith;
use testing::DebugUsingDisplay;
use tracing::{info, span, Level};
#[derive(Debug, Clone, Deserialize)]
struct TestOptions {
#[serde(default)]
defaults: bool,
}
fn parse_compressor_config(cm: Lrc<SourceMap>, s: &str) -> (bool, CompressOptions) {
let opts: TestOptions =
serde_json::from_str(s).expect("failed to deserialize value into a compressor config");
let mut c: TerserCompressorOptions =
serde_json::from_str(s).expect("failed to deserialize value into a compressor config");
c.defaults = opts.defaults;
(c.module, c.into_config(cm))
}
fn stdout_of(code: &str) -> Result<String, Error> {
let stdout = exec_node_js(
code,
JsExecOptions {
cache: true,
module: false,
..Default::default()
},
)?;
info!("Stdout: {}", stdout);
Ok(stdout)
}
fn print<N: swc_ecma_codegen::Node>(
cm: Lrc<SourceMap>,
nodes: &[N],
minify: bool,
skip_semi: bool,
) -> String {
let mut buf = Vec::new();
{
let mut wr: Box<dyn WriteJs> = Box::new(JsWriter::new(cm.clone(), "\n", &mut buf, None));
if minify || skip_semi {
wr = Box::new(omit_trailing_semi(wr));
}
let mut emitter = Emitter {
cfg: swc_ecma_codegen::Config::default().with_minify(minify),
cm,
comments: None,
wr,
};
for n in nodes {
n.emit_with(&mut emitter).unwrap();
}
}
String::from_utf8(buf).unwrap()
}
fn run(
cm: Lrc<SourceMap>,
handler: &Handler,
input: &str,
config: Option<&str>,
mangle: Option<MangleOptions>,
) -> Option<Program> {
let _ = rayon::ThreadPoolBuilder::new()
.thread_name(|i| format!("rayon-{}", i + 1))
.build_global();
let compress_config = config.map(|config| parse_compressor_config(cm.clone(), config).1);
let fm = cm.new_source_file(FileName::Anon.into(), input.into());
let comments = SingleThreadedComments::default();
eprintln!("---- {} -----\n{}", Color::Green.paint("Input"), fm.src);
let unresolved_mark = Mark::new();
let top_level_mark = Mark::new();
let program = parse_file_as_module(
&fm,
Syntax::Es(EsSyntax {
jsx: true,
..Default::default()
}),
Default::default(),
Some(&comments),
&mut Vec::new(),
)
.map_err(|err| {
err.into_diagnostic(handler).emit();
})
.map(Program::Module)
.map(|module| module.apply(&mut resolver(unresolved_mark, top_level_mark, false)));
// Ignore parser errors.
//
// This is typically related to strict mode caused by module context.
let program = match program {
Ok(v) => v,
_ => return None,
};
let run_hygiene = mangle.is_none();
let mut output = optimize(
program,
cm,
Some(&comments),
None,
&MinifyOptions {
compress: compress_config,
mangle,
..Default::default()
},
&ExtraOptions {
unresolved_mark,
top_level_mark,
mangle_name_cache: None,
},
);
if run_hygiene {
output.visit_mut_with(&mut hygiene());
}
let output = output.apply(&mut fixer(None));
Some(output)
}
fn run_exec_test(input_src: &str, config: &str, skip_mangle: bool) {
eprintln!("---- {} -----\n{}", Color::Green.paint("Config"), config);
let expected_output = stdout_of(input_src).unwrap();
eprintln!(
"---- {} -----\n{}",
Color::Green.paint("Expected"),
expected_output
);
testing::run_test2(false, |cm, handler| {
HANDLER.set(&handler, || {
let _tracing = span!(Level::ERROR, "compress-only").entered();
let output = run(cm.clone(), &handler, input_src, Some(config), None);
let output = output.expect("Parsing in base test should not fail");
let output = print(cm, &[output], false, false);
eprintln!(
"---- {} -----\n{}",
Color::Green.paint("Optimized code"),
output
);
let actual_output = stdout_of(&output).expect("failed to execute the optimized code");
assert_ne!(actual_output, "");
assert_eq!(
DebugUsingDisplay(&actual_output),
DebugUsingDisplay(&expected_output)
);
Ok(())
})
})
.unwrap();
if !skip_mangle {
testing::run_test2(false, |cm, handler| {
let _tracing = span!(Level::ERROR, "with-mangle").entered();
let output = run(
cm.clone(),
&handler,
input_src,
None,
Some(MangleOptions {
keep_fn_names: true,
top_level: Some(true),
..Default::default()
}),
);
let output = output.expect("Parsing in base test should not fail");
let output = print(cm, &[&output], true, false);
eprintln!(
"---- {} -----\n{}",
Color::Green.paint("Optimized code"),
output
);
let actual_output = stdout_of(&output).expect("failed to execute the optimized code");
assert_ne!(actual_output, "");
assert_eq!(
DebugUsingDisplay(&actual_output),
DebugUsingDisplay(&expected_output)
);
Ok(())
})
.unwrap();
}
}
fn run_default_exec_test(input_src: &str) {
let config = r#"{
"defaults": true,
"toplevel": true
}"#;
run_exec_test(input_src, config, false);
}
#[test]
fn next_feedback_1_capture_1() {
let src = r###"
const arr = [];
const fns = [];
var _loop = function (i) {
fns.push(() => {
arr.push(i);
})
}
for (var i = 0; i < 10; i++) _loop(i);
fns.forEach(fn => fn());
console.log(arr);"###;
let config = r#"{
"defaults": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn conditionals_reduce_6() {
let src = r#"function x() {
}
function y() {
return "foo";
}
console.log((y() || false) && x());"#;
let config = r#"{
"booleans": true,
"conditionals": true,
"evaluate": true,
"side_effects": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn conditionals_reduce_1() {
let src = r#"function x() {
}
function y() {
return "foo";
}
console.log(x() && true && y());"#;
let config = r#"{
"booleans": true,
"conditionals": true,
"evaluate": true,
"side_effects": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn conditionals_reduce_4() {
let src = r#"function x() {
}
function y() {
return "foo";
}
console.log(y() || false || x());"#;
let config = r#"{
"booleans": true,
"conditionals": true,
"evaluate": true,
"side_effects": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn conditionals_reduce_3() {
let src = r#"function x() {
}
function y() {
return "foo";
}
console.log(x() || false || y());"#;
let config = r#"{
"booleans": true,
"conditionals": true,
"evaluate": true,
"side_effects": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn conditionals_reduce_2() {
let src = r#"function x() {
}
function y() {
return "foo";
}
console.log(y() && true && x());"#;
let config = r#"{
"booleans": true,
"conditionals": true,
"evaluate": true,
"side_effects": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn conditionals_reduce_5() {
let src = r#"function x() {
}
function y() {
return "foo";
}
console.log((x() || false) && y());"#;
let config = r#"{
"booleans": true,
"conditionals": true,
"evaluate": true,
"side_effects": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn vercel_001() {
let src = r#"function _interop_require_default(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _class_call_check(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possible_constructor_return(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function ItemsList() {
var _ref;
var _temp, _this, _ret;
_class_call_check(this, ItemsList);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possible_constructor_return(this, (_ref = ItemsList.__proto__ || Object.getPrototypeOf(ItemsList)).call.apply(_ref, [this].concat(args))), _this), _this.storeHighlightedItemReference = function (highlightedItem) {
_this.props.onHighlightedItemChange(highlightedItem === null ? null : highlightedItem.item);
}, _temp), _possible_constructor_return(_this, _ret);
}
new ItemsList();
console.log('PASS')"#;
let config = r#"{
"defaults": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn vercel_002() {
let src = r#"function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _class_call_check(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _possible_constructor_return(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && ("object" == typeof call || "function" == typeof call) ? call : self;
}
function _inherits(subClass, superClass) {
if ("function" != typeof superClass && null !== superClass) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
function ItemsList() {
_class_call_check(this, ItemsList);
for (var _ref, _temp, _this, _ret, _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possible_constructor_return(this, (_ref = ItemsList.__proto__ || Object.getPrototypeOf(ItemsList)).call.apply(_ref, [
this
].concat(args))), _this), _this.storeHighlightedItemReference = function (highlightedItem) {
_this.props.onHighlightedItemChange(null === highlightedItem ? null : highlightedItem.item);
}, _temp), _possible_constructor_return(_this, _ret);
}
new ItemsList();
console.log("PASS");"#;
let config = r#"{
"defaults": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn regexp_1() {
let src = r#"
function compile(attributePattern, flags) {
return new RegExp(`(?:^|;)\\s*${attributePattern}\\s*=\\s*` + `(` + `[^";\\s][^;\\s]*` + `|` + `"(?:[^"\\\\]|\\\\"?)+"?` + `)`, flags);
}
console.log(compile("foo", "g"));
console.log(compile("bar", "g"));
console.log(compile("baz", "g"));"#;
let config = r#"{
"defaults": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn update_object_1() {
let src = r###"console.log(function () {
console.log({
q: {
p: 8
}
}.q.p++);
return 8;
}());"###;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn update_object_3() {
let src = r###"console.log(function () {
var o = {
p: 7
};
console.log([
o
][0].p++);
return o.p;
}());"###;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn update_object_2() {
let src = r###"function inc() {
this.p++;
}
console.log(function () {
inc.call({
p: 6
});
console.log(6);
return 6;
}());"###;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn iife_reassign_1() {
let src = r###"console.log(function c() {
c = 6;
return c;
}())"###;
let config = r#"{
"evaluate": true,
"inline": true,
"passes": 3,
"reduce_vars": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn emotion_react_1() {
let src = r#"
/* harmony default export */
var emotion_memoize_browser_esm = (memoize);
var hyphenateRegex = /[A-Z]|^ms/g;
var animationRegex = /_EMO_([^_]+?)_([^]*?)_EMO_/g;
var unitlessKeys = {
animationIterationCount: 1,
borderImageOutset: 1,
borderImageSlice: 1,
borderImageWidth: 1,
boxFlex: 1,
boxFlexGroup: 1,
boxOrdinalGroup: 1,
columnCount: 1,
columns: 1,
flex: 1,
flexGrow: 1,
flexPositive: 1,
flexShrink: 1,
flexNegative: 1,
flexOrder: 1,
gridRow: 1,
gridRowEnd: 1,
gridRowSpan: 1,
gridRowStart: 1,
gridColumn: 1,
gridColumnEnd: 1,
gridColumnSpan: 1,
gridColumnStart: 1,
msGridRow: 1,
msGridRowSpan: 1,
msGridColumn: 1,
msGridColumnSpan: 1,
fontWeight: 1,
lineHeight: 1,
opacity: 1,
order: 1,
orphans: 1,
tabSize: 1,
widows: 1,
zIndex: 1,
zoom: 1,
WebkitLineClamp: 1,
// SVG-related properties
fillOpacity: 1,
floodOpacity: 1,
stopOpacity: 1,
strokeDasharray: 1,
strokeDashoffset: 1,
strokeMiterlimit: 1,
strokeOpacity: 1,
strokeWidth: 1
};
var unitless_browser_esm = (unitlessKeys);
var isCustomProperty = function isCustomProperty(property) {
return property.charCodeAt(1) === 45;
};
var labelPattern = /label:\s*([^\s;\n{]+)\s*(;|$)/g;
var cursor;
var hash_browser_esm = (murmur2);
function handleInterpolation(mergedProps, registered, interpolation) {
if (interpolation == null) {
return '';
}
if (interpolation.__emotion_styles !== undefined) {
if (false) { }
return interpolation;
}
switch (typeof interpolation) {
case 'boolean': {
return '';
}
case 'object': {
if (interpolation.anim === 1) {
cursor = {
name: interpolation.name,
styles: interpolation.styles,
next: cursor
};
return interpolation.name;
}
if (interpolation.styles !== undefined) {
var next = interpolation.next;
if (next !== undefined) {
// not the most efficient thing ever but this is a pretty rare case
// and there will be very few iterations of this generally
while (next !== undefined) {
cursor = {
name: next.name,
styles: next.styles,
next: cursor
};
next = next.next;
}
}
var styles = interpolation.styles + ";";
if (false) { }
return styles;
}
return createStringFromObject(mergedProps, registered, interpolation);
}
case 'function': {
if (mergedProps !== undefined) {
var previousCursor = cursor;
var result = interpolation(mergedProps);
cursor = previousCursor;
return handleInterpolation(mergedProps, registered, result);
} else if (false) { }
break;
}
case 'string':
if (false) {
var replaced, matched;
}
break;
} // finalize string values (regular strings and functions interpolated into css calls)
if (registered == null) {
return interpolation;
}
var cached = registered[interpolation];
return cached !== undefined ? cached : interpolation;
}
function serializeStyles(args, registered, mergedProps) {
if (args.length === 1 && typeof args[0] === 'object' && args[0] !== null && args[0].styles !== undefined) {
return args[0];
}
var stringMode = true;
var styles = '';
cursor = undefined;
var strings = args[0];
if (strings == null || strings.raw === undefined) {
stringMode = false;
console.log('stringMode = false')
styles += handleInterpolation(mergedProps, registered, strings);
} else {
if (false) { }
styles += strings[0];
} // we start at 1 since we've already handled the first arg
console.log(`Styles: ${styles}`)
for (var i = 1; i < args.length; i++) {
styles += handleInterpolation(mergedProps, registered, args[i]);
if (stringMode) {
if (false) { }
styles += strings[i];
}
}
console.log(`Styles: ${styles}`)
var sourceMap;
if (false) { } // using a global regex with .exec is stateful so lastIndex has to be reset each time
labelPattern.lastIndex = 0;
var identifierName = '';
var match; // https://esbench.com/bench/5b809c2cf2949800a0f61fb5
while ((match = labelPattern.exec(styles)) !== null) {
identifierName += '-' + // $FlowFixMe we know it's not null
match[1];
}
console.log(`styles = ${styles}`)
console.log(`identifierName = ${identifierName}`)
var name = hash_browser_esm(styles) + identifierName;
if (false) { }
return {
name: name,
styles: styles,
next: cursor
};
}
function createStringFromObject(mergedProps, registered, obj) {
var string = '';
if (Array.isArray(obj)) {
for (var i = 0; i < obj.length; i++) {
string += handleInterpolation(mergedProps, registered, obj[i]) + ";";
}
} else {
for (var _key in obj) {
var value = obj[_key];
if (typeof value !== 'object') {
if (registered != null && registered[value] !== undefined) {
string += _key + "{" + registered[value] + "}";
} else if (isProcessableValue(value)) {
string += processStyleName(_key) + ":" + processStyleValue(_key, value) + ";";
}
} else {
if (_key === 'NO_COMPONENT_SELECTOR' && "production" !== 'production') { }
if (Array.isArray(value) && typeof value[0] === 'string' && (registered == null || registered[value[0]] === undefined)) {
for (var _i = 0; _i < value.length; _i++) {
if (isProcessableValue(value[_i])) {
string += processStyleName(_key) + ":" + processStyleValue(_key, value[_i]) + ";";
}
}
} else {
var interpolated = handleInterpolation(mergedProps, registered, value);
switch (_key) {
case 'animation':
case 'animationName': {
string += processStyleName(_key) + ":" + interpolated + ";";
break;
}
default: {
if (false) { }
string += _key + "{" + interpolated + "}";
}
}
}
}
}
}
return string;
}
function murmur2(str) {
// 'm' and 'r' are mixing constants generated offline.
// They're not really 'magic', they just happen to work well.
// const m = 0x5bd1e995;
// const r = 24;
// Initialize the hash
var h = 0; // Mix 4 bytes at a time into the hash
var k,
i = 0,
len = str.length;
for (; len >= 4; ++i, len -= 4) {
k = str.charCodeAt(i) & 0xff | (str.charCodeAt(++i) & 0xff) << 8 | (str.charCodeAt(++i) & 0xff) << 16 | (str.charCodeAt(++i) & 0xff) << 24;
console.log(`K1: ${k}`);
k =
/* Math.imul(k, m): */
(k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16);
console.log(`K2: ${k}`);
k ^=
/* k >>> r: */
k >>> 24;
console.log(`K3: ${k}`);
h =
/* Math.imul(k, m): */
(k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16) ^
/* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
console.log(`H: ${h}`);
} // Handle the last few bytes of the input array
switch (len) {
case 3:
h ^= (str.charCodeAt(i + 2) & 0xff) << 16;
case 2:
h ^= (str.charCodeAt(i + 1) & 0xff) << 8;
case 1:
h ^= str.charCodeAt(i) & 0xff;
h =
/* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
} // Do a few final mixes of the hash to ensure the last few
// bytes are well-incorporated.
h ^= h >>> 13;
h =
/* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
return ((h ^ h >>> 15) >>> 0).toString(36);
}
function isProcessableValue(value) {
return value != null && typeof value !== 'boolean';
}
var processStyleName = /* #__PURE__ */ emotion_memoize_browser_esm(function (styleName) {
return isCustomProperty(styleName) ? styleName : styleName.replace(hyphenateRegex, '-$&').toLowerCase();
});
var processStyleValue = function processStyleValue(key, value) {
switch (key) {
case 'animation':
case 'animationName': {
if (typeof value === 'string') {
return value.replace(animationRegex, function (match, p1, p2) {
cursor = {
name: p1,
styles: p2,
next: cursor
};
return p1;
});
}
}
}
if (unitless_browser_esm[key] !== 1 && !isCustomProperty(key) && typeof value === 'number' && value !== 0) {
return value + 'px';
}
return value;
};
function memoize(fn) {
var cache = Object.create(null);
return function (arg) {
if (cache[arg] === undefined) cache[arg] = fn(arg);
return cache[arg];
};
}
console.log(serializeStyles(`:root {
--background-color: rebeccapurple;
}`));
console.log(serializeStyles(`:root {
--background-color: rebeccapurple;
}`));
console.log(serializeStyles(`:root {
--background-color: rebeccapurple;
}`));
console.log(serializeStyles(`:root {
--background-color: rebeccapurple;
}`));
console.log(serializeStyles(`:root {
--background-color: rebeccapurple;
}`));
console.log(serializeStyles(`:root {
--background-color: rebeccapurple;
}`));"#;
let config = r#"{
"defaults": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn simple_1() {
let src = r###"console.log('PASS')"###;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_1588_unsafe_undefined() {
let src = r###"var a, c;
console.log(
(function (undefined) {
return function () {
if (a) return b;
if (c) return d;
};
})()()
);"###;
let config = r#"{
"conditionals": true,
"if_return": true,
"unsafe_undefined": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_1588_safe_undefined() {
let src = r###"var a, c;
console.log(
(function (undefined) {
return function () {
if (a) return b;
if (c) return d;
};
})(1)()
);"###;
let config = r#"{
"conditionals": true,
"if_return": true,
"unsafe": false
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_drop_toplevel_retain() {
let src = r###"var a,
b = 1,
c = g;
function f(d) {
return function () {
c = 2;
};
}
a = 2;
function g() {}
function h() {}
console.log((b = 3));"###;
let config = r#"{
"top_retain": "f,a,o",
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_issue_t161_top_retain_15() {
let src = r###"class Alpha {
num() {
return x;
}
}
class Beta {
num() {
return y;
}
}
class Carrot {
num() {
return z;
}
}
function f() {
return x;
}
const g = () => y;
const h = () => z;
let x = 2,
y = 3,
z = 4;
console.log(
x,
y,
z,
x * y,
x * z,
y * z,
f(),
g(),
h(),
new Alpha().num(),
new Beta().num(),
new Carrot().num()
);"###;
let config = r#"{
"defaults": true,
"inline": 3,
"passes": 2,
"top_retain": "Alpha,z"
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_issue_t161_top_retain_4() {
let src = r###"function f() {
return 2;
}
function g() {
return 3;
}
console.log(f(), f(), g(), g());"###;
let config = r#"{
"defaults": true,
"inline": 3,
"passes": 3,
"top_retain": "f"
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_issue_t161_top_retain_3() {
let src = r###"function f() {
return 2;
}
function g() {
return 3;
}
console.log(f(), g());"###;
let config = r#"{
"defaults": true,
"inline": 3,
"passes": 3,
"top_retain": "f"
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_double_assign_1() {
let src = r###"function f1() {
var a = {};
var a = [];
return a;
}
function f2() {
var a = {};
a = [];
return a;
}
function f3() {
a = {};
var a = [];
return a;
}
function f4(a) {
a = {};
a = [];
return a;
}
function f5(a) {
var a = {};
a = [];
return a;
}
function f6(a) {
a = {};
var a = [];
return a;
}
console.log(f1(), f2(), f3(), f4(), f5(), f6());"###;
let config = r#"{
"passes": 2,
"reduce_vars": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_issue_2846() {
let src = r###"function f(a, b) {
var a = 0;
b && b(a);
return a++;
}
var c = f();
console.log(c);"###;
let config = r#"{
"collapse_vars": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_issue_2660_2() {
let src = r###"var a = 1;
function f(b) {
b && f();
--a, a.toString();
}
f();
console.log(a);"###;
let config = r#"{
"collapse_vars": true,
"reduce_vars": true,
"sequences": true,
"side_effects": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_drop_toplevel_retain_array() {
let src = r###"var a,
b = 1,
c = g;
function f(d) {
return function () {
c = 2;
};
}
a = 2;
function g() {}
function h() {}
console.log((b = 3));"###;
let config = r#"{
"top_retain": ["f", "a", "o"],
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_chained_3() {
let src = r###"console.log(
(function (a, b) {
var c = a,
c = b;
b++;
return c;
})(1, 2)
);"###;
let config = r#"{
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_issue_2665() {
let src = r#"var a = 1;
function g() {
a-- && g();
}
typeof h == "function" && h();
function h() {
typeof g == "function" && g();
}
console.log(a);"#;
let config = r#"{
"evaluate": true,
"inline": true,
"keep_fargs": false,
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"toplevel": true,
"typeofs": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_issue_2516_2() {
let src = r#"function foo() {
function qux(x) {
bar.call(null, x);
}
function bar(x) {
var FOUR = 4;
var trouble = x || never_called();
var value = (FOUR - 1) * trouble;
console.log(value == 6 ? "PASS" : value);
}
Baz = qux;
}
var Baz;
foo();
Baz(2);"#;
let config = r#"{
"collapse_vars": true,
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_drop_toplevel_funcs_retain() {
let src = r###"var a,
b = 1,
c = g;
function f(d) {
return function () {
c = 2;
};
}
a = 2;
function g() {}
function h() {}
console.log((b = 3));"###;
let config = r#"{
"top_retain": "f,a,o",
"toplevel": "funcs",
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_issue_1709() {
let src = r###"console.log(
(function x() {
var x = 1;
return x;
})(),
(function y() {
const y = 2;
return y;
})(),
(function z() {
function z() {}
return z;
})()
);"###;
let config = r#"{
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_drop_var() {
let src = r###"var a;
console.log(a, b);
var a = 1,
b = 2;
console.log(a, b);
var a = 3;
console.log(a, b);"###;
let config = r#"{
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_drop_toplevel_funcs() {
let src = r###"var a,
b = 1,
c = g;
function f(d) {
return function () {
c = 2;
};
}
a = 2;
function g() {}
function h() {}
console.log((b = 3));"###;
let config = r#"{
"toplevel": "funcs",
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_delete_assign_1() {
let src = r###"var a;
console.log(delete (a = undefined));
console.log(delete (a = void 0));
console.log(delete (a = Infinity));
console.log(delete (a = 1 / 0));
console.log(delete (a = NaN));
console.log(delete (a = 0 / 0));"###;
let config = r#"{
"booleans": true,
"side_effects": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_issue_2226_3() {
let src = r###"console.log(
(function (a, b) {
a += b;
return a;
})(1, 2)
);"###;
let config = r#"{
"collapse_vars": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
#[ignore]
fn terser_drop_unused_issue_3146_3() {
let src = r#"var g = "PASS";
(function (f) {
var g = "FAIL";
f("console.log(g)", g[g]);
})(function (a) {
eval(a);
});"#;
let config = r#"{
"collapse_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
#[ignore]
fn terser_drop_unused_issue_3146_4() {
let src = r#"var g = "PASS";
(function (f) {
var g = "FAIL";
f("console.log(g)", g[g]);
})(function (a) {
eval(a);
});"#;
let config = r#"{
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_drop_toplevel_vars_retain() {
let src = r###"var a,
b = 1,
c = g;
function f(d) {
return function () {
c = 2;
};
}
a = 2;
function g() {}
function h() {}
console.log((b = 3));"###;
let config = r#"{
"top_retain": "f,a,o",
"toplevel": "vars",
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_issue_2226_2() {
let src = r###"console.log(
(function (a, b) {
a += b;
return a;
})(1, 2)
);"###;
let config = r#"{
"collapse_vars": true,
"sequences": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_drop_fargs() {
let src = r###"function f(a) {
var b = a;
}
console.log(f())"###;
let config = r#"{
"keep_fargs": false,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_issue_2136_3() {
let src = r###"function f(x) {
console.log(x);
}
!(function (a, ...b) {
f(b[0]);
})(1, 2, 3);"###;
let config = r#"{
"collapse_vars": true,
"evaluate": true,
"inline": true,
"passes": 3,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"toplevel": true,
"unsafe": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_issue_2660_1() {
let src = r###"var a = 2;
function f(b) {
return (b && f()) || a--;
}
f(1);
console.log(a);"###;
let config = r#"{
"reduce_vars": true,
"side_effects": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_double_assign_2() {
let src = r###"for (var i = 0; i < 2; i++) (a = void 0), (a = {}), console.log(a);
var a;"###;
let config = r#"{
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_issue_2136_2() {
let src = r###"function f(x) {
console.log(x);
}
!(function (a, ...b) {
f(b[0]);
})(1, 2, 3);"###;
let config = r#"{
"collapse_vars": true,
"inline": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_issue_t183() {
let src = r#"function foo(val) {
function bar(x) {
if (x) return x;
bar(x - 1);
}
return bar(val);
}
console.log(foo("PASS"));"#;
let config = r#"{
"defaults": true,
"top_retain": []
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_drop_toplevel_vars() {
let src = r###"var a,
b = 1,
c = g;
function f(d) {
return function () {
c = 2;
};
}
a = 2;
function g() {}
function h() {}
console.log((b = 3));"###;
let config = r#"{
"toplevel": "vars",
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_issue_2516_1() {
let src = r#"function foo() {
function qux(x) {
bar.call(null, x);
}
function bar(x) {
var FOUR = 4;
var trouble = x || never_called();
var value = (FOUR - 1) * trouble;
console.log(value == 6 ? "PASS" : value);
}
Baz = qux;
}
var Baz;
foo();
Baz(2);"#;
let config = r#"{
"collapse_vars": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_defun_lambda_same_name() {
let src = r###"function f(n) {
return n ? n * f(n - 1) : 1;
}
console.log(
(function f(n) {
return n ? n * f(n - 1) : 1;
})(5)
);"###;
let config = r#"{
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_drop_toplevel_vars_fargs() {
let src = r###"var a,
b = 1,
c = g;
function f(d) {
return function () {
c = 2;
};
}
a = 2;
function g() {}
function h() {}
console.log((b = 3));"###;
let config = r#"{
"keep_fargs": false,
"toplevel": "vars",
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_issue_1968() {
let src = r###"function f(c) {
var a;
if (c) {
let b;
return (a = 2) + (b = 3);
}
}
console.log(f(1));"###;
let config = r#"{
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_issue_1715_4() {
let src = r###"var a = 1;
!(function a() {
a++;
try {
x();
} catch (a) {
var a;
}
})();
console.log(a);"###;
let config = r#"{
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_drop_assign() {
let src = r###"function f1() {
var a;
a = 1;
}
function f2() {
var a = 1;
a = 2;
}
function f3(a) {
a = 1;
}
function f4() {
var a;
return (a = 1);
}
function f5() {
var a;
return function () {
a = 1;
};
}
console.log(f1())
console.log(f2())
console.log(f3())
console.log(f4())
console.log(f5())"###;
let config = r#"{
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_issue_3146_1() {
let src = r#"(function (f) {
f("g()");
})(function (a) {
eval(a);
function g(b) {
if (!b) b = "PASS";
console.log(b);
}
});"#;
let config = r#"{
"collapse_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_delete_assign_2() {
let src = r###"var a;
console.log(delete (a = undefined));
console.log(delete (a = void 0));
console.log(delete (a = Infinity));
console.log(delete (a = 1 / 0));
console.log(delete (a = NaN));
console.log(delete (a = 0 / 0));"###;
let config = r#"{
"booleans": true,
"keep_infinity": true,
"side_effects": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_drop_unused_drop_toplevel_all_retain() {
let src = r###"var a,
b = 1,
c = g;
function f(d) {
return function () {
c = 2;
};
}
a = 2;
function g() {}
function h() {}
console.log((b = 3));"###;
let config = r#"{
"top_retain": "f,a,o",
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_comparing_issue_2857_6() {
let src = r###"function f(a) {
if ({}.b === undefined || {}.b === null)
return a.b !== undefined && a.b !== null;
}
console.log(
f({
a: [null],
get b() {
return this.a.shift();
},
})
);"###;
let config = r#"{
"comparisons": true,
"pure_getters": "strict",
"reduce_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_pure_getters_impure_getter_2() {
let src = r###"({
get a() {
console.log(1);
},
b: 1,
}.a);
({
get a() {
console.log(1);
},
b: 1,
}.b);"###;
let config = r#"{
"pure_getters": true,
"side_effects": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_pure_getters_issue_2838() {
let src = r#"function f(a, b) {
(a || b).c = "PASS";
(function () {
return f(a, b);
}.prototype.foo = "bar");
}
var o = {};
f(null, o);
console.log(o.c);"#;
let config = r#"{
"pure_getters": true,
"side_effects": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_pure_getters_issue_2938_4() {
let src = r#"var Parser = function Parser() {};
var p = Parser.prototype;
var unused = p.x;
p.initialContext = function initialContext() {
p.y;
console.log("PASS");
};
p.braceIsBlock = function () {};
new Parser().initialContext();"#;
let config = r#"{
"pure_getters": true,
"side_effects": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_pure_getters_set_mutable_1() {
let src = r#"!(function a() {
a.foo += "";
if (a.foo) console.log("PASS");
else console.log("FAIL");
})();"#;
let config = r#"{
"collapse_vars": true,
"evaluate": true,
"pure_getters": "strict",
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_pure_getters_issue_2938_3() {
let src = r#"function f(a) {
var unused = a.a;
a.b = "PASS";
a.c;
}
var o = {};
o.d;
f(o);
console.log(o.b);"#;
let config = r#"{
"pure_getters": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_pure_getters_set_immutable_6() {
let src = r#"var a = 1;
a.foo += "";
if (a.foo) console.log("FAIL");
else console.log("PASS");"#;
let config = r#"{
"collapse_vars": true,
"conditionals": true,
"evaluate": true,
"pure_getters": "strict",
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_pure_getters_set_immutable_1() {
let src = r#"var a = 1;
a.foo += "";
if (a.foo) console.log("FAIL");
else console.log("PASS");"#;
let config = r#"{
"collapse_vars": true,
"evaluate": true,
"pure_getters": "strict",
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_pure_getters_set_mutable_2() {
let src = r#"!(function a() {
a.foo += "";
if (a.foo) console.log("PASS");
else console.log("FAIL");
})();"#;
let config = r#"{
"collapse_vars": true,
"conditionals": true,
"pure_getters": "strict",
"reduce_funcs": true,
"reduce_vars": true,
"sequences": true,
"side_effects": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_dead_code_issue_2860_1() {
let src = r###"console.log(
(function (a) {
return (a ^= 1);
})()
);"###;
let config = r#"{
"dead_code": true,
"evaluate": true,
"reduce_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_dead_code_global_fns() {
let src = r###"Boolean(1, 2);
decodeURI(1, 2);
decodeURIComponent(1, 2);
Date(1, 2);
encodeURI(1, 2);
encodeURIComponent(1, 2);
Error(1, 2);
escape(1, 2);
EvalError(1, 2);
isFinite(1, 2);
isNaN(1, 2);
Number(1, 2);
Object(1, 2);
parseFloat(1, 2);
parseInt(1, 2);
RangeError(1, 2);
ReferenceError(1, 2);
String(1, 2);
SyntaxError(1, 2);
TypeError(1, 2);
unescape(1, 2);
URIError(1, 2);
try {
Function(1, 2);
} catch (e) {
console.log(e.name);
}
try {
RegExp(1, 2);
} catch (e) {
console.log(e.name);
}
try {
Array(NaN);
} catch (e) {
console.log(e.name);
}"###;
let config = r#"{
"side_effects": true,
"unsafe": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_block_scope_issue_334() {
let src = r#"(function (A) {
(function () {
doPrint();
})();
function doPrint() {
print(A);
}
})("Hello World!");
function print(A) {
if (!A.x) {
console.log(A);
}
}"#;
let config = r#"{
"defaults": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_hoist_props_issue_3021() {
let src = r###"var a = 1,
b = 2;
(function () {
b = a;
if (a++ + b--) return 1;
return;
var b = {};
})();
console.log(a, b);"###;
let config = r#"{
"hoist_props": true,
"reduce_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
#[ignore = "Function (anonymous)"]
fn terser_hoist_props_contains_this_2() {
let src = r###"var o = {
u: function () {
return this === this;
},
p: 1,
};
console.log(o.p, o.p, o.u);"###;
let config = r#"{
"evaluate": true,
"hoist_props": true,
"inline": true,
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
#[ignore]
fn terser_hoist_props_issue_851_hoist_to_conflicting_name() {
let src = r#"const BBB = { CCC: "PASS" };
if (id(true)) {
const BBB_CCC = BBB.CCC;
console.log(BBB_CCC);
}"#;
let config = r#"{
"hoist_props": true,
"reduce_vars": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_hoist_props_name_collision_1() {
let src = r#"var obj_foo = 1;
var obj_bar = 2;
function f() {
var obj = { foo: 3, bar: 4, "b-r": 5, "b+r": 6, "b!r": 7 };
console.log(obj_foo, obj.foo, obj.bar, obj["b-r"], obj["b+r"], obj["b!r"]);
}
f();"#;
let config = r#"{
"hoist_props": true,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_hoist_props_new_this() {
let src = r###"var o = {
a: 1,
b: 2,
f: function (a) {
this.b = a;
},
};
console.log(new o.f(o.a).b, o.b);"###;
let config = r#"{
"evaluate": true,
"hoist_props": true,
"inline": true,
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_hoist_props_toplevel_let() {
let src = r###"let a = { b: 1, c: 2 };
console.log(a.b + a.c);"###;
let config = r#"{
"hoist_props": true,
"reduce_vars": true,
"toplevel": false
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_hoist_props_undefined_key() {
let src = r###"var a,
o = {};
o[a] = 1;
o.b = 2;
console.log(o[a] + o.b);"###;
let config = r#"{
"evaluate": true,
"hoist_props": true,
"join_vars": true,
"passes": 4,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_hoist_props_direct_access_1() {
let src = r###"var a = 0;
var obj = { a: 1, b: 2 };
for (var k in obj) a++;
console.log(a, obj.a);"###;
let config = r#"{
"hoist_props": true,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_hoist_props_issue_2473_3() {
let src = r###"var o = { a: 1, b: 2 };
console.log(o.a, o.b);"###;
let config = r#"{
"hoist_props": true,
"reduce_vars": true,
"top_retain": "o",
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_hoist_props_issue_2473_4() {
let src = r###"(function () {
var o = { a: 1, b: 2 };
console.log(o.a, o.b);
})();"###;
let config = r#"{
"hoist_props": true,
"reduce_vars": true,
"top_retain": "o",
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_hoist_props_toplevel_const() {
let src = r###"const a = { b: 1, c: 2 };
console.log(a.b + a.c);"###;
let config = r#"{
"hoist_props": true,
"reduce_vars": true,
"toplevel": false
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_hoist_props_issue_2377_3() {
let src = r###"var obj = {
foo: 1,
bar: 2,
square: function (x) {
return x * x;
},
cube: function (x) {
return x * x * x;
},
};
console.log(obj.foo, obj.cube(3));"###;
let config = r#"{
"evaluate": true,
"hoist_props": true,
"inline": true,
"passes": 4,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_hoist_props_issue_2508_2() {
let src = r###"var o = {
a: { b: 2 },
f: function (x) {
console.log(x);
},
};
o.f(o.a);"###;
let config = r#"{
"collapse_vars": true,
"hoist_props": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
#[ignore = "Function anonymous"]
fn terser_hoist_props_issue_2508_5() {
let src = r###"var o = {
f: function (x) {
console.log(x);
},
};
o.f(o.f);"###;
let config = r#"{
"collapse_vars": true,
"hoist_props": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_hoist_props_issue_2377_2() {
let src = r###"var obj = {
foo: 1,
bar: 2,
square: function (x) {
return x * x;
},
cube: function (x) {
return x * x * x;
},
};
console.log(obj.foo, obj.cube(3));"###;
let config = r#"{
"evaluate": true,
"hoist_props": true,
"inline": true,
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_hoist_props_toplevel_var() {
let src = r###"var a = { b: 1, c: 2 };
console.log(a.b + a.c);"###;
let config = r#"{
"hoist_props": true,
"reduce_vars": true,
"toplevel": false
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_hoist_props_issue_3046() {
let src = r###"console.log(
(function (a) {
do {
var b = { c: a++ };
} while (b.c && a);
return a;
})(0)
);"###;
let config = r#"{
"hoist_props": true,
"reduce_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_hoist_props_name_collision_3() {
let src = r#"var o = {
p: 1,
"+": function (x) {
return x;
},
"-": function (x) {
return x + 1;
},
},
o__$0 = 2,
o__$1 = 3;
console.log(o.p === o.p, o["+"](4), o["-"](5));"#;
let config = r#"{
"hoist_props": true,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_hoist_props_hoist_class_with_new() {
let src = r###"var o = {
p: class Foo {
constructor(value) {
this.value = value * 10;
}
},
x: 1,
y: 2,
};
console.log(o.p.name, o.p === o.p, new o.p(o.x).value, new o.p(o.y).value);"###;
let config = r#"{
"comparisons": true,
"evaluate": true,
"hoist_props": true,
"inline": true,
"keep_classnames": true,
"keep_fnames": true,
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, true);
}
#[test]
fn terser_hoist_props_hoist_function_with_call() {
let src = r###"var o = {
p: function Foo(value) {
return 10 * value;
},
x: 1,
y: 2,
};
console.log(o.p.name, o.p === o.p, o.p(o.x), o.p(o.y));"###;
let config = r#"{
"comparisons": true,
"evaluate": true,
"hoist_props": true,
"inline": true,
"keep_fnames": true,
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_hoist_props_name_collision_2() {
let src = r#"var o = {
p: 1,
"+": function (x) {
return x;
},
"-": function (x) {
return x + 1;
},
},
o__$0 = 2,
o__$1 = 3;
console.log(o.p === o.p, o["+"](4), o["-"](5), o__$0, o__$1);"#;
let config = r#"{
"hoist_props": true,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_hoist_props_direct_access_2() {
let src = r#"var o = { a: 1 };
var f = function (k) {
if (o[k]) return "PASS";
};
console.log(f("a"));"#;
let config = r#"{
"hoist_props": true,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_hoist_props_hoist_class() {
let src = r###"function run(c, v) {
return new c(v).value;
}
var o = {
p: class Foo {
constructor(value) {
this.value = value * 10;
}
},
x: 1,
y: 2,
};
console.log(o.p.name, o.p === o.p, run(o.p, o.x), run(o.p, o.y));"###;
let config = r#"{
"comparisons": true,
"evaluate": true,
"hoist_props": true,
"inline": true,
"keep_classnames": true,
"keep_fnames": true,
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, true);
}
#[test]
fn terser_hoist_props_issue_2519() {
let src = r###"function testFunc() {
var dimensions = { minX: 5, maxX: 6 };
var scale = 1;
var d = { x: (dimensions.maxX + dimensions.minX) / 2 };
return d.x * scale;
}
console.log(testFunc());"###;
let config = r#"{
"collapse_vars": true,
"evaluate": true,
"hoist_props": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_hoist_props_issue_2377_1() {
let src = r###"var obj = {
foo: 1,
bar: 2,
square: function (x) {
return x * x;
},
cube: function (x) {
return x * x * x;
},
};
console.log(obj.foo, obj.cube(3));"###;
let config = r#"{
"evaluate": true,
"hoist_props": true,
"inline": true,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
#[ignore = "Function anoymous"]
fn terser_hoist_props_issue_2508_6() {
let src = r###"var o = {
f: (x) => {
console.log(x);
},
};
o.f(o.f);"###;
let config = r#"{
"collapse_vars": true,
"hoist_props": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_hoist_props_issue_2508_1() {
let src = r###"var o = {
a: [1],
f: function (x) {
console.log(x);
},
};
o.f(o.a);"###;
let config = r#"{
"collapse_vars": true,
"hoist_props": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_identity_inline_identity_extra_params() {
let src = r###"const id = (x) => x;
console.log(id(1, console.log(2)), id(3, 4));"###;
let config = r#"{
"inline": true,
"reduce_vars": true,
"unused": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_identity_inline_identity_function() {
let src = r###"function id(x) {
return x;
}
console.log(id(1), id(2));"###;
let config = r#"{
"inline": true,
"reduce_vars": true,
"unused": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_identity_inline_identity_duplicate_arg_var() {
let src = r###"const id = (x) => {
return x;
var x;
};
console.log(id(1), id(2));"###;
let config = r#"{
"inline": true,
"reduce_vars": true,
"unused": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_template_string_regex_2() {
let src = r#"console.log(`${/a/} ${6 / 2} ${/b/.test("b")} ${1 ? /c/ : /d/}`);"#;
let config = r#"{
"evaluate": true,
"unsafe": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_template_string_evaluate_nested_templates() {
let src = r###"/*#__NOINLINE__*/ const any = 'any string, but should not be inlined';
var foo = `${`${`${`foo`}`}`}`;
var bar = `before ${`innerBefore ${any} innerAfter`} after`;
var baz = `1 ${2 + `3 ${any} 4` + 5} 6`;
console.log(foo);
console.log(bar);
console.log(baz);"###;
let config = r#"{
"evaluate": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_destructuring_destructuring_assign_of_computed_key() {
let src = r###"let x;
let four = 4;
({ [5 + 2 - four]: x } = { [1 + 2]: 42 });
console.log(x);"###;
let config = r#"{
"evaluate": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_destructuring_unused_destructuring_getter_side_effect_2() {
let src = r#"function extract(obj) {
const { a: a, b: b } = obj;
console.log(b);
}
extract({ a: 1, b: 2 });
extract({
get a() {
var s = "side effect";
console.log(s);
return s;
},
b: 4,
});"#;
let config = r#"{
"pure_getters": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_destructuring_mangle_destructuring_decl_array() {
let src = r###"var [, t, e, n, s, o = 2, r = [1 + 2]] = [9, 8, 7, 6];
console.log(t, e, n, s, o, r);"###;
let config = r#"{
"evaluate": true,
"unused": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_destructuring_issue_3205_4() {
let src = r#"(function () {
function f(o) {
var { a: x } = o;
console.log(x);
}
f({ a: "PASS" });
})();"#;
let config = r#"{
"inline": 3,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_destructuring_issue_3205_3() {
let src = r#"(function () {
function f(o, { a: x } = o) {
console.log(x);
}
f({ a: "PASS" });
})();"#;
let config = r#"{
"inline": 3,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_destructuring_unused_destructuring_multipass() {
let src = r###"let { w: w, x: y, z: z } = { x: 1, y: 2, z: 3 };
console.log(y);
if (0) {
console.log(z);
}"###;
let config = r#"{
"conditionals": true,
"evaluate": true,
"toplevel": true,
"passes": 2,
"pure_getters": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_destructuring_arrow_func_with_destructuring_args() {
let src = r###"(({ foo: foo = 1 + 0, bar: bar = 2 }, [car = 3, far = 4]) => {
console.log(foo, bar, car, far);
})({ bar: 5 - 0 }, [, 6]);"###;
let config = r#"{
"evaluate": true,
"unused": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_destructuring_issue_3205_2() {
let src = r#"(function () {
function f() {
var o = { a: "PASS" },
{ a: x } = o;
console.log(x);
}
f();
})();"#;
let config = r#"{
"inline": 3,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_destructuring_empty_object_destructuring_3() {
let src = r#"var {} = Object;
let { L: L } = Object,
L2 = "foo";
const bar = "bar",
{ prop: C1, C2: C2 = console.log("side effect"), C3: C3 } = Object;"#;
let config = r#"{
"pure_getters": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_destructuring_empty_object_destructuring_4() {
let src = r#"var {} = Object;
let { L: L } = Object,
L2 = "foo";
const bar = "bar",
{ prop: C1, C2: C2 = console.log("side effect"), C3: C3 } = Object;"#;
let config = r#"{
"pure_getters": true,
"toplevel": true,
"unsafe": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_destructuring_issue_3205_5() {
let src = r#"(function () {
function f(g) {
var o = g,
{ a: x } = o;
console.log(x);
}
f({ a: "PASS" });
})();"#;
let config = r#"{
"inline": 3,
"passes": 4,
"reduce_vars": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_destructuring_unused_destructuring_decl_1() {
let src = r###"let { x: L, y: y } = { x: 2 };
var { U: u, V: V } = { V: 3 };
const { C: C, D: D } = { C: 1, D: 4 };
console.log(L, V);"###;
let config = r#"{
"pure_getters": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_destructuring_mangle_destructuring_decl() {
let src = r###"function test(opts) {
let a = opts.a || { e: 7, n: 8 };
let { t: t, e: e, n: n, s: s = 5 + 4, o: o, r: r } = a;
console.log(t, e, n, s, o, r);
}
test({ a: { t: 1, e: 2, n: 3, s: 4, o: 5, r: 6 } });
test({});"###;
let config = r#"{
"evaluate": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_destructuring_unused_destructuring_arrow_param() {
let src = r#"let bar = ({ w: w = console.log("side effect"), x: x, y: z }) => {
console.log(x);
};
bar({ x: 4, y: 5, z: 6 });"#;
let config = r#"{
"pure_getters": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_destructuring_anon_func_with_destructuring_args() {
let src = r###"(function ({ foo: foo = 1 + 0, bar: bar = 2 }, [car = 3, far = 4]) {
console.log(foo, bar, car, far);
})({ bar: 5 - 0 }, [, 6]);"###;
let config = r#"{
"evaluate": true,
"unused": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_destructuring_mangle_destructuring_assign_toplevel_true() {
let src = r###"function test(opts) {
let s, o, r;
let a = opts.a || { e: 7, n: 8 };
({ t, e, n, s = 5 + 4, o, r } = a);
console.log(t, e, n, s, o, r);
}
let t, e, n;
test({ a: { t: 1, e: 2, n: 3, s: 4, o: 5, r: 6 } });
test({});"###;
let config = r#"{
"toplevel": true,
"evaluate": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_destructuring_mangle_destructuring_decl_collapse_vars() {
let src = r###"function test(opts) {
let a = opts.a || { e: 7, n: 8 };
let { t: t, e: e, n: n, s: s = 5 + 4, o: o, r: r } = a;
console.log(t, e, n, s, o, r);
}
test({ a: { t: 1, e: 2, n: 3, s: 4, o: 5, r: 6 } });
test({});"###;
let config = r#"{
"collapse_vars": true,
"evaluate": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_destructuring_unused_destructuring_decl_5() {
let src = r###"const { a: a, b: c, d: d = new Object(1) } = { b: 7 };
let { e: e, f: g, h: h = new Object(2) } = { e: 8 };
var { w: w, x: y, z: z = new Object(3) } = { w: 4, x: 5, y: 6 };
console.log(c, e, z + 0);"###;
let config = r#"{
"pure_getters": true,
"toplevel": true,
"top_retain": ["a", "e", "w"],
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_destructuring_mangle_destructuring_assign_toplevel_false() {
let src = r###"function test(opts) {
let s, o, r;
let a = opts.a || { e: 7, n: 8 };
({ t, e, n, s = 9, o, r } = a);
console.log(t, e, n, s, o, r);
}
let t, e, n;
test({ a: { t: 1, e: 2, n: 3, s: 4, o: 5, r: 6 } });
test({});"###;
let config = r#"{
"toplevel": false,
"evaluate": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_arrow_issue_2105_2() {
let src = r#"((factory) => {
factory();
})(() =>
((fn) => {
fn()().prop();
})(() => {
let bar = () => {
var quux = () => {
console.log("PASS");
},
foo = () => {
console.log;
quux();
};
return { prop: foo };
};
return bar;
})
);"#;
let config = r#"{
"collapse_vars": true,
"inline": true,
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_arrow_issue_2105_1() {
let src = r#"!(function (factory) {
factory();
})(function () {
return (function (fn) {
fn()().prop();
})(function () {
function bar() {
var quux = function () {
console.log("PASS");
},
foo = function () {
console.log;
quux();
};
return { prop: foo };
}
return bar;
});
});"#;
let config = r#"{
"unsafe_arrows": true,
"collapse_vars": true,
"ecma": 2015,
"inline": true,
"passes": 3,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"unsafe_methods": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_arrow_issue_2084() {
let src = r###"var c = 0;
!(function () {
!(function (c) {
c = 1 + c;
var c = 0;
function f14(a_1) {
if (((c = 1 + c), 0 !== (23).toString()))
(c = 1 + c), a_1 && (a_1[0] = 0);
}
f14();
})(-1);
})();
console.log(c);"###;
let config = r#"{
"unsafe_arrows": true,
"collapse_vars": true,
"conditionals": true,
"ecma": 2015,
"evaluate": true,
"inline": true,
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"sequences": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_t120_issue_t120_4() {
let src = r###"for (
var x = 1,
t = (o) => {
var i = +o;
return console.log(i + i) && 0;
};
x--;
t(2)
);"###;
let config = r#"{
"defaults": true,
"inline": 3,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_t120_issue_t120_5() {
let src = r###"for (
var x = 1,
t = (o) => {
var i = +o;
return console.log(i + i) && 0;
};
x--;
)
t(3);"###;
let config = r#"{
"defaults": true,
"inline": 3,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_class_properties_mangle_keep_quoted() {
let src = r#"class Foo {
bar = "bar";
static zzz = "zzz";
toString() {
return this.bar + Foo.zzz;
}
}
console.log(new Foo().toString())"#;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn terser_class_properties_static_means_execution() {
let src = r#"let x = 0;
class NoProps {}
class WithProps {
prop = (x = x === 1 ? "PASS" : "FAIL");
}
class WithStaticProps {
static prop = (x = x === 0 ? 1 : "FAIL");
}
new NoProps();
new WithProps();
new WithStaticProps();
console.log(x);"#;
let config = r#"{
"toplevel": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_1447_conditional_false_stray_else_in_loop() {
let src = r###"for (var i = 1; i <= 4; ++i) {
if (i <= 2) continue;
console.log(i);
}"###;
let config = r#"{
"booleans": true,
"comparisons": true,
"conditionals": false,
"dead_code": true,
"evaluate": true,
"hoist_vars": true,
"if_return": true,
"join_vars": true,
"loops": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_harmony_object_spread_unsafe() {
let src = r###"var o1 = { x: 1, y: 2 };
var o2 = { x: 3, z: 4 };
var cloned = { ...o1 };
var merged = { ...o1, ...o2 };
console.log(cloned, merged);"###;
let config = r#"{
"collapse_vars": true,
"evaluate": true,
"join_vars": true,
"passes": 3,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"toplevel": true,
"unsafe": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_harmony_issue_2794_4() {
let src = r###"for (var x of ([1, 2], [3, 4])) {
console.log(x);
}"###;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn terser_harmony_issue_2794_3() {
let src = r###"function foo() {
for (const a of func(value)) {
console.log(a);
}
function func(va) {
return doSomething(va);
}
}
function doSomething(x) {
return [x, 2 * x, 3 * x];
}
const value = 10;
foo();"###;
let config = r#"{
"collapse_vars": true,
"evaluate": true,
"inline": 3,
"passes": 3,
"properties": true,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_harmony_array_spread_of_sequence() {
let src = r###"var a = [1];
console.log([...(a, a)]);
console.log([...a, a]);
console.log([...(a || a)]);
console.log([...(a || a)]);"###;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn terser_harmony_issue_2794_2() {
let src = r###"function foo() {
for (const a of func(value)) {
console.log(a);
}
function func(va) {
return doSomething(va);
}
}
function doSomething(x) {
return [x, 2 * x, 3 * x];
}
const value = 10;
foo();"###;
let config = r#"{
"collapse_vars": true,
"evaluate": true,
"inline": true,
"passes": 1,
"properties": true,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": false,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_harmony_issue_2874_1() {
let src = r#"(function () {
function foo() {
let letters = ["A", "B", "C"];
let result = [2, 1, 0].map((key) => bar(letters[key] + key));
return result;
}
function bar(value) {
return () => console.log(value);
}
foo().map((fn) => fn());
})();"#;
let config = r#"{
"collapse_vars": true,
"evaluate": true,
"inline": 3,
"reduce_funcs": true,
"reduce_vars": true,
"sequences": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_harmony_issue_2762() {
let src = r###"var bar = 1,
T = true;
(function () {
if (T) {
const a = function () {
var foo = bar;
console.log(foo, a.prop, b.prop);
};
a.prop = 2;
const b = { prop: 3 };
a();
}
})();"###;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn terser_harmony_issue_1898() {
let src = r###"class Foo {
bar() {
for (const x of [6, 5]) {
for (let y of [4, 3]) {
for (var z of [2, 1]) {
console.log(x, y, z);
}
}
}
}
}
new Foo().bar();"###;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn terser_harmony_issue_2794_6() {
let src = r###"for (let e of ([1, 2], [3, 4, 5])) {
console.log(e);
}"###;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn terser_harmony_issue_2794_1() {
let src = r###"function foo() {
for (const a of func(value)) {
console.log(a);
}
function func(va) {
return doSomething(va);
}
}
function doSomething(x) {
return [x, 2 * x, 3 * x];
}
const value = 10;
foo();"###;
let config = r#"{
"collapse_vars": true,
"evaluate": true,
"inline": true,
"passes": 1,
"properties": true,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": false,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_harmony_issue_2874_2() {
let src = r#"(function () {
let keys = [];
function foo() {
var result = [2, 1, 0].map((value) => {
keys.push(value);
return bar();
});
return result;
}
function bar() {
var letters = ["A", "B", "C"],
key = keys.shift();
return () => console.log(letters[key] + key);
}
foo().map((fn) => fn());
})();"#;
let config = r#"{
"collapse_vars": true,
"evaluate": true,
"inline": 3,
"reduce_funcs": true,
"reduce_vars": true,
"sequences": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_harmony_issue_t80() {
let src = r#"function foo(data = []) {
var u,
v = "unused";
if (arguments.length == 1) {
data = [data];
}
return data;
}
console.log(JSON.stringify([foo(), foo(null), foo(5, 6)]));"#;
let config = r#"{
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_harmony_issue_2349() {
let src = r#"function foo(boo, key) {
const value = boo.get();
return value.map(({ [key]: bar }) => bar);
}
console.log(foo({ get: () => [{ blah: 42 }] }, "blah"));"#;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn terser_harmony_issue_2874_3() {
let src = r#"function f() {
return x + y;
}
let x, y;
let a = (z) => {
x = "A";
y = z;
console.log(f());
};
a(1);
a(2);"#;
let config = r#"{
"collapse_vars": true,
"evaluate": true,
"inline": 3,
"reduce_funcs": false,
"reduce_vars": true,
"sequences": true,
"side_effects": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_harmony_issue_2349b() {
let src = r#"function foo(boo, key) {
const value = boo.get();
return value.map(function ({ [key]: bar }) {
return bar;
});
}
console.log(
foo(
{
get: function () {
return [{ blah: 42 }];
},
},
"blah"
)
);"#;
let config = r#"{
"arrows": true,
"collapse_vars": true,
"ecma": 2015,
"evaluate": true,
"inline": true,
"passes": 3,
"properties": true,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"side_effects": true,
"unsafe_arrows": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_1275_string_plus_optimization() {
let src = r#"function foo(anything) {
function throwing_function() {
throw "nope";
}
try {
console.log("0" + throwing_function() ? "yes" : "no");
} catch (ex) {
console.log(ex);
}
console.log("0" + anything ? "yes" : "no");
console.log(anything + "0" ? "Yes" : "No");
console.log("" + anything);
console.log(anything + "");
}
foo();"#;
let config = r#"{
"booleans": true,
"comparisons": true,
"conditionals": true,
"dead_code": true,
"evaluate": true,
"hoist_funs": true,
"if_return": true,
"join_vars": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_async_async_inline() {
let src = r#"(async function () {
return await 3;
})();
(async function (x) {
await console.log(x);
})(4);
function invoke(x, y) {
return x(y);
}
invoke(async function () {
return await 1;
});
invoke(async function (x) {
await console.log(x);
}, 2);
function top() {
console.log("top");
}
top();
async function async_top() {
console.log("async_top");
}
async_top();"#;
let config = r#"{
"collapse_vars": true,
"conditionals": true,
"evaluate": true,
"inline": true,
"negate_iife": true,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
#[ignore]
fn terser_logical_assignments_assign_in_conditional_part() {
let src = r#"var status = "PASS";
var nil = null;
var nil_prop = { prop: null };
nil &&= console.log((status = "FAIL"));
nil_prop.prop &&= console.log((status = "FAIL"));
console.log(status);"#;
let config = r#"{
"toplevel": true,
"evaluate": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
#[ignore]
fn terser_logical_assignments_assignment_in_left_part() {
let src = r#"var status = "FAIL";
var x = {};
x[(status = "PASS")] ||= 1;
console.log(status);"#;
let config = r#"{
"toplevel": true,
"evaluate": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_labels_labels_4() {
let src = r###"out: for (var i = 0; i < 5; ++i) {
if (i < 3) continue out;
console.log(i);
}"###;
let config = r#"{
"conditionals": true,
"dead_code": true,
"if_return": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_labels_labels_3() {
let src = r###"for (var i = 0; i < 5; ++i) {
if (i < 3) continue;
console.log(i);
}"###;
let config = r#"{
"conditionals": true,
"dead_code": true,
"if_return": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_labels_labels_6() {
let src = r###"out: break out;
console.log('PASS')"###;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_t292_no_flatten_with_var_colliding_with_arg_value_inner_scope() {
let src = r#"var g = ["a"];
function problem(arg) {
return g.indexOf(arg);
}
function unused(arg) {
return problem(arg);
}
function a(arg) {
return problem(arg);
}
function b(test) {
var problem = test * 2;
console.log(problem);
return g[problem];
}
function c(arg) {
return b(a(arg));
}
console.log(c("a"));"#;
let config = r#"{
"collapse_vars": true,
"inline": true,
"reduce_funcs": true,
"reduce_vars": true,
"sequences": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_t292_no_flatten_with_arg_colliding_with_arg_value_inner_scope() {
let src = r#"var g = ["a"];
function problem(arg) {
return g.indexOf(arg);
}
function unused(arg) {
return problem(arg);
}
function a(arg) {
return problem(arg);
}
function b(problem) {
return g[problem];
}
function c(arg) {
return b(a(arg));
}
console.log(c("a"));"#;
let config = r#"{
"collapse_vars": true,
"inline": true,
"reduce_funcs": true,
"reduce_vars": true,
"sequences": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_1770_numeric_literal() {
let src = r#"var obj = {
0: 0,
"-0": 1,
42: 2,
42: 3,
37: 4,
o: 5,
1e42: 6,
j: 7,
1e42: 8,
};
console.log(obj[-0], obj[-""], obj["-0"]);
console.log(obj[42], obj["42"]);
console.log(obj[37], obj["o"], obj[37], obj["37"]);
console.log(obj[1e42], obj["j"], obj["1e+42"]);"#;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_1770_mangle_props() {
let src = r#"var obj = { undefined: 1, NaN: 2, Infinity: 3, "-Infinity": 4, null: 5 };
console.log(
obj[void 0],
obj[undefined],
obj["undefined"],
obj[0 / 0],
obj[NaN],
obj["NaN"],
obj[1 / 0],
obj[Infinity],
obj["Infinity"],
obj[-1 / 0],
obj[-Infinity],
obj["-Infinity"],
obj[null],
obj["null"]
);"#;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_1105_infinity_not_in_with_scope() {
let src = r#"var o = { Infinity: "oInfinity" };
var vInfinity = "Infinity";
vInfinity = Infinity;
console.log(o)
console.log(vInfinity)"#;
let config = r#"{
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_3113_1() {
let src = r###"var c = 0;
(function () {
function f() {
while (g());
}
var a = f();
function g() {
a && a[c++];
}
g((a = 1));
})();
console.log(c);"###;
let config = r#"{
"evaluate": true,
"reduce_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_2799_2() {
let src = r#"(function () {
function foo() {
Function.prototype.call.apply(console.log, [null, "PASS"]);
}
foo();
})();"#;
let config = r#"{
"reduce_vars": true,
"unsafe_proto": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_recursive_inlining_1() {
let src = r#"!(function () {
function foo() {
bar();
}
function bar() {
foo();
}
console.log("PASS");
})();"#;
let config = r#"{
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_var_assign_2() {
let src = r###"!(function () {
var a;
if ((a = 2)) console.log(a);
})();"###;
let config = r#"{
"evaluate": true,
"reduce_funcs": true,
"reduce_vars": true,
"sequences": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_2757_1() {
let src = r###"let u;
(function () {
let v;
console.log(u, v);
})();"###;
let config = r#"{
"evaluate": true,
"inline": true,
"reduce_vars": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_inverted_var() {
let src = r#"console.log(
(function () {
var a = 1;
return a;
})(),
(function () {
var b;
b = 2;
return b;
})(),
(function () {
c = 3;
return c;
var c;
})(),
(function (c) {
c = 4;
return c;
})(),
(function (c) {
c = 5;
return c;
var c;
})(),
(function c() {
c = 6;
return typeof c;
})(),
(function c() {
c = 7;
return c;
var c;
})(),
(function () {
c = 8;
return c;
var c = "foo";
})()
);"#;
let config = r#"{
"evaluate": true,
"inline": true,
"passes": 3,
"reduce_vars": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_pure_getters_3() {
let src = r###"var a;
var a = a && a.b;
console.log(a && a.b)"###;
let config = r#"{
"pure_getters": true,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_unsafe_evaluate_side_effect_free_1() {
let src = r###"console.log(
(function () {
var o = { p: 1 };
console.log(o.p);
return o.p;
})()
);
console.log(
(function () {
var o = { p: 2 };
console.log(o.p);
return o;
})()
);
console.log(
(function () {
var o = { p: 3 };
console.log([o][0].p);
return o.p;
})()
);"###;
let config = r#"{
"evaluate": true,
"reduce_funcs": true,
"reduce_vars": true,
"unsafe": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_2420_2() {
let src = r#"function f() {
var that = this;
if (that.bar) that.foo();
else
!(function (that, self) {
console.log(this === that, self === this, that === self);
})(that, this);
}
f.call({
bar: 1,
foo: function () {
console.log("foo", this.bar);
},
});
f.call({});"#;
let config = r#"{
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_escape_expansion() {
let src = r#"function main() {
var thing = baz();
if (thing !== (thing = baz())) console.log("FAIL");
else console.log("PASS");
}
function foo() {}
function bar(...x) {
return x[0];
}
function baz() {
return bar(...[foo]);
}
main();"#;
let config = r#"{
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_obj_arg_1() {
let src = r###"var C = 1;
function f(obj) {
return obj.bar();
}
console.log(
f({
bar: function () {
return C + C;
},
})
);"###;
let config = r#"{
"collapse_vars": true,
"evaluate": true,
"inline": true,
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_2420_3() {
let src = r#"function f() {
var that = this;
if (that.bar) that.foo();
else
((that, self) => {
console.log(this === that, self === this, that === self);
})(that, this);
}
f.call({
bar: 1,
foo: function () {
console.log("foo", this.bar);
},
});
f.call({});"#;
let config = r#"{
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
#[ignore]
fn terser_reduce_vars_iife_eval_2() {
let src = r#"(function () {
var x = function f() {
return f;
};
console.log(x() === eval("x"));
})();"#;
let config = r#"{
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_pure_getters_2() {
let src = r###"var a;
var a = a && a.b;
console.log(a && a.b)"###;
let config = r#"{
"pure_getters": "strict",
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_func_modified() {
let src = r###"function f(a) {
function a() {
return 1;
}
function b() {
return 2;
}
function c() {
return 3;
}
b.inject = [];
c = function () {
return 4;
};
return a() + b() + c();
}
console.log(f(1423796))"###;
let config = r#"{
"inline": true,
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_2860_1() {
let src = r###"console.log(
(function (a) {
return (a ^= 1);
a ^= 2;
})()
);"###;
let config = r#"{
"dead_code": true,
"evaluate": true,
"reduce_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_2836() {
let src = r#"function f() {
return "FAIL";
}
console.log(f());
function f() {
return "PASS";
}"#;
let config = r#"{
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_chained_assignments() {
let src = r###"function f() {
var a = [94, 173, 190, 239];
var b = 0;
b |= a[0];
b <<= 8;
b |= a[1];
b <<= 8;
b |= a[2];
b <<= 8;
b |= a[3];
return b;
}
console.log(f().toString(16));"###;
let config = r#"{
"evaluate": true,
"inline": true,
"reduce_vars": true,
"sequences": true,
"side_effects": true,
"toplevel": true,
"unsafe": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_obj_for_1() {
let src = r###"var o = { a: 1 };
for (var i = o.a--; i; i--) console.log(i);"###;
let config = r#"{
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_iife() {
let src = r###"!(function (a, b, c) {
b++;
console.log(a - 1, b * 1, c + 2);
})(1, 2, 3);"###;
let config = r#"{
"evaluate": true,
"reduce_funcs": true,
"reduce_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_inner_var_label() {
let src = r###"function f(a) {
l: {
if (a) break l;
var t = 1;
}
console.log(t);
}
f(123123)
f(0)"###;
let config = r#"{
"evaluate": true,
"reduce_funcs": true,
"reduce_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_side_effects_assign() {
let src = r###"var a = typeof void (a && a.in == 1, 0);
console.log(a);"###;
let config = r#"{
"evaluate": true,
"reduce_funcs": true,
"reduce_vars": true,
"sequences": true,
"side_effects": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_defun_catch_6() {
let src = r###"try {
throw 42;
} catch (a) {
console.log(a);
}
function a() {}"###;
let config = r#"{
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_passes() {
let src = r###"function f() {
var a = 1,
b = 2,
c = 3;
if (a) {
b = c;
} else {
c = b;
}
console.log(a + b);
console.log(b + c);
console.log(a + c);
console.log(a + b + c);
}
f()"###;
let config = r#"{
"conditionals": true,
"evaluate": true,
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_defun_catch_1() {
let src = r###"function a() {}
try {
throw 42;
} catch (a) {
console.log(a);
}"###;
let config = r#"{
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_unsafe_evaluate_array_2() {
let src = r###"var arr = [
1,
2,
function (x) {
return x * x;
},
function (x) {
return x * x * x;
},
];
console.log(arr[0], arr[1], arr[2](2), arr[3]);"###;
let config = r#"{
"evaluate": true,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unsafe": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_1670_6() {
let src = r###"(function (a) {
switch (1) {
case (a = 1):
console.log(a);
break;
default:
console.log(2);
break;
}
})(1);"###;
let config = r#"{
"dead_code": true,
"evaluate": true,
"keep_fargs": false,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"switches": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_redefine_farg_1() {
let src = r###"function f(a) {
var a;
return typeof a;
}
function g(a) {
var a = 42;
return typeof a;
}
function h(a, b) {
var a = b;
return typeof a;
}
console.log(f([]), g([]), h([]));"###;
let config = r#"{
"evaluate": true,
"keep_fargs": false,
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_1670_1() {
let src = r#"(function f() {
switch (1) {
case 0:
var a = true;
break;
default:
if (typeof a === "undefined") console.log("PASS");
else console.log("FAIL");
}
})();"#;
let config = r#"{
"comparisons": true,
"conditionals": true,
"dead_code": true,
"evaluate": true,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"switches": true,
"typeofs": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_perf_3() {
let src = r###"var foo = function (x, y, z) {
return x < y ? x * y + z : x * z - y;
};
var indirect_foo = function (x, y, z) {
return foo(x, y, z);
};
var sum = 0;
for (var i = 0; i < 100; ++i) sum += indirect_foo(i, i + 1, 3 * i);
console.log(sum);"###;
let config = r#"{
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_defun_var_3() {
let src = r###"function a() {}
function b() {}
console.log(typeof a, typeof b);
var a = 42,
b;"###;
let config = r#"{
"evaluate": true,
"reduce_vars": true,
"toplevel": true,
"typeofs": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_accessor_2() {
let src = r###"var A = 1;
var B = {
get c() {
console.log(A);
},
};
B.c;"###;
let config = r#"{
"collapse_vars": true,
"evaluate": true,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_unused_modified() {
let src = r#"console.log(
(function () {
var b = 1,
c = "FAIL";
if (0 || b--) c = "PASS";
b = 1;
return c;
})()
);"#;
let config = r#"{
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_unsafe_evaluate_object_1() {
let src = r###"function f0() {
var a = 1;
var b = {};
b[a] = 2;
console.log(a + 3);
}
function f1() {
var a = { b: 1 };
a.b = 2;
console.log(a.b + 3);
}
f0()
f1()"###;
let config = r#"{
"evaluate": true,
"reduce_funcs": true,
"reduce_vars": true,
"unsafe": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_duplicate_lambda_defun_name_1() {
let src = r###"console.log(
(function f(a) {
function f() {}
return f.length;
})()
);"###;
let config = r#"{
"reduce_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_2423_5() {
let src = r###"function x() {
y();
}
function y() {
console.log(1);
}
function z() {
function y() {
console.log(2);
}
x();
}
z();
z();"###;
let config = r#"{
"inline": true,
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_unsafe_evaluate_array_4() {
let src = r###"var arr = [
1,
2,
function () {
return ++this[0];
},
];
console.log(arr[0], arr[1], arr[2], arr[0]);"###;
let config = r#"{
"evaluate": true,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unsafe": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_2774() {
let src = r###"console.log(
{
get a() {
var b;
(b = true) && b.c;
b = void 0;
},
}.a
);"###;
let config = r#"{
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_lvalues_def_2() {
let src = r###"var b = 1;
var a = (b += 1),
b = NaN;
console.log(a, b);"###;
let config = r#"{
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_func_arg_2() {
let src = r###"var a = 42;
!(function (a) {
console.log(a());
})(function (a) {
return a;
});"###;
let config = r#"{
"evaluate": true,
"inline": true,
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_unsafe_evaluate() {
let src = r###"function f0() {
var a = { b: 1 };
console.log(a.b + 3);
}
function f1() {
var a = { b: { c: 1 }, d: 2 };
console.log(a.b + 3, a.d + 4, a.b.c + 5, a.d.c + 6);
}
console.log(f0())
console.log(f1())"###;
let config = r#"{
"evaluate": true,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"unsafe": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_2423_3() {
let src = r###"function c() {
return 1;
}
function p() {
console.log(c());
}
p();"###;
let config = r#"{
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_defun_inline_3() {
let src = r###"function f() {
return g(2);
function g(b) {
return b;
}
}
console.log(f())"###;
let config = r#"{
"evaluate": true,
"inline": true,
"passes": 3,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_3113_2() {
let src = r###"var c = 0;
(function () {
function f() {
while (g());
}
var a = f();
function g() {
a && a[c++];
}
a = 1;
g();
})();
console.log(c);"###;
let config = r#"{
"evaluate": true,
"reduce_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_2799_1() {
let src = r###"console.log(
(function () {
return f;
function f(n) {
function g(i) {
return i && i + g(i - 1);
}
function h(j) {
return g(j);
}
return h(n);
}
})()(5)
);"###;
let config = r#"{
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_iife_new() {
let src = r###"var A = new (function (a, b, c) {
b++;
console.log(a - 1, b * 1, c + 2);
})(1, 2, 3);"###;
let config = r#"{
"evaluate": true,
"reduce_funcs": true,
"reduce_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_recursive_inlining_3() {
let src = r#"!(function () {
function foo(x) {
console.log("foo", x);
if (x) bar(x - 1);
}
function bar(x) {
console.log("bar", x);
if (x) qux(x - 1);
}
function qux(x) {
console.log("qux", x);
if (x) foo(x - 1);
}
qux(4);
})();"#;
let config = r#"{
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_recursive_inlining_4() {
let src = r#"!(function () {
function foo(x) {
console.log("foo", x);
if (x) bar(x - 1);
}
function bar(x) {
console.log("bar", x);
if (x) qux(x - 1);
}
function qux(x) {
console.log("qux", x);
if (x) foo(x - 1);
}
qux(4);
bar(5);
})();"#;
let config = r#"{
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_2757_2() {
let src = r###"(function () {
let bar;
const unused = function () {
bar = true;
};
if (!bar) {
console.log(1);
}
console.log(2);
})();"###;
let config = r#"{
"conditionals": true,
"evaluate": true,
"inline": true,
"passes": 2,
"reduce_vars": true,
"sequences": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_recursive_inlining_2() {
let src = r#"!(function () {
function foo() {
qux();
}
function bar() {
foo();
}
function qux() {
bar();
}
console.log("PASS");
})();"#;
let config = r#"{
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_var_assign_1() {
let src = r###"!(function () {
var a;
a = 2;
console.log(a);
})();"###;
let config = r#"{
"evaluate": true,
"reduce_funcs": true,
"reduce_vars": true,
"sequences": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_1865() {
let src = r###"function f(some) {
some.thing = false;
}
console.log(
(function () {
var some = { thing: true };
f(some);
return some.thing;
})()
);"###;
let config = r#"{
"evaluate": true,
"reduce_funcs": true,
"reduce_vars": true,
"unsafe": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_2449() {
let src = r#"var a = "PASS";
function f() {
return a;
}
function g() {
return f();
}
(function () {
var a = "FAIL";
if (a == a) console.log(g());
})();"#;
let config = r#"{
"passes": 10,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_2420_1() {
let src = r#"function run() {
var self = this;
if (self.count++) self.foo();
else self.bar();
}
var o = {
count: 0,
foo: function () {
console.log("foo");
},
bar: function () {
console.log("bar");
},
};
run.call(o);
run.call(o);"#;
let config = r#"{
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_2485() {
let src = r###"var foo = function (bar) {
var n = function (a, b) {
return a + b;
};
var sumAll = function (arg) {
return arg.reduce(n, 0);
};
var runSumAll = function (arg) {
return sumAll(arg);
};
bar.baz = function (arg) {
var n = runSumAll(arg);
return (n.get = 1), n;
};
return bar;
};
var bar = foo({});
console.log(bar.baz([1, 2, 3]));"###;
let config = r#"{
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_inner_var_for_2() {
let src = r###"!(function () {
var a = 1;
for (var b = 1; --b; ) var a = 2;
console.log(a);
})();"###;
let config = r#"{
"evaluate": true,
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_obj_arg_2() {
let src = r###"var C = 1;
function f(obj) {
return obj.bar();
}
console.log(
f({
bar: function () {
return C + C;
},
})
);"###;
let config = r#"{
"collapse_vars": true,
"evaluate": true,
"inline": true,
"passes": 3,
"properties": true,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
#[ignore]
fn terser_reduce_vars_reduce_vars() {
let src = r#"var A = 1;
(function f0() {
var a = 2;
console.log(a - 5);
console.log(A - 5);
})();
(function f1() {
var a = 2;
console.log(a - 5);
eval("console.log(a);");
})();
(function f2(eval) {
var a = 2;
console.log(a - 5);
eval("console.log(a);");
})(eval);
(function f3() {
var b = typeof C !== "undefined";
var c = 4;
if (b) {
return "yes";
} else {
return "no";
}
})();
console.log(A + 1);"#;
let config = r#"{
"conditionals": true,
"evaluate": true,
"global_defs": {
"C": 0
},
"inline": true,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_modified() {
let src = r#"function f0() {
var a = 1,
b = 2;
b++;
console.log(a + 1);
console.log(b + 1);
}
function f1() {
var a = 1,
b = 2;
--b;
console.log(a + 1);
console.log(b + 1);
}
function f2() {
var a = 1,
b = 2,
c = 3;
b = c;
console.log(a + b);
console.log(b + c);
console.log(a + c);
console.log(a + b + c);
}
function f3() {
var a = 1,
b = 2,
c = 3;
b *= c;
console.log(a + b);
console.log(b + c);
console.log(a + c);
console.log(a + b + c);
}
function f4() {
var a = 1,
b = 2,
c = 3;
if (a) {
b = c;
} else {
c = b;
}
console.log(a + b);
console.log(b + c);
console.log(a + c);
console.log(a + b + c);
}
function f5(a) {
B = a;
console.log(typeof A ? "yes" : "no");
console.log(typeof B ? "yes" : "no");
}
f0(), f1(), f2(), f3(), f4(), f5();"#;
let config = r#"{
"conditionals": true,
"evaluate": true,
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_unsafe_evaluate_escaped() {
let src = r###"console.log(
(function () {
var o = { p: 1 };
console.log(o, o.p);
return o.p;
})()
);
console.log(
(function () {
var o = { p: 2 };
console.log(o.p, o);
return o.p;
})()
);
console.log(
(function () {
var o = { p: 3 },
a = [o];
console.log(a[0].p++);
return o.p;
})()
);"###;
let config = r#"{
"evaluate": true,
"reduce_funcs": true,
"reduce_vars": true,
"unsafe": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_2669() {
let src = r#"let foo;
console.log(([foo] = ["PASS"]) && foo);"#;
let config = r#"{
"evaluate": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_defun_catch_3() {
let src = r###"try {
throw 42;
function a() {}
} catch (a) {
console.log(a);
}"###;
let config = r#"{
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_2860_2() {
let src = r###"console.log(
(function (a) {
return (a ^= 1);
a ^= 2;
})()
);"###;
let config = r#"{
"dead_code": true,
"evaluate": true,
"inline": true,
"passes": 2,
"reduce_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_delay_def() {
let src = r###"function f() {
return a;
var a;
}
function g() {
return a;
var a = 1;
}
console.log(f(), g());"###;
let config = r#"{
"evaluate": true,
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_2496() {
let src = r#"function execute(callback) {
callback();
}
class Foo {
constructor(message) {
this.message = message;
}
go() {
this.message = "PASS";
console.log(this.message);
}
run() {
execute(() => {
this.go();
});
}
}
new Foo("FAIL").run();"#;
let config = r#"{
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_defun_catch_2() {
let src = r###"try {
function a() {}
throw 42;
} catch (a) {
console.log(a);
}"###;
let config = r#"{
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_2450_5() {
let src = r###"var a;
function f(b) {
console.log(a === b);
a = b;
}
function g() {}
[1, 2, 3].forEach(function () {
f(g);
});"###;
let config = r#"{
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_1850_2() {
let src = r###"function f() {
console.log(a, a, a);
}
var a = 1;
f();"###;
let config = r#"{
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": "funcs",
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_3110_3() {
let src = r#"(function () {
function foo() {
return isDev ? "foo" : "bar";
}
console.log(foo());
var isDev = true;
var obj = { foo: foo };
console.log(obj.foo());
})();"#;
let config = r#"{
"conditionals": true,
"evaluate": true,
"inline": true,
"properties": true,
"reduce_vars": true,
"sequences": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_defun_redefine() {
let src = r###"function f() {
function g() {
return 1;
}
function h() {
return 2;
}
g = function () {
return 3;
};
return g() + h();
}
console.log(f())"###;
let config = r#"{
"inline": true,
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_2423_6() {
let src = r###"function x() {
y();
}
function y() {
console.log(1);
}
function z() {
function y() {
console.log(2);
}
x();
y();
}
z();
z();"###;
let config = r#"{
"inline": true,
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_unsafe_evaluate_object_2() {
let src = r###"var obj = {
foo: 1,
bar: 2,
square: function (x) {
return x * x;
},
cube: function (x) {
return x * x * x;
},
};
console.log(obj.foo, obj.bar, obj.square(2), obj.cube);"###;
let config = r#"{
"evaluate": true,
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unsafe": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_2423_1() {
let src = r###"function c() {
return 1;
}
function p() {
console.log(c());
}
p();
p();"###;
let config = r#"{
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_redefine_farg_2() {
let src = r###"function f(a) {
var a;
return typeof a;
}
function g(a) {
var a = 42;
return typeof a;
}
function h(a, b) {
var a = b;
return typeof a;
}
console.log(f([]), g([]), h([]));"###;
let config = r#"{
"evaluate": true,
"inline": true,
"keep_fargs": false,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_1670_2() {
let src = r#"(function f() {
switch (1) {
case 0:
var a = true;
break;
default:
if (typeof a === "undefined") console.log("PASS");
else console.log("FAIL");
}
})();"#;
let config = r#"{
"conditionals": true,
"dead_code": true,
"evaluate": true,
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"switches": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_unsafe_evaluate_array_1() {
let src = r###"function f0() {
var a = 1;
var b = [];
b[a] = 2;
console.log(a + 3);
}
function f1() {
var a = [1];
a[2] = 3;
console.log(a.length);
}
function f2() {
var a = [1];
a.push(2);
console.log(a.length);
}
console.log(f0())
console.log(f1())
console.log(f2())"###;
let config = r#"{
"evaluate": true,
"reduce_funcs": true,
"reduce_vars": true,
"unsafe": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_perf_7() {
let src = r###"var indirect_foo = function (x, y, z) {
var foo = function (x, y, z) {
return x < y ? x * y + z : x * z - y;
};
return foo(x, y, z);
};
var sum = 0;
for (var i = 0; i < 100; ++i) sum += indirect_foo(i, i + 1, 3 * i);
console.log(sum);"###;
let config = r#"{
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_1670_5() {
let src = r###"(function (a) {
switch (1) {
case a:
console.log(a);
break;
default:
console.log(2);
break;
}
})(1);"###;
let config = r#"{
"dead_code": true,
"evaluate": true,
"keep_fargs": false,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"switches": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_escaped_prop_3() {
let src = r###"var a;
function f(b) {
if (a) console.log(a === b.c);
a = b.c;
}
function g() {}
function h() {
f({ c: g });
}
h();
h();"###;
let config = r#"{
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_defun_call() {
let src = r###"function f() {
return g() + h(1) - h(g(), 2, 3);
function g() {
return 4;
}
function h(a) {
return a;
}
}
console.log(f())"###;
let config = r#"{
"evaluate": true,
"inline": true,
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_defun_label() {
let src = r###"!(function () {
function f(a) {
L: {
if (a) break L;
return 1;
}
}
console.log(f(2));
})();"###;
let config = r#"{
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
#[ignore]
fn terser_reduce_vars_unsafe_evaluate_modified() {
let src = r#"console.log(
(function () {
var o = { p: 1 };
o.p++;
console.log(o.p);
return o.p;
})()
);
console.log(
(function () {
var o = { p: 2 };
--o.p;
console.log(o.p);
return o.p;
})()
);
console.log(
(function () {
var o = { p: 3 };
o.p += "";
console.log(o.p);
return o.p;
})()
);
console.log(
(function () {
var o = { p: 4 };
o = {};
console.log(o.p);
return o.p;
})()
);
console.log(
(function () {
var o = { p: 5 };
o.p = -9;
console.log(o.p);
return o.p;
})()
);
function inc() {
this.p++;
}
console.log(
(function () {
var o = { p: 6 };
inc.call(o);
console.log(o.p);
return o.p;
})()
);
console.log(
(function () {
var o = { p: 7 };
console.log([o][0].p++);
return o.p;
})()
);
console.log(
(function () {
var o = { p: 8 };
console.log({ q: o }.q.p++);
return o.p;
})()
);"#;
let config = r#"{
"evaluate": true,
"reduce_funcs": true,
"reduce_vars": true,
"unsafe": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_lvalues_def_1() {
let src = r###"var b = 1;
var a = b++,
b = NaN;
console.log(a, b);"###;
let config = r#"{
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_func_arg_1() {
let src = r###"var a = 42;
!(function (a) {
console.log(a());
})(function () {
return a;
});"###;
let config = r#"{
"evaluate": true,
"inline": true,
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_escape_local_sequence() {
let src = r#"function main() {
var thing = baz();
if (thing !== (thing = baz())) console.log("PASS");
else console.log("FAIL");
}
function baz() {
function foo() {}
function bar() {}
return foo, bar;
}
main();"#;
let config = r#"{
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_regex_loop() {
let src = r#"function f(x) {
for (var r, s = "acdabcdeabbb"; (r = x().exec(s)); ) console.log(r[0]);
}
var a = /ab*/g;
f(function () {
return a;
});"#;
let config = r#"{
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_3140_4() {
let src = r#"(function () {
var a;
function f() {}
f.g = function g() {
var o = { p: this };
function h() {
console.log(a ? "PASS" : "FAIL");
}
a = true;
o.p();
a = false;
h.g = g;
return h;
};
return f;
})()
.g()
.g();"#;
let config = r#"{
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_1670_4() {
let src = r#"(function f() {
switch (1) {
case 0:
var a = true;
break;
case 1:
if (typeof a === "undefined") console.log("PASS");
else console.log("FAIL");
}
})();"#;
let config = r#"{
"conditionals": true,
"dead_code": true,
"evaluate": true,
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"switches": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_redefine_farg_3() {
let src = r###"function f(a) {
var a;
return typeof a;
}
function g(a) {
var a = 42;
return typeof a;
}
function h(a, b) {
var a = b;
return typeof a;
}
console.log(f([]), g([]), h([]));"###;
let config = r#"{
"collapse_vars": true,
"evaluate": true,
"inline": true,
"keep_fargs": false,
"passes": 3,
"reduce_funcs": true,
"reduce_vars": true,
"sequences": true,
"side_effects": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_3140_3() {
let src = r#"(function () {
var a;
function f() {}
f.g = function g() {
var self = this;
function h() {
console.log(a ? "PASS" : "FAIL");
}
a = true;
(function () {
return self;
})()();
a = false;
h.g = g;
return h;
};
return f;
})()
.g()
.g();"#;
let config = r#"{
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_issue_1670_3() {
let src = r#"(function f() {
switch (1) {
case 0:
var a = true;
break;
case 1:
if (typeof a === "undefined") console.log("PASS");
else console.log("FAIL");
}
})();"#;
let config = r#"{
"comparisons": true,
"conditionals": true,
"dead_code": true,
"evaluate": true,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"switches": true,
"typeofs": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_reduce_vars_perf_1() {
let src = r###"function foo(x, y, z) {
return x < y ? x * y + z : x * z - y;
}
function indirect_foo(x, y, z) {
return foo(x, y, z);
}
var sum = 0;
for (var i = 0; i < 100; ++i) {
sum += indirect_foo(i, i + 1, 3 * i);
}
console.log(sum);"###;
let config = r#"{
"reduce_funcs": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_issue_2187_2() {
let src = r###"var b = 1;
console.log(
(function (a) {
return a && ++b;
})(b--)
);"###;
let config = r#"{
"collapse_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_issue_2436_14() {
let src = r#"var a = "PASS";
var b = {};
(function () {
var c = a;
c &&
(function (c, d) {
console.log(c, d);
})(b, c);
})();"#;
let config = r#"{
"collapse_vars": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_issue_2506() {
let src = r###"var c = 0;
function f0(bar) {
function f1(Infinity_2) {
function f13(NaN) {
if ((false <= NaN) & (this >> 1 >= 0)) {
c++;
}
}
var b_2 = f13(NaN, c++);
}
var bar = f1(-3, -1);
}
f0(false);
console.log(c);"###;
let config = r#"{
"collapse_vars": true,
"passes": 2,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_issue_2436_13() {
let src = r#"var a = "PASS";
(function () {
function f(b) {
(function g(b) {
var b = b && (b.null = "FAIL");
})(a);
}
f();
})();
console.log(a);"#;
let config = r#"{
"collapse_vars": true,
"passes": 2,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_issue_2187_3() {
let src = r###"var b = 1;
console.log(
(function (a) {
return a && ++b;
})(b--)
);"###;
let config = r#"{
"collapse_vars": true,
"inline": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_issue_2203_1() {
let src = r#"a = "FAIL";
console.log(
{
a: "PASS",
b: function () {
return (function (c) {
return c.a;
})((String, Object, this));
},
}.b()
);"#;
let config = r#"{
"collapse_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_issue_2914_2() {
let src = r###"function read(input) {
var i = 0;
var e = 0;
var t = 0;
while (e < 32) {
var n = input[i++];
t = (127 & n) << e;
if (0 === (128 & n)) return t;
e += 7;
}
}
console.log(read([129]));"###;
let config = r#"{
"collapse_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_issue_2319_1() {
let src = r###"console.log(
(function (a) {
return a;
})(
!(function () {
return this;
})()
)
);"###;
let config = r#"{
"collapse_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_cascade_forin() {
let src = r###"var a;
function f(b) {
return [b, b, b];
}
for (var c in ((a = console), f(a))) console.log(c);"###;
let config = r#"{
"collapse_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_inner_lvalues() {
let src = r###"var a,
b = 10;
var a = (--b || a || 3).toString(),
c = --b + -a;
console.log(null, a, b);"###;
let config = r#"{
"collapse_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_issue_2298() {
let src = r#"!(function () {
function f() {
var a = undefined;
var undefined = a++;
try {
!(function g(b) {
b[1] = "foo";
})();
console.log("FAIL");
} catch (e) {
console.log("PASS");
}
}
f();
})();"#;
let config = r#"{
"collapse_vars": true,
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_chained_3() {
let src = r###"console.log(
(function (a, b) {
var c = a,
c = b;
b++;
return c;
})(1, 2)
);"###;
let config = r#"{
"collapse_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_collapse_vars_self_reference() {
let src = r###"function f1() {
var self = {
inner: function () {
return self;
},
};
console.log(self)
}
function f2() {
var self = { inner: self };
console.log(self)
}
f1()
f2()"###;
let config = r#"{
"booleans": true,
"collapse_vars": true,
"comparisons": true,
"conditionals": true,
"dead_code": true,
"evaluate": true,
"hoist_funs": true,
"if_return": true,
"join_vars": true,
"keep_fargs": true,
"loops": true,
"properties": true,
"sequences": true,
"side_effects": true,
"unused": false
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_chained_2() {
let src = r###"var a;
var a = 2;
a = 3 / a;
console.log(a);"###;
let config = r#"{
"collapse_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_cond_branch_1() {
let src = r###"function f1(b, c) {
var log = console.log;
var a = ++c;
if (b) b++;
log(a, b);
}
function f2(b, c) {
var log = console.log;
var a = ++c;
b && b++;
log(a, b);
}
function f3(b, c) {
var log = console.log;
var a = ++c;
b ? b++ : b--;
log(a, b);
}
f1(1, 2);
f2(3, 4);
f3(5, 6);"###;
let config = r#"{
"collapse_vars": true,
"sequences": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_var_side_effects_2() {
let src = r#"var print = console.log.bind(console);
function foo(x) {
var twice = x.y * 2;
print("Foo:", twice);
}
foo({ y: 10 });"#;
let config = r#"{
"collapse_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_issue_3032() {
let src = r###"console.log(
{
f: function () {
this.a = 42;
return [this.a, !1];
},
}.f()[0]
);"###;
let config = r#"{
"collapse_vars": true,
"pure_getters": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_var_side_effects_3() {
let src = r#"var print = console.log.bind(console);
function foo(x) {
var twice = x.y * 2;
print("Foo:", twice);
}
foo({ y: 10 });"#;
let config = r#"{
"collapse_vars": true,
"pure_getters": true,
"unsafe": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_collapse_vars_throw() {
let src = r###"var f1 = function (x, y) {
var a,
b,
r = x + y,
q = r * r,
z = q - r;
(a = z), (b = 7);
throw a + b;
};
try {
f1(1, 2);
} catch (e) {
console.log(e);
}"###;
let config = r#"{
"booleans": true,
"collapse_vars": true,
"comparisons": true,
"conditionals": true,
"dead_code": true,
"evaluate": true,
"hoist_funs": true,
"if_return": true,
"join_vars": true,
"keep_fargs": true,
"loops": true,
"properties": true,
"sequences": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_issue_2203_4() {
let src = r#"a = "FAIL";
console.log(
{
a: "PASS",
b: function () {
return ((c) => c.a)((String, Object, (() => this)()));
},
}.b()
);"#;
let config = r#"{
"collapse_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_issue_2203_3() {
let src = r#"a = "FAIL";
console.log(
{
a: "PASS",
b: function () {
return (function (c) {
return c.a;
})((String, Object, (() => this)()));
},
}.b()
);"#;
let config = r#"{
"collapse_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_issue_2187_1() {
let src = r###"var a = 1;
!(function (foo) {
foo();
var a = 2;
console.log(a);
})(function () {
console.log(a);
});"###;
let config = r#"{
"collapse_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_var_defs() {
let src = r#"var f1 = function (x, y) {
var a,
b,
r = x + y,
q = r * r,
z = q - r,
a = z,
b = 7;
console.log(a + b);
};
f1("1", 0);"#;
let config = r#"{
"booleans": true,
"collapse_vars": true,
"comparisons": true,
"conditionals": true,
"dead_code": true,
"evaluate": true,
"hoist_funs": true,
"if_return": true,
"join_vars": true,
"keep_fargs": true,
"loops": true,
"properties": true,
"sequences": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_issue_2203_2() {
let src = r#"a = "PASS";
console.log(
{
a: "FAIL",
b: function () {
return (function (c) {
return c.a;
})(
(String,
Object,
(function () {
return this;
})())
);
},
}.b()
);"#;
let config = r#"{
"collapse_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_collapse_vars_seq() {
let src = r###"var f1 = function (x, y) {
var a,
b,
r = x + y,
q = r * r,
z = q - r;
(a = z), (b = 7);
return a + b;
};
console.log(f1(1, 2));"###;
let config = r#"{
"booleans": true,
"collapse_vars": true,
"comparisons": true,
"conditionals": true,
"dead_code": true,
"evaluate": true,
"hoist_funs": true,
"if_return": true,
"join_vars": true,
"keep_fargs": true,
"loops": true,
"properties": true,
"sequences": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_issue_2319_3() {
let src = r#""use strict";
console.log(
(function (a) {
return a;
})(
!(function () {
return this;
})()
)
);"#;
let config = r#"{
"collapse_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_may_throw_2() {
let src = r###"function f(b) {
try {
var a = x();
++b;
return b(a);
} catch (e) {}
console.log(b);
}
f(0);"###;
let config = r#"{
"collapse_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_issue_2453() {
let src = r###"function log(n) {
console.log(n);
}
const a = 42;
log(a);"###;
let config = r#"{
"collapse_vars": true,
"conditionals": true,
"inline": true,
"join_vars": true,
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"sequences": true,
"side_effects": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_cond_branch_2() {
let src = r###"function f1(b, c) {
var log = console.log;
var a = ++c;
if (b) b += a;
log(a, b);
}
function f2(b, c) {
var log = console.log;
var a = ++c;
b && (b += a);
log(a, b);
}
function f3(b, c) {
var log = console.log;
var a = ++c;
b ? (b += a) : b--;
log(a, b);
}
f1(1, 2);
f2(3, 4);
f3(5, 6);"###;
let config = r#"{
"collapse_vars": true,
"sequences": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_chained_1() {
let src = r###"var a = 2;
var a = 3 / a;
console.log(a);"###;
let config = r#"{
"collapse_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_collapse_vars_reduce_vars_assign() {
let src = r###"!(function () {
var a = 1;
(a = [].length), console.log(a);
})();"###;
let config = r#"{
"collapse_vars": true,
"reduce_funcs": true,
"reduce_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_inline_inline_within_extends_2() {
let src = r#"class Baz extends foo(bar(Array)) {
constructor() {
super(...arguments);
}
}
function foo(foo_base) {
return class extends foo_base {
constructor() {
super(...arguments);
}
second() {
return this[1];
}
};
}
function bar(bar_base) {
return class extends bar_base {
constructor(...args) {
super(...args);
}
};
}
console.log(new Baz(1, "PASS", 3).second());"#;
let config = r#"{
"defaults": true,
"evaluate": true,
"inline": 3,
"passes": 3,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"collapse_vars": false,
"unused": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_evaluate_unsafe_float_key() {
let src = r#"console.log(
{ 2.72: 1 } + 1,
{ 2.72: 1 }[2.72] + 1,
{ 2.72: 1 }["2.72"] + 1,
{ 2.72: 1 }[3.14] + 1,
{ 2.72: 1 }[2.72][3.14] + 1,
{ 2.72: 1 }[2.72]["3.14"] + 1
);"#;
let config = r#"{
"evaluate": true,
"unsafe": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_evaluate_unsafe_float_key_complex() {
let src = r#"console.log(
{ 2.72: { 3.14: 1 }, 3.14: 1 } + 1,
{ 2.72: { 3.14: 1 }, 3.14: 1 }[2.72] + 1,
{ 2.72: { 3.14: 1 }, 3.14: 1 }["2.72"] + 1,
{ 2.72: { 3.14: 1 }, 3.14: 1 }[3.14] + 1,
{ 2.72: { 3.14: 1 }, 3.14: 1 }[2.72][3.14] + 1,
{ 2.72: { 3.14: 1 }, 3.14: 1 }[2.72]["3.14"] + 1
);"#;
let config = r#"{
"evaluate": true,
"unsafe": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_892_dont_mangle_arguments() {
let src = r###"(function () {
var arguments = arguments,
not_arguments = 9;
console.log(not_arguments, arguments);
})(5, 6, 7);"###;
let config = r#"{
"booleans": true,
"comparisons": true,
"conditionals": true,
"dead_code": true,
"drop_debugger": true,
"evaluate": true,
"hoist_funs": true,
"hoist_vars": true,
"if_return": true,
"join_vars": true,
"keep_fargs": true,
"keep_fnames": false,
"loops": true,
"negate_iife": false,
"properties": true,
"sequences": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_issue_t64() {
let src = r#"var obj = {};
obj.Base = class {
constructor() {
this.id = "PASS";
}
};
obj.Derived = class extends obj.Base {
constructor() {
super();
console.log(this.id);
}
};
new obj.Derived();"#;
let config = r#"{
"collapse_vars": true,
"join_vars": true,
"properties": true,
"reduce_vars": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_computed_property() {
let src = r#"console.log({ a: "bar", [console.log("foo")]: 42 }.a);"#;
let config = r#"{
"properties": true,
"side_effects": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_sub_properties() {
let src = r#"const a = {};
a[0] = 0;
a["0"] = 1;
a[3.14] = 2;
a["3" + ".14"] = 3;
a["i" + "f"] = 4;
a["foo" + " bar"] = 5;
a[0 / 0] = 6;
a[null] = 7;
a[undefined] = 8;
console.log(a)"#;
let config = r#"{
"evaluate": true,
"properties": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_dont_mangle_computed_property_2() {
let src = r#"const prop = Symbol("foo");
const obj = {
[prop]: "bar",
baz: 1,
qux: 2,
[3 + 4]: "seven",
0: "zero",
1: "one",
null: "Null",
undefined: "Undefined",
Infinity: "infinity",
NaN: "nan",
void: "Void",
};
console.log(
obj[prop],
obj["baz"],
obj.qux,
obj[7],
obj[0],
obj[1 + 0],
obj[null],
obj[undefined],
obj[1 / 0],
obj[NaN],
obj.void
);
console.log(obj.null, obj.undefined, obj.Infinity, obj.NaN);"#;
let config = r#"{
"defaults": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_prop_side_effects_2() {
let src = r#"var C = 1;
console.log(C);
var obj = {
"": function () {
return C + C;
},
};
console.log(obj[""]());"#;
let config = r#"{
"evaluate": true,
"inline": true,
"passes": 2,
"properties": true,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_join_object_assignments_negative() {
let src = r###"var o = {};
o[0] = 0;
o[-0] = 1;
o[-1] = 2;
console.log(o[0], o[-0], o[-1]);"###;
let config = r#"{
"evaluate": true,
"join_vars": true,
"properties": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_issue_2208_4() {
let src = r###"function foo() {}
console.log(
{
a: foo(),
p: function () {
return 42;
},
}.p()
);"###;
let config = r#"{
"inline": true,
"properties": true,
"side_effects": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_issue_869_1() {
let src = r#"var o = { p: "FAIL" };
Object.defineProperty(o, "p", {
get: function () {
return "PASS";
},
});
console.log(o.p);"#;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_join_object_assignments_undefined_2() {
let src = r###"var o = {};
o[undefined] = 1;
console.log(o[undefined]);"###;
let config = r#"{
"evaluate": true,
"join_vars": true,
"properties": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_issue_2208_5() {
let src = r#"console.log(
{
p: "FAIL",
p: function () {
return 42;
},
}.p()
);"#;
let config = r#"{
"inline": true,
"properties": true,
"side_effects": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_issue_2513() {
let src = r#"!(function (Infinity, NaN, undefined) {
console.log("a"[1 / 0], "b"["Infinity"]);
console.log("c"[0 / 0], "d"["NaN"]);
console.log("e"[void 0], "f"["undefined"]);
})(0, 0, 0);"#;
let config = r#"{
"evaluate": true,
"properties": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_join_object_assignments_return_1() {
let src = r#"console.log(
(function () {
var o = { p: 3 };
return (o.q = "foo");
})()
);"#;
let config = r#"{
"join_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_issue_2816_ecma6() {
let src = r#""use strict";
var o = { a: 1 };
o.b = 2;
o.a = 3;
o.c = 4;
console.log(o.a, o.b, o.c);"#;
let config = r#"{
"ecma": "6",
"join_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_join_object_assignments_1() {
let src = r#"console.log(
(function () {
var x = { a: 1, c: (console.log("c"), "C") };
x.b = 2;
(x[3] = function () {
console.log(x);
}),
(x["a"] = /foo/),
(x.bar = x);
return x;
})()
);"#;
let config = r#"{
"evaluate": true,
"join_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_dont_mangle_computed_property_1() {
let src = r#""AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
"BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
"CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC";
const prop = Symbol("foo");
const obj = {
[prop]: "bar",
baz: 1,
qux: 2,
[3 + 4]: "seven",
0: "zero",
1: "one",
null: "Null",
undefined: "Undefined",
Infinity: "infinity",
NaN: "nan",
void: "Void",
};
console.log(
obj[prop],
obj["baz"],
obj.qux,
obj[7],
obj[0],
obj[1 + 0],
obj[null],
obj[undefined],
obj[1 / 0],
obj[NaN],
obj.void
);
console.log(obj.null, obj.undefined, obj.Infinity, obj.NaN);"#;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_join_object_assignments_if() {
let src = r#"console.log(
(function () {
var o = {};
if ((o.a = "PASS")) return o.a;
})()
);"#;
let config = r#"{
"join_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_join_object_assignments_nan_2() {
let src = r###"var o = {};
o[NaN] = 1;
o[0 / 0] = 2;
console.log(o[NaN], o[NaN]);"###;
let config = r#"{
"evaluate": true,
"join_vars": true,
"properties": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_prop_side_effects_1() {
let src = r###"var C = 1;
console.log(C);
var obj = {
bar: function () {
return C + C;
},
};
console.log(obj.bar());"###;
let config = r#"{
"evaluate": true,
"inline": true,
"properties": true,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_join_object_assignments_null_1() {
let src = r###"var o = {};
o[null] = 1;
console.log(o[null]);"###;
let config = r#"{
"evaluate": true,
"join_vars": true,
"properties": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_issue_2208_7() {
let src = r###"console.log(
{
p() {
return 42;
},
}.p()
);"###;
let config = r#"{
"ecma": 2015,
"inline": true,
"properties": true,
"side_effects": true,
"unsafe_arrows": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_issue_869_2() {
let src = r#"var o = { p: "FAIL" };
Object.defineProperties(o, {
p: {
get: function () {
return "PASS";
},
},
});
console.log(o.p);"#;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_issue_2208_9() {
let src = r###"a = 42;
console.log(
{
p: () =>
(function () {
return this.a;
})(),
}.p()
);"###;
let config = r#"{
"inline": true,
"properties": true,
"side_effects": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_join_object_assignments_undefined_1() {
let src = r###"var o = {};
o[undefined] = 1;
console.log(o[undefined]);"###;
let config = r#"{
"join_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_join_object_assignments_forin() {
let src = r#"console.log(
(function () {
var o = {};
for (var a in ((o.a = "PASS"), o)) return o[a];
})()
);"#;
let config = r#"{
"join_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_join_object_assignments_void_0() {
let src = r###"var o = {};
o[void 0] = 1;
console.log(o[void 0]);"###;
let config = r#"{
"evaluate": true,
"join_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_join_object_assignments_return_2() {
let src = r#"console.log(
(function () {
var o = { p: 3 };
return (o.q = /foo/), (o.r = "bar");
})()
);"#;
let config = r#"{
"join_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_join_object_assignments_regex() {
let src = r###"var o = {};
o[/rx/] = 1;
console.log(o[/rx/]);"###;
let config = r#"{
"evaluate": true,
"join_vars": true,
"properties": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_join_object_assignments_2() {
let src = r###"var o = { foo: 1 };
o.bar = 2;
o.baz = 3;
console.log(o.foo, o.bar + o.bar, o.foo * o.bar * o.baz);"###;
let config = r#"{
"evaluate": true,
"hoist_props": true,
"join_vars": true,
"passes": 3,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_properties_join_object_assignments_return_3() {
let src = r#"console.log(
(function () {
var o = { p: 3 };
return (o.q = "foo"), (o.p += ""), console.log(o.q), o.p;
})()
);"#;
let config = r#"{
"join_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_1321_issue_1321_no_debug() {
let src = r#"var x = {};
x.foo = 1;
x["a"] = 2 * x.foo;
console.log(x.foo, x["a"]);"#;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_1321_issue_1321_with_quoted() {
let src = r#"var x = {};
x.foo = 1;
x["a"] = 2 * x.foo;
console.log(x.foo, x["a"]);"#;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_1321_issue_1321_debug() {
let src = r#"var x = {};
x.foo = 1;
x["_$foo$_"] = 2 * x.foo;
console.log(x.foo, x["_$foo$_"]);"#;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_976_eval_collapse_vars() {
let src = r#"function f1() {
var e = 7;
var s = "abcdef";
var i = 2;
var eval = console.log.bind(console);
var x = s.charAt(i++);
var y = s.charAt(i++);
var z = s.charAt(i++);
eval(x, y, z, e);
}
function p1() {
var a = foo(),
b = bar(),
eval = baz();
return a + b + eval;
}
function p2() {
var a = foo(),
b = bar(),
eval = baz;
return a + b + eval();
}
(function f2(eval) {
var a = 2;
console.log(a - 5);
eval("console.log(a);");
})(eval);"#;
let config = r#"{
"booleans": true,
"collapse_vars": true,
"comparisons": true,
"conditionals": true,
"dead_code": true,
"evaluate": true,
"hoist_funs": true,
"if_return": true,
"join_vars": true,
"keep_fargs": true,
"loops": true,
"properties": true,
"sequences": false,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_array_constructor_unsafe() {
let src = r#"const foo = 'string'
console.log(new Array());
console.log(new Array(0));
console.log(new Array(1));
console.log(new Array(11));
console.log(Array(11));
console.log(new Array(12));
console.log(Array(12));
console.log(new Array(foo));
console.log(Array(foo));
console.log(new Array("foo"));
console.log(Array("foo"));"#;
let config = r#"{
"unsafe": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_sequences_forin() {
let src = r#"var o = [];
o.push("PASS");
for (var a in o) console.log(o[a]);"#;
let config = r#"{
"sequences": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_sequences_for_init_var() {
let src = r#"var a = "PASS";
(function () {
var b = 42;
for (var c = 5; c > 0; ) c--;
a = "FAIL";
var a;
})();
console.log(a);"#;
let config = r#"{
"join_vars": true,
"unused": false
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_sequences_func_def_1() {
let src = r###"function f() {
return (f = 0), !!f;
}
console.log(f());"###;
let config = r#"{
"collapse_vars": true,
"side_effects": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_1639_issue_1639_1() {
let src = r###"var a = 100,
b = 10;
var L1 = 5;
while (--L1 > 0) {
if ((--b, false)) {
if (b) {
var ignore = 0;
}
}
}
console.log(a, b);"###;
let config = r#"{
"booleans": true,
"collapse_vars": true,
"conditionals": true,
"evaluate": true,
"join_vars": true,
"loops": true,
"sequences": true,
"side_effects": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_1639_issue_1639_2() {
let src = r###"var a = 100,
b = 10;
function f19() {
if ((++a, false)) if (a) if (++a);
}
f19();
console.log(a, b);"###;
let config = r#"{
"booleans": true,
"collapse_vars": true,
"conditionals": true,
"evaluate": true,
"join_vars": true,
"sequences": true,
"side_effects": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_arrays_for_loop() {
let src = r###"function f0() {
var a = [1, 2, 3];
var b = 0;
for (var i = 0; i < a.length; i++) b += a[i];
return b;
}
function f1() {
var a = [1, 2, 3];
var b = 0;
for (var i = 0, len = a.length; i < len; i++) b += a[i];
return b;
}
function f2() {
var a = [1, 2, 3];
for (var i = 0; i < a.length; i++) a[i]++;
return a[2];
}
console.log(f0(), f1(), f2());"###;
let config = r#"{
"evaluate": true,
"reduce_funcs": true,
"reduce_vars": true,
"unsafe": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_keep_quoted_strict_keep_quoted_strict() {
let src = r#"var propa = 1;
var a = {
propa,
get propb() {
return 2;
},
propc: 3,
get propd() {
return 4;
},
};
var b = {
propa: 5,
get propb() {
return 6;
},
propc: 7,
get propd() {
return 8;
},
};
var c = {};
Object.defineProperty(c, "propa", { value: 9 });
Object.defineProperty(c, "propc", { value: 10 });
console.log(a.propa, a.propb, a.propc, a["propc"], a.propd, a["propd"]);
console.log(b["propa"], b["propb"], b.propc, b["propc"], b.propd, b["propd"]);
console.log(c.propa, c["propc"]);"#;
let config = r#"{
"evaluate": true,
"properties": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_switch_issue_1663() {
let src = r###"var a = 100,
b = 10;
function f() {
switch (1) {
case 1:
b = a++;
return ++b;
default:
var b;
}
}
f();
console.log(a, b);"###;
let config = r#"{
"dead_code": true,
"evaluate": true,
"side_effects": true,
"switches": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_2107() {
let src = r###"var c = 0;
!(function () {
c++;
})(
c++ +
new (function () {
this.a = 0;
var a = (c = c + 1) + (c = 1 + c);
return c++ + a;
})()
);
console.log(c);"###;
let config = r#"{
"collapse_vars": true,
"inline": true,
"passes": 3,
"sequences": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_2630_5() {
let src = r###"var c = 1;
!(function () {
do {
c *= 10;
} while (f());
function f() {
return (function () {
return (c = 2 + c) < 100;
})((c = c + 3));
}
})();
console.log(c);"###;
let config = r#"{
"collapse_vars": true,
"inline": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_2630_2() {
let src = r###"var c = 0;
!(function () {
while (f()) {}
function f() {
var not_used = (function () {
c = 1 + c;
})((c = c + 1));
}
})();
console.log(c);"###;
let config = r#"{
"collapse_vars": true,
"inline": true,
"passes": 2,
"reduce_vars": true,
"sequences": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_2101() {
let src = r###"a = {};
console.log(
(function () {
return (function () {
return this.a;
})();
})() ===
(function () {
return a;
})()
);"###;
let config = r#"{
"inline": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_2630_3() {
let src = r###"var x = 2,
a = 1;
(function () {
function f1(a) {
f2();
--x >= 0 && f1({});
}
f1(a++);
function f2() {
a++;
}
})();
console.log(a);"###;
let config = r#"{
"inline": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_2630_4() {
let src = r###"var x = 3,
a = 1,
b = 2;
(function () {
(function f1() {
while (--x >= 0 && f2());
})();
function f2() {
a++ + (b += a);
}
})();
console.log(a);"###;
let config = r#"{
"collapse_vars": true,
"inline": true,
"reduce_vars": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_1841_2() {
let src = r#"var b = 10;
!(function (arg) {
for (var key in "hi") var n = arg.baz, n = [(b = 42)];
})(--b);
console.log(b);"#;
let config = r#"{
"keep_fargs": false,
"pure_getters": false,
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_t131a() {
let src = r###"(function () {
function thing() {
return { a: 1 };
}
function one() {
return thing();
}
function two() {
var x = thing();
x.a = 2;
x.b = 3;
return x;
}
console.log(JSON.stringify(one()), JSON.stringify(two()));
})();"###;
let config = r#"{
"inline": 1,
"join_vars": true,
"reduce_vars": true,
"side_effects": true,
"passes": 2,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_unsafe_apply_1() {
let src = r#"(function (a, b) {
console.log(a, b);
}.apply("foo", ["bar"]));
(function (a, b) {
console.log(this, a, b);
}.apply("foo", ["bar"]));
(function (a, b) {
console.log(a, b);
}.apply("foo", ["bar"], "baz"));"#;
let config = r#"{
"inline": true,
"passes": 2,
"reduce_vars": true,
"side_effects": true,
"unsafe": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_2898() {
let src = r###"var c = 0;
(function () {
while (f());
function f() {
var b = ((c = 1 + c), void (c = 1 + c));
b && b[0];
}
})();
console.log(c);"###;
let config = r#"{
"collapse_vars": true,
"inline": true,
"reduce_vars": true,
"sequences": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_inline_1() {
let src = r###"(function () {
console.log(1);
})();
(function (a) {
console.log(a);
})(2);
(function (b) {
var c = b;
console.log(c);
})(3);"###;
let config = r#"{
"inline": 1,
"side_effects": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_3125() {
let src = r#"console.log(
function () {
return "PASS";
}.call()
);"#;
let config = r#"{
"inline": true,
"unsafe": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_3016_2() {
let src = r###"var b = 1;
do {
(function (a) {
return a[b];
try {
a = 2;
} catch (a) {
var a;
}
})(3);
} while (0);
console.log(b);"###;
let config = r#"{
"dead_code": true,
"inline": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_2531_1() {
let src = r#"function outer() {
function inner(value) {
function closure() {
return value;
}
return function () {
return closure();
};
}
return inner("Hello");
}
console.log("Greeting:", outer()());"#;
let config = r#"{
"evaluate": true,
"inline": true,
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_use_before_init_in_loop() {
let src = r#"var a = "PASS";
for (var b = 2; --b >= 0; )
(function () {
var c = (function () {
return 1;
})(c && (a = "FAIL"));
})();
console.log(a);"#;
let config = r#"{
"inline": true,
"side_effects": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_unsafe_apply_expansion_2() {
let src = r###"var values = [2, 3];
console.log.apply(console, [1, ...values, 4]);"###;
let config = r#"{
"unsafe": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_2663_2() {
let src = r###"(function () {
var i;
function fn(j) {
return (function () {
console.log(j);
})();
}
for (i in { a: 1, b: 2, c: 3 }) fn(i);
})();"###;
let config = r#"{
"inline": true,
"reduce_vars": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_unsafe_call_3() {
let src = r#"console.log(
function () {
return arguments[0] + eval("arguments")[1];
}.call(0, 1, 2)
);"#;
let config = r#"{
"side_effects": true,
"unsafe": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_unsafe_call_expansion_1() {
let src = r###"(function (...a) {
console.log(...a);
}.call(console, 1, ...[2, 3], 4));"###;
let config = r#"{
"unsafe": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_2630_1() {
let src = r###"var c = 0;
(function () {
while (f());
function f() {
var a = (function () {
var b = c++,
d = (c = 1 + c);
})();
}
})();
console.log(c);"###;
let config = r#"{
"collapse_vars": true,
"inline": true,
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"sequences": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_203() {
let src = r#"var m = {};
var fn = Function("require", "module", "exports", "module.exports = 42;");
fn(null, m, m.exports);
console.log(m.exports);"#;
let config = r#"{
"keep_fargs": false,
"side_effects": true,
"unsafe_Function": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_2842() {
let src = r###"(function () {
function inlinedFunction(data) {
return data[data[0]];
}
function testMinify() {
if (true) {
const data = inlinedFunction([1, 2, 3]);
console.log(data);
}
}
return testMinify();
})();"###;
let config = r#"{
"side_effects": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_1841_1() {
let src = r#"var b = 10;
!(function (arg) {
for (var key in "hi") var n = arg.baz, n = [(b = 42)];
})(--b);
console.log(b);"#;
let config = r#"{
"keep_fargs": false,
"pure_getters": "strict",
"reduce_funcs": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_2476() {
let src = r###"function foo(x, y, z) {
return x < y ? x * y + z : x * z - y;
}
for (var sum = 0, i = 0; i < 10; i++) sum += foo(i, i + 1, 3 * i);
console.log(sum);"###;
let config = r#"{
"inline": true,
"reduce_vars": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_t131b() {
let src = r###"(function () {
function thing() {
return { a: 1 };
}
function one() {
return thing();
}
function two() {
var x = thing();
x.a = 2;
x.b = 3;
return x;
}
console.log(JSON.stringify(one()), JSON.stringify(two()));
})();"###;
let config = r#"{
"defaults": true,
"passes": 2
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_inline_2() {
let src = r###"(function () {
console.log(1);
})();
(function (a) {
console.log(a);
})(2);
(function (b) {
var c = b;
console.log(c);
})(3);"###;
let config = r#"{
"inline": 2,
"side_effects": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_2531_3() {
let src = r#"function outer() {
function inner(value) {
function closure() {
return value;
}
return function () {
return closure();
};
}
return inner("Hello");
}
console.log("Greeting:", outer()());"#;
let config = r#"{
"evaluate": true,
"inline": true,
"passes": 3,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_inline_3() {
let src = r###"(function () {
console.log(1);
})();
(function (a) {
console.log(a);
})(2);
(function (b) {
var c = b;
console.log(c);
})(3);"###;
let config = r#"{
"inline": 3,
"side_effects": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_2657() {
let src = r#""use strict";
console.log(
(function f() {
return h;
function g(b) {
return b || b();
}
function h(a) {
g(a);
return a;
}
})()(42)
);"#;
let config = r#"{
"inline": true,
"reduce_vars": true,
"sequences": true,
"passes": 2,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_unsafe_apply_expansion_1() {
let src = r###"console.log.apply(console, [1, ...[2, 3], 4]);"###;
let config = r#"{
"unsafe": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_3016_1() {
let src = r###"var b = 1;
do {
(function (a) {
return a[b];
var a;
})(3);
} while (0);
console.log(b);"###;
let config = r#"{
"inline": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_2531_2() {
let src = r#"function outer() {
function inner(value) {
function closure() {
return value;
}
return function () {
return closure();
};
}
return inner("Hello");
}
console.log("Greeting:", outer()());"#;
let config = r#"{
"evaluate": true,
"inline": true,
"passes": 3,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_unsafe_call_expansion_2() {
let src = r###"var values = [2, 3];
(function (...a) {
console.log(...a);
}.call(console, 1, ...values, 4));"###;
let config = r#"{
"unsafe": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_issue_2783() {
let src = r#"(function () {
return g;
function f(a) {
var b = a.b;
if (b) return b;
return a;
}
function g(o, i) {
while (i--) {
console.log(f(o));
}
}
})()({ b: "PASS" }, 1);"#;
let config = r#"{
"collapse_vars": true,
"conditionals": true,
"if_return": true,
"inline": true,
"reduce_vars": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_functions_unsafe_call_1() {
let src = r#"(function (a, b) {
console.log(a, b);
}.call("foo", "bar"));
(function (a, b) {
console.log(this, a, b);
}.call("foo", "bar"));"#;
let config = r#"{
"inline": true,
"passes": 2,
"reduce_vars": true,
"side_effects": true,
"unsafe": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_1466_different_variable_in_multiple_for_of() {
let src = r#"var test = ["a", "b", "c"];
for (let tmp of test) {
console.log(tmp);
let dd;
dd = ["e", "f", "g"];
for (let t of dd) {
console.log(t);
}
}"#;
let config = r#"{
"hoist_funs": true,
"dead_code": true,
"conditionals": true,
"comparisons": true,
"evaluate": true,
"booleans": true,
"loops": true,
"unused": true,
"keep_fargs": true,
"if_return": true,
"join_vars": true,
"side_effects": true,
"collapse_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_1466_same_variable_in_multiple_for_of() {
let src = r#"var test = ["a", "b", "c"];
for (let tmp of test) {
console.log(tmp);
let dd;
dd = ["e", "f", "g"];
for (let tmp of dd) {
console.log(tmp);
}
}"#;
let config = r#"{
"hoist_funs": true,
"dead_code": true,
"conditionals": true,
"comparisons": true,
"evaluate": true,
"booleans": true,
"loops": true,
"unused": true,
"keep_fargs": true,
"if_return": true,
"join_vars": true,
"side_effects": true,
"collapse_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_1466_same_variable_in_multiple_for_of_sequences_let() {
let src = r#"var test = ["a", "b", "c"];
for (let tmp of test) {
console.log(tmp);
let dd;
dd = ["e", "f", "g"];
for (let tmp of dd) {
console.log(tmp);
}
}"#;
let config = r#"{
"hoist_funs": true,
"dead_code": true,
"conditionals": true,
"comparisons": true,
"evaluate": true,
"booleans": true,
"loops": true,
"unused": true,
"keep_fargs": true,
"if_return": true,
"join_vars": true,
"sequences": true,
"side_effects": true,
"collapse_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_1466_same_variable_in_multiple_for_in_sequences_const() {
let src = r#"var test = ["a", "b", "c"];
for (const tmp in test) {
console.log(tmp);
let dd;
dd = ["e", "f", "g"];
for (const tmp in test) {
console.log(tmp);
}
}"#;
let config = r#"{
"hoist_funs": true,
"dead_code": true,
"conditionals": true,
"comparisons": true,
"evaluate": true,
"booleans": true,
"loops": true,
"unused": false,
"keep_fargs": true,
"if_return": true,
"join_vars": true,
"sequences": true,
"side_effects": true,
"collapse_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_1466_more_variable_in_multiple_for() {
let src = r###"for (let a = 9, i = 0; i < 20; i += a) {
let b = a++ + i;
console.log(a, b, i);
for (let k = b, m = b * b, i = 0; i < 10; i++) {
console.log(a, b, m, k, i);
}
}"###;
let config = r#"{
"hoist_funs": true,
"dead_code": true,
"conditionals": true,
"comparisons": true,
"evaluate": true,
"booleans": true,
"loops": true,
"unused": false,
"keep_fargs": true,
"if_return": true,
"join_vars": true,
"side_effects": true,
"collapse_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_1466_different_variable_in_multiple_for_in() {
let src = r#"var test = ["a", "b", "c"];
for (let tmp in test) {
console.log(tmp);
let dd;
dd = ["e", "f", "g"];
for (let t in test) {
console.log(t);
}
}"#;
let config = r#"{
"hoist_funs": true,
"dead_code": true,
"conditionals": true,
"comparisons": true,
"evaluate": true,
"booleans": true,
"loops": true,
"unused": false,
"keep_fargs": true,
"if_return": true,
"join_vars": true,
"side_effects": true,
"collapse_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_1466_same_variable_in_multiple_for_in() {
let src = r#"var test = ["a", "b", "c"];
for (let tmp in test) {
console.log(tmp);
let dd;
dd = ["e", "f", "g"];
for (let tmp in test) {
console.log(tmp);
}
}"#;
let config = r#"{
"hoist_funs": true,
"dead_code": true,
"conditionals": true,
"comparisons": true,
"evaluate": true,
"booleans": true,
"loops": true,
"unused": false,
"keep_fargs": true,
"if_return": true,
"join_vars": true,
"side_effects": true,
"collapse_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_1466_same_variable_in_multiple_for_in_sequences_let() {
let src = r#"var test = ["a", "b", "c"];
for (let tmp in test) {
console.log(tmp);
let dd;
dd = ["e", "f", "g"];
for (let tmp in test) {
console.log(tmp);
}
}"#;
let config = r#"{
"hoist_funs": true,
"dead_code": true,
"conditionals": true,
"comparisons": true,
"evaluate": true,
"booleans": true,
"loops": true,
"unused": false,
"keep_fargs": true,
"if_return": true,
"join_vars": true,
"sequences": true,
"side_effects": true,
"collapse_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_1466_same_variable_in_multiple_for_of_sequences_const() {
let src = r#"var test = ["a", "b", "c"];
for (const tmp of test) {
console.log(tmp);
let dd;
dd = ["e", "f", "g"];
for (const tmp of dd) {
console.log(tmp);
}
}"#;
let config = r#"{
"hoist_funs": true,
"dead_code": true,
"conditionals": true,
"comparisons": true,
"evaluate": true,
"booleans": true,
"loops": true,
"unused": true,
"keep_fargs": true,
"if_return": true,
"join_vars": true,
"sequences": true,
"side_effects": true,
"collapse_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_747_dont_reuse_prop() {
let src = r#""aaaaaaaaaabbbbb";
var obj = {};
obj.a = 123;
obj.asd = 256;
console.log(obj.a);"#;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_747_unmangleable_props_should_always_be_reserved() {
let src = r#""aaaaaaaaaabbbbb";
var obj = {};
obj.asd = 256;
obj.a = 123;
console.log(obj.a);"#;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn terser_loops_issue_2740_7() {
let src = r###"let a = 9,
b = 0;
for (const a = 1; a < 3; ++b) break;
console.log(a, b);"###;
let config = r#"{
"dead_code": true,
"loops": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_loops_issue_2740_8() {
let src = r###"var a = 9,
b = 0;
for (const a = 1; a < 3; ++b) break;
console.log(a, b);"###;
let config = r#"{
"dead_code": true,
"loops": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_loops_issue_2740_6() {
let src = r###"const a = 9,
b = 0;
for (const a = 1; a < 3; ++b) break;
console.log(a, b);"###;
let config = r#"{
"dead_code": true,
"loops": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_loops_issue_2740_3() {
let src = r###"L1: for (var x = 0; x < 3; x++) {
L2: for (var y = 0; y < 2; y++) {
break L1;
}
}
console.log(x, y);"###;
let config = r#"{
"dead_code": true,
"loops": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_loops_issue_2740_4() {
let src = r###"L1: for (var x = 0; x < 3; x++) {
L2: for (var y = 0; y < 2; y++) {
break L2;
}
}
console.log(x, y);"###;
let config = r#"{
"dead_code": true,
"loops": true,
"passes": 2
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_loops_issue_2740_5() {
let src = r###"L1: for (var x = 0; x < 3; x++) {
break L1;
L2: for (var y = 0; y < 2; y++) {
break L2;
}
}
console.log(x, y);"###;
let config = r#"{
"dead_code": true,
"loops": true,
"passes": 2
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_rename_function_iife_catch() {
let src = r###"function f(n) {
!(function () {
try {
throw 0;
} catch (n) {
var a = 1;
console.log(n, a);
}
})();
}
f();"###;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn terser_rename_mangle_catch_var() {
let src = r#"var a = "FAIL";
try {
throw 1;
} catch (args) {
var a = "PASS";
}
console.log(a);"#;
let config = r#"{
"ie8": false,
"toplevel": false
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_negate_iife_issue_1254_negate_iife_true() {
let src = r#"(function () {
return function () {
console.log("test");
};
})()();"#;
let config = r#"{
"negate_iife": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_try_catch_catch_destructuring_with_sequence() {
let src = r###"try {
throw {};
} catch ({ xCover = (0, function () { }) }) {
console.log(typeof xCover)
}"###;
let config = r###"{}"###;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_281_pure_annotation_1() {
let src = r#"(function () {
console.log("hello");
})();"#;
let config = r#"{
"inline": true,
"side_effects": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_281_keep_fargs() {
let src = r###"var a = 1;
!(function (a_1) {
a++;
})(a++ + (a && a.var));
console.log(a);"###;
let config = r#"{
"collapse_vars": true,
"inline": true,
"keep_fargs": true,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_281_drop_fargs() {
let src = r###"var a = 1;
!(function (a_1) {
a++;
})(a++ + (a && a.var));
console.log(a);"###;
let config = r#"{
"collapse_vars": true,
"inline": true,
"keep_fargs": false,
"side_effects": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_issue_281_pure_annotation_2() {
let src = r#"(function (n) {
console.log("hello", n);
})(42);"#;
let config = r#"{
"collapse_vars": true,
"inline": true,
"side_effects": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_arguments_duplicate_parameter_with_arguments() {
let src = r#"(function (a, a) {
console.log((a = "foo"), arguments[0]);
})("baz", "Bar");"#;
let config = r#"{
"arguments": true,
"defaults": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_arguments_destructuring_1() {
let src = r#"(function (a, { d: d }) {
console.log((a = "foo"), arguments[0]);
})("baz", { d: "Bar" });"#;
let config = r#"{
"arguments": true,
"defaults": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_arguments_destructuring_2() {
let src = r#"(function ({ d: d }, a) {
console.log((a = "foo"), arguments[0].d);
})({ d: "Bar" }, "baz");"#;
let config = r#"{
"arguments": true,
"defaults": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_arguments_modified_strict() {
let src = r#""use strict";
(function (a, b) {
var c = arguments[0];
var d = arguments[1];
var a = "foo";
b++;
arguments[0] = "moo";
arguments[1] *= 2;
console.log(a, b, c, d, arguments[0], arguments[1]);
})("bar", 42);"#;
let config = r#"{
"arguments": true,
"reduce_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_arguments_replace_index() {
let src = r#"var arguments = [];
console.log(arguments[0]);
(function () {
console.log(arguments[1], arguments["1"], arguments["foo"]);
})("bar", 42);
(function (a, b) {
console.log(arguments[1], arguments["1"], arguments["foo"]);
})("bar", 42);
(function (arguments) {
console.log(arguments[1], arguments["1"], arguments["foo"]);
})("bar", 42);
(function () {
var arguments;
console.log(arguments[1], arguments["1"], arguments["foo"]);
})("bar", 42);"#;
let config = r#"{
"arguments": true,
"evaluate": true,
"properties": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_arguments_modified() {
let src = r#"(function (a, b) {
var c = arguments[0];
var d = arguments[1];
var a = "foo";
b++;
arguments[0] = "moo";
arguments[1] *= 2;
console.log(a, b, c, d, arguments[0], arguments[1]);
})("bar", 42);"#;
let config = r#"{
"arguments": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_arguments_replace_index_strict() {
let src = r#""use strict";
(function () {
console.log(arguments[1], arguments["1"], arguments["foo"]);
})("bar", 42);
(function (a, b) {
console.log(arguments[1], arguments["1"], arguments["foo"]);
})("bar", 42);"#;
let config = r#"{
"arguments": true,
"evaluate": true,
"properties": true,
"reduce_vars": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_arguments_issue_687() {
let src = r###"function shouldBePure() {
return arguments.length;
}
console.log(shouldBePure())"###;
let config = r#"{
"defaults": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_arguments_replace_index_keep_fargs() {
let src = r#"var arguments = [];
console.log(arguments[0]);
(function () {
console.log(arguments[1], arguments["1"], arguments["foo"]);
})("bar", 42);
(function (a, b) {
console.log(arguments[1], arguments["1"], arguments["foo"]);
})("bar", 42);
(function (arguments) {
console.log(arguments[1], arguments["1"], arguments["foo"]);
})("bar", 42);
(function () {
var arguments;
console.log(arguments[1], arguments["1"], arguments["foo"]);
})("bar", 42);"#;
let config = r#"{
"arguments": true,
"evaluate": true,
"keep_fargs": false,
"properties": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_typeof_issue_2728_3() {
let src = r###"(function () {
function arguments() {}
console.log(typeof arguments);
})();"###;
let config = r#"{
"evaluate": true,
"reduce_vars": true,
"typeofs": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_typeof_issue_2728_4() {
let src = r###"function arguments() {}
console.log(typeof arguments);"###;
let config = r#"{
"evaluate": true,
"reduce_vars": true,
"toplevel": true,
"typeofs": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_typeof_typeof_defun_1() {
let src = r#"function f() {
console.log("YES");
}
function g() {
h = 42;
console.log("NOPE");
}
function h() {
console.log("YUP");
}
g = 42;
"function" == typeof f && f();
"function" == typeof g && g();
"function" == typeof h && h();"#;
let config = r#"{
"evaluate": true,
"inline": true,
"passes": 2,
"reduce_vars": true,
"side_effects": true,
"toplevel": true,
"typeofs": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
#[ignore]
fn terser_pure_funcs_issue_3065_4() {
let src = r#"var debug = function (msg) {
console.log(msg);
};
debug(
(function () {
console.log("PASS");
return "FAIL";
})()
);"#;
let config = r#"{
"pure_funcs": ["debug"],
"reduce_vars": true,
"side_effects": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
#[ignore]
fn terser_pure_funcs_issue_3065_3() {
let src = r#"function debug(msg) {
console.log(msg);
}
debug(
(function () {
console.log("PASS");
return "FAIL";
})()
);"#;
let config = r#"{
"pure_funcs": ["debug"],
"reduce_vars": true,
"side_effects": true,
"toplevel": true,
"unused": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn issues_vercel_ms_1() {
let src = r#"const s = 1000;
const m = s * 60;
const h = m * 60;
const d = h * 24;
const w = d * 7;
const y = d * 365.25;
function ms(value, options) {
try {
if (typeof value === "string" && value.length > 0) {
return parse(value);
} else if (typeof value === "number" && isFinite(value)) {
return options?.long ? fmtLong(value) : fmtShort(value);
}
throw new Error("Value is not a string or number.");
} catch (error) {
const message = isError(error) ? `${error.message}. value=${JSON.stringify(value)}` : "An unknown error has occured.";
throw new Error(message);
}
}
function parse(str) {
str = String(str);
if (str.length > 100) {
throw new Error("Value exceeds the maximum length of 100 characters.");
}
const match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);
if (!match) {
return NaN;
}
const n = parseFloat(match[1]);
const type = (match[2] || "ms").toLowerCase();
switch (type) {
case "years":
case "year":
case "yrs":
case "yr":
case "y":
return n * y;
case "weeks":
case "week":
case "w":
return n * w;
case "days":
case "day":
case "d":
return n * d;
case "hours":
case "hour":
case "hrs":
case "hr":
case "h":
return n * h;
case "minutes":
case "minute":
case "mins":
case "min":
case "m":
return n * m;
case "seconds":
case "second":
case "secs":
case "sec":
case "s":
return n * s;
case "milliseconds":
case "millisecond":
case "msecs":
case "msec":
case "ms":
return n;
default:
throw new Error(`The unit ${type} was matched, but no matching case exists.`);
}
}
function fmtShort(ms) {
const msAbs = Math.abs(ms);
if (msAbs >= d) {
return `${Math.round(ms / d)}d`;
}
if (msAbs >= h) {
return `${Math.round(ms / h)}h`;
}
if (msAbs >= m) {
return `${Math.round(ms / m)}m`;
}
if (msAbs >= s) {
return `${Math.round(ms / s)}s`;
}
return `${ms}ms`;
}
function fmtLong(ms) {
const msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, "day");
}
if (msAbs >= h) {
return plural(ms, msAbs, h, "hour");
}
if (msAbs >= m) {
return plural(ms, msAbs, m, "minute");
}
if (msAbs >= s) {
return plural(ms, msAbs, s, "second");
}
return `${ms} ms`;
}
function plural(ms, msAbs, n, name) {
const isPlural = msAbs >= n * 1.5;
return `${Math.round(ms / n)} ${name}${isPlural ? "s" : ""}`;
}
function isError(error) {
return typeof error === "object" && error !== null && "message" in error;
}
console.log(ms(123))
console.log(ms('123day'))
console.log(ms(12321341234217))
console.log(ms(12321341234217))
console.log(ms(12321341234217))
console.log(ms(12321341234217))
console.log(ms(12321341234217))
console.log(ms(12321341234217))
console.log(ms(12321341234217))"#;
let config = r#"{
"defaults": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn issues_2011_1() {
let src = r###"class ClassA {
constructor() {
console.log('Class A');
}
}
const cls = class ClassB {
static MyA = ClassA;
constructor() {
console.log('Claas B');
}
it() {
console.log('method it - start');
this.bb = new ClassB.MyA();
console.log('method it - end');
}
}
new cls().it();"###;
let config = r#"{
"defaults": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn issues_2011_2() {
let src = r#"function _class_call_check(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _create_class(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _define_property(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
var ClassA = function ClassA() {
"use strict";
_class_call_check(this, ClassA);
console.log('Class A');
};
var cls = function () {
var ClassB = /*#__PURE__*/ function () {
"use strict";
function ClassB() {
_class_call_check(this, ClassB);
console.log('Claas B');
}
_create_class(ClassB, [
{
key: "it",
value: function it() {
console.log('method it - start');
this.bb = new ClassB.MyA();
console.log('method it - end');
}
}
]);
return ClassB;
}();
_define_property(ClassB, "MyA", ClassA);
return ClassB;
}();
new cls().it();"#;
let config = r#"{
"defaults": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn murmur2_1() {
let src = r#"function murmur2(str) {
// 'm' and 'r' are mixing constants generated offline.
// They're not really 'magic', they just happen to work well.
// const m = 0x5bd1e995;
// const r = 24;
// Initialize the hash
var h = 0; // Mix 4 bytes at a time into the hash
var k,
i = 0,
len = str.length;
for (; len >= 4; ++i, len -= 4) {
k = str.charCodeAt(i) & 0xff | (str.charCodeAt(++i) & 0xff) << 8 | (str.charCodeAt(++i) & 0xff) << 16 | (str.charCodeAt(++i) & 0xff) << 24;
k =
/* Math.imul(k, m): */
(k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16);
k ^=
/* k >>> r: */
k >>> 24;
h =
/* Math.imul(k, m): */
(k & 0xffff) * 0x5bd1e995 + ((k >>> 16) * 0xe995 << 16) ^
/* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
} // Handle the last few bytes of the input array
switch (len) {
case 3:
h ^= (str.charCodeAt(i + 2) & 0xff) << 16;
case 2:
h ^= (str.charCodeAt(i + 1) & 0xff) << 8;
case 1:
h ^= str.charCodeAt(i) & 0xff;
h =
/* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
} // Do a few final mixes of the hash to ensure the last few
// bytes are well-incorporated.
h ^= h >>> 13;
h =
/* Math.imul(h, m): */
(h & 0xffff) * 0x5bd1e995 + ((h >>> 16) * 0xe995 << 16);
return ((h ^ h >>> 15) >>> 0).toString(36);
}
console.log(murmur2("123421334"))
console.log(murmur2("123asd ;nv"))
console.log(murmur2("1va1ns`klj"))"#;
let config = r#"{
"defaults": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn murmur2_reduced() {
let src = r#"function murmur2(str) {
var h = 0;
var k, i = 0, len = str.length;
for (; len >= 4; ++i, len -= 4) {
k = 255 & str.charCodeAt(i) | (255 & str.charCodeAt(++i)) << 8 | (255 & str.charCodeAt(++i)) << 16 | (255 & str.charCodeAt(++i)) << 24;
k = (65535 & k) * 1540483477 + ((k >>> 16) * 59797 << 16);
k ^= k >>> 24;
h = (65535 & k) * 1540483477 + ((k >>> 16) * 59797 << 16) ^ (65535 & h) * 1540483477 + ((h >>> 16) * 59797 << 16);
}
switch (len) {
case 3:
h ^= (255 & str.charCodeAt(i + 2)) << 16;
case 2:
h ^= (255 & str.charCodeAt(i + 1)) << 8;
case 1:
h ^= 255 & str.charCodeAt(i);
h = (65535 & h) * 1540483477 + ((h >>> 16) * 59797 << 16);
}
h ^= h >>> 13;
h = (65535 & h) * 1540483477 + ((h >>> 16) * 59797 << 16);
return ((h ^ h >>> 15) >>> 0).toString(36);
}
console.log(murmur2("123421334"));
console.log(murmur2("123asd ;nv"));
console.log(murmur2("1va1ns`klj"));"#;
let config = r#"{
"defaults": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn plotly_1() {
let src = r###"
function log2(v) {
var r, shift;
r = (v > 0xFFFF) << 4; v >>>= r;
shift = (v > 0xFF ) << 3; v >>>= shift; r |= shift;
shift = (v > 0xF ) << 2; v >>>= shift; r |= shift;
shift = (v > 0x3 ) << 1; v >>>= shift; r |= shift;
return r | (v >> 1);
}
console.log(log2(65536))
console.log(log2(2))
console.log(log2(4))
console.log(log2(8))
"###;
let config = r#"{
"defaults": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn internal_1() {
let src = r###"
function H (x) {
return function (y, z) {
return x._ + y + z
}
}
function P () {
var a = 0
a = {
_: 1
}
a.calc = H(a)
return a
}
console.log(P().calc(1, 1))
"###;
let config = r#"{
"defaults": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn direct_eval_1() {
let src = r###"
const obj = {
1: function () {
const foo = 1;
return {
test: function (s) {
return eval(s)
}
}
},
2: function foo(mod1) {
console.log(mod1.test('foo'))
}
};
obj[2](obj[1]());
"###;
let config = r#"{
"defaults": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn indirect_eval_1() {
let src = r###"
const obj = {
1: function () {
const foo = 1;
return {
test: function (s) {
const e = eval;
return e(s)
}
}
},
2: function foo(mod1) {
let success = false;
try {
mod1.test('foo')
} catch (e) {
success = true;
console.log('PASS');
}
if (!success) {
throw new Error('indirect eval should not be direct eval');
}
}
};
obj[2](obj[1]());
"###;
let config = r#"{
"defaults": true,
"toplevel": true
}"#;
run_exec_test(src, config, false);
}
#[test]
fn try_catch_1() {
let src = r#"
var a = "FAIL";
try {
throw 1;
} catch (args) {
a = "PASS";
}
console.log(a);
"#;
run_default_exec_test(src);
}
#[test]
fn try_catch_2() {
let src = r#"
var a = "PASS";
try {
throw "FAIL1";
} catch (a) {
var a = "FAIL2";
}
console.log(a);
"#;
run_default_exec_test(src);
}
#[test]
fn try_catch_3() {
let src = r#"
var a = "FAIL";
try {
throw 1;
} catch (args) {
var a = "PASS";
}
console.log(a);
"#;
run_default_exec_test(src);
}
#[test]
fn try_catch_4() {
let src = r#"
"aaaaaaaa";
var a = 1,
b = "FAIL";
try {
throw 1;
} catch (c) {
try {
throw 0;
} catch (a) {
if (c) b = "PASS";
}
}
console.log(b);
"#;
run_default_exec_test(src);
}
#[test]
fn try_catch_5() {
let src = r#"
var a = "PASS";
try {
throw "FAIL1";
} catch (a) {
var a = "FAIL2";
}
console.log(a);
"#;
run_default_exec_test(src);
}
#[test]
fn issue_4444_1() {
let src = r#"
const test = () => {
let a = 0;
let b = 0;
let c = [1, 2, 3, 4, 5].map((i) => {
a += i;
b += i;
return i;
});
return [a, b, c];
};
const [a, b, c] = test();
console.log("test", a, b, c);
"#;
let config = r#"
{
"arguments": false,
"arrows": false,
"booleans": true,
"booleans_as_integers": false,
"collapse_vars": true,
"comparisons": true,
"computed_props": false,
"conditionals": false,
"dead_code": false,
"directives": false,
"drop_console": false,
"drop_debugger": true,
"evaluate": false,
"expression": false,
"hoist_funs": false,
"hoist_props": false,
"hoist_vars": false,
"if_return": true,
"join_vars": false,
"keep_classnames": false,
"keep_fargs": true,
"keep_fnames": false,
"keep_infinity": false,
"loops": true,
"negate_iife": false,
"properties": true,
"reduce_funcs": false,
"reduce_vars": false,
"side_effects": true,
"switches": false,
"typeofs": false,
"unsafe": false,
"unsafe_arrows": false,
"unsafe_comps": false,
"unsafe_Function": false,
"unsafe_math": false,
"unsafe_symbols": false,
"unsafe_methods": false,
"unsafe_proto": false,
"unsafe_regexp": false,
"unsafe_undefined": false,
"unused": true
}
"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_insane_1() {
let src = r###"
function f() {
a--;
try {
a++;
x();
} catch (a) {
if (a) var a;
var a = 10;
}
console.log(a)
}
f();
"###;
let config = r#"
{
"conditionals": true,
"negate_iife": true,
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"toplevel": true,
"unused": true
}
"#;
run_exec_test(src, config, false);
}
#[test]
fn terser_insane_2() {
let src = r###"
function f() {
console.log(a)
a--;
console.log(a)
try {
console.log(a)
a++;
console.log(a)
x();
} catch (a) {
if (a) var a;
var a = 10;
}
console.log(a)
}
f();
"###;
let config = r#"
{
"conditionals": true,
"negate_iife": true,
"passes": 2,
"reduce_funcs": true,
"reduce_vars": true,
"side_effects": true,
"toplevel": true,
"unused": true
}
"#;
run_exec_test(src, config, false);
}
#[test]
fn issue_4788_1() {
let src = r#"
let id = 0;
const obj = {
get foo() {
console.log("foo", id++);
},
};
obj.foo;
const obj2 = {
...obj,
};
obj2.foo;
const obj3 = {
...obj,
foo: 1,
};
obj3.foo;
"#;
run_default_exec_test(src);
}
#[test]
fn issue_5645() {
let src = r###"
const t = {
1: 'a',
2: 'b'
}
function g(arg) {
if (t[arg] === undefined) {
var arg = 2
}
return t[arg]
}
console.log(g(1))
"###;
let config = r#"
{
"arguments": false,
"arrows": false,
"booleans": false,
"booleans_as_integers": false,
"collapse_vars": false,
"comparisons": false,
"computed_props": false,
"conditionals": false,
"dead_code": false,
"directives": false,
"drop_console": false,
"drop_debugger": false,
"evaluate": false,
"expression": false,
"hoist_funs": false,
"hoist_props": false,
"hoist_vars": false,
"if_return": false,
"join_vars": false,
"keep_classnames": false,
"keep_fargs": false,
"keep_fnames": false,
"keep_infinity": false,
"loops": false,
"negate_iife": false,
"properties": false,
"reduce_funcs": false,
"reduce_vars": false,
"side_effects": false,
"switches": false,
"typeofs": false,
"unsafe": false,
"unsafe_arrows": false,
"unsafe_comps": false,
"unsafe_Function": false,
"unsafe_math": false,
"unsafe_symbols": false,
"unsafe_methods": false,
"unsafe_proto": false,
"unsafe_regexp": false,
"unsafe_undefined": false,
"unused": false,
"const_to_let": false,
"pristine_globals": false
}
"#;
run_exec_test(src, config, false);
}
#[test]
fn issue_5799() {
let src = r"
console.log(`\u2014`)
";
run_default_exec_test(src);
}
#[test]
fn issue_5914() {
let src = r###"
class Test {
constructor(config) {
const that = this;
this.config = config;
this.options = {
get config() {
return that.config;
},
};
}
}
const instance = new Test(42);
console.log(instance.options.config);
"###;
let config = r#"
{
"arguments": false,
"arrows": true,
"booleans": true,
"booleans_as_integers": false,
"collapse_vars": true,
"comparisons": true,
"computed_props": true,
"conditionals": true,
"dead_code": true,
"directives": true,
"drop_console": false,
"drop_debugger": true,
"evaluate": true,
"expression": false,
"hoist_funs": false,
"hoist_props": true,
"hoist_vars": false,
"if_return": true,
"join_vars": true,
"keep_classnames": false,
"keep_fargs": true,
"keep_fnames": false,
"keep_infinity": false,
"loops": true,
"negate_iife": true,
"properties": true,
"reduce_funcs": false,
"reduce_vars": false,
"side_effects": true,
"switches": true,
"typeofs": true,
"unsafe": false,
"unsafe_arrows": false,
"unsafe_comps": false,
"unsafe_Function": false,
"unsafe_math": false,
"unsafe_symbols": false,
"unsafe_methods": false,
"unsafe_proto": false,
"unsafe_regexp": false,
"unsafe_undefined": false,
"unused": true,
"const_to_let": true,
"pristine_globals": true
}
"#;
run_exec_test(src, config, false);
}
#[test]
fn feedback_regex_range() {
let src = r###"
const rtlRegEx = new RegExp(
/* eslint-disable prettier/prettier */
'[' +
String.fromCharCode(0x00591) + '-' + String.fromCharCode(0x008ff) +
String.fromCharCode(0x0fb1d) + '-' + String.fromCharCode(0x0fdff) +
String.fromCharCode(0x0fe70) + '-' + String.fromCharCode(0x0fefc) +
String.fromCharCode(0x10800) + '-' + String.fromCharCode(0x10fff) +
String.fromCharCode(0x1e800) + '-' + String.fromCharCode(0x1efff) +
']'
/* eslint-enable prettier/prettier */
);
console.log('PASS')
"###;
run_default_exec_test(src);
}
#[test]
fn issue_6004() {
run_default_exec_test(
r###"
const props = {'a': 1, 'b': 2};
const isBox = 'a' in props || 'b' in props;
for (const p in props) {
delete props[p];
}
console.log(isBox);
"###,
);
}
#[test]
fn issue_6047_1() {
run_default_exec_test(
r###"
let foo = () => 1;
const obj = {
get 0() {
foo = () => 2;
return 40;
},
};
console.log(obj)
var c = obj[0];
console.log(foo(c));
"###,
);
}
#[test]
fn issue_6047_2() {
run_default_exec_test(
r###"
let foo = () => 1;
const obj = new Proxy({}, {
get () {
foo = () => 2;
return 40;
},
});
console.log(obj)
var c = obj[0];
console.log(foo(c));
"###,
);
}
#[test]
fn issue_6039_1() {
run_default_exec_test(
r###"
function foo() {
let walker = 0;
let arr = [];
function bar(defaultValue) {
const myIndex = walker;
walker += 1;
console.log({ arr });
if (arr.length < myIndex + 1) {
arr[myIndex] = defaultValue;
}
}
return bar;
}
const bar = foo();
bar(null);
bar(null);
bar(null);
bar(null);
bar(null);
"###,
);
}
#[test]
fn issue_6039_2() {
run_default_exec_test(
r###"
var foo = function foo() {
var walker = 0;
var arr = [];
function bar(defaultValue) {
var myIndex = walker;
walker += 1;
console.log({
arr: arr
});
if (arr.length < myIndex + 1) {
arr[myIndex] = defaultValue;
}
}
return bar;
};
var bar = foo();
bar(null);
bar(null);
bar(null);
bar(null);
bar(null);
"###,
);
}
#[test]
fn issue_6217_1() {
run_exec_test(
r###"
var foo = function foo() {
var walker = 0;
var arr = [];
function bar(defaultValue) {
var myIndex = walker;
walker += 1;
console.log({
arr: arr
});
if (arr.length < myIndex + 1) {
arr[myIndex] = defaultValue;
}
}
return bar;
};
var bar = foo();
bar(null);
bar(null);
bar(null);
bar(null);
bar(null);
"###,
r#"
{
"arguments": false,
"arrows": false,
"booleans": false,
"booleans_as_integers": false,
"collapse_vars": true,
"comparisons": false,
"computed_props": false,
"conditionals": false,
"dead_code": false,
"directives": false,
"drop_console": false,
"drop_debugger": false,
"evaluate": false,
"expression": false,
"hoist_funs": false,
"hoist_props": false,
"hoist_vars": false,
"if_return": false,
"join_vars": false,
"keep_classnames": false,
"keep_fargs": false,
"keep_fnames": false,
"keep_infinity": false,
"loops": false,
"negate_iife": false,
"properties": false,
"reduce_funcs": false,
"reduce_vars": false,
"side_effects": false,
"switches": false,
"typeofs": false,
"unsafe": false,
"unsafe_arrows": false,
"unsafe_comps": false,
"unsafe_Function": false,
"unsafe_math": false,
"unsafe_symbols": false,
"unsafe_methods": false,
"unsafe_proto": false,
"unsafe_regexp": false,
"unsafe_undefined": false,
"unused": false,
"const_to_let": false,
"pristine_globals": false
}
"#,
false,
);
}
#[test]
fn issue_6279_1() {
run_default_exec_test(
r###"
function run(str, r) {
let m
while(m = r.exec(str)) {
console.log(m)
}
}
run('abcda', /a/g)
"###,
);
}
#[test]
fn issue_6279_2() {
run_default_exec_test(
r###"
const r = new RegExp('a', 'g');
function run(str, r) {
let m
while (m = r.exec(str)) {
console.log(m)
}
}
run('abcda', r)
"###,
);
}
#[test]
fn issue_6463_1() {
run_default_exec_test(
r#"
var foo_1 = foo;
function foo() {
console.log("foo");
}
foo_1();
foo_1();
"#,
);
}
#[test]
fn issue_6528() {
run_default_exec_test(
r#"
const foo = {
"+1": 1,
"2": 2,
"-3": 3,
}
console.log(foo[1]);
console.log(foo["+1"]);
console.log(foo["2"]);
console.log(foo[2]);
console.log(foo[-3]);
console.log(foo["-3"]);
"#,
)
}
#[test]
fn issue_6641() {
run_default_exec_test(
r###"
const iota = (i => () => 1 << ++i)(-1);
const a = iota(), b = iota();
console.log(a, b);
"###,
)
}
#[test]
fn issue_6728() {
run_default_exec_test(
r###"
async function foo() {
if (undefined_var_1) {
let replace;
if (undefined_var_2) {
replace = 1;
} else {
replace = 2;
}
await a({ replace })
}
}
console.log('PASS')
"###,
)
}
#[test]
fn issue_6750_1() {
run_default_exec_test(
r#"
let current_component;
function set_current_component(component) {
current_component = component;
}
function f(component) {
const parent = current_component
set_current_component(component)
parent.m()
}
const obj = {
m() {
console.log("call m()")
}
}
try {
f(obj)
} catch (e) {
console.log('PASS')
}
"#,
)
}
#[test]
fn issue_6750_2() {
run_exec_test(
r#"
let current_component;
function set_current_component(component) {
current_component = component;
}
function f(component) {
const parent = current_component
set_current_component(component)
parent.m()
}
const obj = {
m() {
console.log("call m()")
}
}
try {
f(obj)
} catch (e) {
console.log('PASS')
}
"#,
r#"{
"defaults": true,
"sequences": false
}"#,
false,
)
}
#[test]
fn issue_6899_1() {
run_exec_test(
r#"
// this the original code, just for comparison
function Limit(min, max) {
var length = Math.abs(min - max);
function reachedMin(n) {
return n < min;
}
function reachedMax(n) {
return n > max;
}
function reachedAny(n) {
return reachedMin(n) || reachedMax(n);
}
function constrain(n) {
if (!reachedAny(n)) return n;
return reachedMin(n) ? min : max;
}
function removeOffset(n) {
if (!length) return n;
return n - length * Math.ceil((n - max) / length);
}
var self = {
length: length,
max: max,
min: min,
constrain: constrain,
reachedAny: reachedAny,
reachedMax: reachedMax,
reachedMin: reachedMin,
removeOffset: removeOffset
};
return self;
}
console.log("The result should be 0. And it is:", Limit(0,3).constrain(-1))
"#,
r#"
{
"arguments": false,
"arrows": true,
"booleans": true,
"booleans_as_integers": false,
"collapse_vars": true,
"comparisons": true,
"computed_props": true,
"conditionals": true,
"dead_code": true,
"directives": true,
"drop_console": false,
"drop_debugger": true,
"evaluate": true,
"expression": false,
"hoist_funs": false,
"hoist_props": true,
"hoist_vars": false,
"if_return": true,
"join_vars": true,
"keep_classnames": false,
"keep_fargs": true,
"keep_fnames": false,
"keep_infinity": false,
"loops": true,
"negate_iife": true,
"properties": true,
"reduce_funcs": false,
"reduce_vars": false,
"side_effects": true,
"switches": true,
"typeofs": true,
"unsafe": false,
"unsafe_arrows": false,
"unsafe_comps": false,
"unsafe_Function": false,
"unsafe_math": false,
"unsafe_symbols": false,
"unsafe_methods": false,
"unsafe_proto": false,
"unsafe_regexp": false,
"unsafe_undefined": false,
"unused": true,
"const_to_let": true,
"pristine_globals": true
}
"#,
false,
)
}
#[test]
fn issue_6899_2() {
run_default_exec_test(
r#"
// this the original code, just for comparison
function Limit(min, max) {
var length = Math.abs(min - max);
function reachedMin(n) {
return n < min;
}
function reachedMax(n) {
return n > max;
}
function reachedAny(n) {
return reachedMin(n) || reachedMax(n);
}
function constrain(n) {
if (!reachedAny(n)) return n;
return reachedMin(n) ? min : max;
}
function removeOffset(n) {
if (!length) return n;
return n - length * Math.ceil((n - max) / length);
}
var self = {
length: length,
max: max,
min: min,
constrain: constrain,
reachedAny: reachedAny,
reachedMax: reachedMax,
reachedMin: reachedMin,
removeOffset: removeOffset
};
return self;
}
console.log("The result should be 0. And it is:", Limit(0,3).constrain(-1))
"#,
);
}
#[test]
fn issue_6899_3() {
run_default_exec_test(
r#"
console.log("The result should be 0. And it is:", function(n, e) {
var r = Math.abs(n - e);
function t(e) {
return e < n
}
function u(n) {
return n > e
}
function c(n) {
return t(n) || u(n)
}
return {
length: r,
max: e,
min: n,
constrain: function(r) {
return c(r) ? t(r) ? n : e : r
},
reachedAny: c,
reachedMax: u,
reachedMin: t,
removeOffset: function(n) {
return r ? n - r * Math.ceil((n - e) / r) : n
}
}
}(0, 3).constrain(-1));
"#,
);
}
#[test]
fn issue_6899_4() {
run_exec_test(
r#"
console.log("The result should be 0. And it is:", function(n, e) {
var r = Math.abs(n - e);
function t(e) {
return e < n
}
function u(n) {
return n > e
}
function c(n) {
return t(n) || u(n)
}
return {
length: r,
max: e,
min: n,
constrain: function(r) {
return c(r) ? t(r) ? n : e : r
},
reachedAny: c,
reachedMax: u,
reachedMin: t,
removeOffset: function(n) {
return r ? n - r * Math.ceil((n - e) / r) : n
}
}
}(0, 3).constrain(-1));
"#,
r#"
{
"inline": true,
"passes": 2
}
"#,
false,
);
}
#[test]
fn issue_6899_5() {
run_exec_test(
r#"
console.log("The result should be 0. And it is:", function(n, e) {
var r = Math.abs(n - e);
function t(e) {
return e < n
}
function u(n) {
return n > e
}
function c(n) {
return t(n) || u(n)
}
return {
constrain: function(r) {
return c(r) ? (t(r) ? n : e) : r
},
}
}(0, 3).constrain(-1));
"#,
r#"
{
"inline": true,
"passes": 2
}
"#,
false,
);
}
#[test]
fn issue_6903_1() {
run_default_exec_test(
r#"
function test(a, b) {
let wrapper = (e) => e
wrapper = (e) => (["not", e])
if (a) {
return wrapper(b)
}
return wrapper(1)
}
console.log(test(true, "bad"))
"#,
);
}
#[test]
fn issue_6903_2() {
run_exec_test(
r#"
function test(a, b) {
let wrapper = (e) => e
wrapper = (e) => (["not", e])
if (a) {
return wrapper(b)
}
return wrapper(1)
}
console.log(test(true, "bad"))
"#,
r#"
{
"if_return": true,
"join_vars": true,
"side_effects": true,
"conditionals": true
}"#,
false,
);
}
#[test]
fn issue_6903_3() {
run_exec_test(
r#"
function test(a, b) {
let wrapper = (e)=>e;
return ((wrapper = (e)=>[
"not",
e
]), a) ? wrapper(b) : wrapper(1);
}
console.log(test(true, "bad"));
"#,
r#"
{
"conditionals": true
}"#,
false,
);
}
#[test]
fn issue_6914_1() {
run_default_exec_test(
r###"
console.log(doSomething())
function doSomething() {
return fabricateEvent()
}
function fabricateEvent() {
let def = createEventDef()
return {
def,
ui: compileEventUi(def),
}
}
function compileEventUi(def) {
let uis = []
uis.push(def.ui)
return uis
}
function createEventDef() {
return {
id: 'fakeId',
ui: 'something'
}
}
"###,
);
}
#[test]
fn issue_6914_2() {
run_exec_test(
r###"
console.log(doSomething())
function doSomething() {
return fabricateEvent()
}
function fabricateEvent() {
let def = createEventDef()
return {
def,
ui: compileEventUi(def),
}
}
function compileEventUi(def) {
let uis = []
uis.push(def.ui)
return uis
}
function createEventDef() {
return {
id: 'fakeId',
ui: 'something'
}
}
"###,
r#"
{
"inline": true,
"toplevel": true
}
"#,
false,
);
}
#[test]
fn issue_6914_3() {
run_exec_test(
r###"
console.log(function() {
return function() {
let def = function() {
return {
id: 'fakeId',
ui: 'something'
};
}();
return {
def,
ui: function(def) {
let uis = [];
uis.push(def.ui);
return uis;
}(def)
};
}();
}());
"###,
r#"
{
"inline": true,
"toplevel": true
}
"#,
false,
);
}
#[test]
fn issue_7274() {
run_default_exec_test(
r#"
if (
// incorrect:
"😋📋👌".length === 3
// correct:
// "😋📋👌".length === 6
) {
// side effect
new Response(123);
}
console.log('PASS');
"#,
);
}
#[test]
fn issue_8119_1() {
run_exec_test(
r#"
const myArr = [];
// function with side effect
function foo(arr) {
arr.push('foo');
return 'foo';
}
let a;
if (Math.random() > 1.1) {
a = true;
}
// the function call below should always run
// regardless of whether `a` is `undefined`
let b = foo(myArr);
// const seems to keep this line here instead of
// moving it behind the logitcal nullish assignment
// const b = foo(myArr);
a ??= b;
console.log(a);
console.log(myArr);
"#,
r#"
{
"arguments": false,
"arrows": true,
"booleans": true,
"booleans_as_integers": false,
"collapse_vars": true,
"comparisons": true,
"computed_props": true,
"conditionals": true,
"dead_code": true,
"directives": true,
"drop_console": false,
"drop_debugger": true,
"evaluate": true,
"expression": false,
"hoist_funs": false,
"hoist_props": true,
"hoist_vars": false,
"if_return": true,
"join_vars": true,
"keep_classnames": false,
"keep_fargs": true,
"keep_fnames": false,
"keep_infinity": false,
"loops": true,
"negate_iife": true,
"properties": true,
"reduce_funcs": false,
"reduce_vars": false,
"side_effects": true,
"switches": true,
"typeofs": true,
"unsafe": false,
"unsafe_arrows": false,
"unsafe_comps": false,
"unsafe_Function": false,
"unsafe_math": false,
"unsafe_symbols": false,
"unsafe_methods": false,
"unsafe_proto": false,
"unsafe_regexp": false,
"unsafe_undefined": false,
"unused": true,
"const_to_let": true,
"pristine_globals": true,
"passes": 2
}
"#,
false,
);
}
#[test]
fn issue_8119_2() {
run_exec_test(
r#"
const myArr = [];
// function with side effect
function foo(arr) {
arr.push('foo');
return 'foo';
}
let a;
if (Math.random() > -0.1) {
a = true;
}
// the function call below should always run
// regardless of whether `a` is `undefined`
let b = foo(myArr);
// const seems to keep this line here instead of
// moving it behind the logitcal nullish assignment
// const b = foo(myArr);
a ??= b;
console.log(a);
console.log(myArr);
"#,
r#"
{
"arguments": false,
"arrows": true,
"booleans": true,
"booleans_as_integers": false,
"collapse_vars": true,
"comparisons": true,
"computed_props": true,
"conditionals": true,
"dead_code": true,
"directives": true,
"drop_console": false,
"drop_debugger": true,
"evaluate": true,
"expression": false,
"hoist_funs": false,
"hoist_props": true,
"hoist_vars": false,
"if_return": true,
"join_vars": true,
"keep_classnames": false,
"keep_fargs": true,
"keep_fnames": false,
"keep_infinity": false,
"loops": true,
"negate_iife": true,
"properties": true,
"reduce_funcs": false,
"reduce_vars": false,
"side_effects": true,
"switches": true,
"typeofs": true,
"unsafe": false,
"unsafe_arrows": false,
"unsafe_comps": false,
"unsafe_Function": false,
"unsafe_math": false,
"unsafe_symbols": false,
"unsafe_methods": false,
"unsafe_proto": false,
"unsafe_regexp": false,
"unsafe_undefined": false,
"unused": true,
"const_to_let": true,
"pristine_globals": true,
"passes": 2
}
"#,
false,
);
}
#[test]
fn issue_8246_1() {
run_exec_test(
r#"
function withLog(methods) {
const result = {};
for(const methodName in methods){
result[methodName] = ((methodName)=>function() {
console.log(methodName + ' invoked');
return methods[methodName].apply(this, arguments);
})(methodName);
}
return result;
}
function main() {
const result = withLog({
test () {
console.log('method test executed');
},
another () {
console.log('method another executed');
}
});
result.test();
}
main();
"#,
r#"
{
"ecma": 2015,
"arguments": false,
"arrows": true,
"booleans": true,
"booleans_as_integers": false,
"collapse_vars": true,
"comparisons": true,
"computed_props": true,
"conditionals": true,
"dead_code": true,
"directives": true,
"drop_console": false,
"drop_debugger": true,
"evaluate": true,
"expression": false,
"hoist_funs": false,
"hoist_props": true,
"hoist_vars": false,
"if_return": true,
"join_vars": true,
"keep_classnames": false,
"keep_fargs": true,
"keep_fnames": false,
"keep_infinity": false,
"loops": true,
"negate_iife": true,
"properties": true,
"reduce_funcs": false,
"reduce_vars": false,
"side_effects": true,
"switches": true,
"typeofs": true,
"unsafe": false,
"unsafe_arrows": false,
"unsafe_comps": false,
"unsafe_Function": false,
"unsafe_math": false,
"unsafe_symbols": false,
"unsafe_methods": false,
"unsafe_proto": false,
"unsafe_regexp": false,
"unsafe_undefined": false,
"unused": true,
"const_to_let": true,
"pristine_globals": true,
"passes": 5
}
"#,
false,
);
}
#[test]
fn issue_8864_1() {
run_default_exec_test(
"
class Renderer {
renderStaticFrame(string1, string2) {
const line1Text = `${string1} and ${string2}`.toUpperCase();
const line2Text = 'line 2 text'.toUpperCase();
const text = `${line1Text}\n${line2Text}`;
return text;
}
}
console.log(new Renderer().renderStaticFrame('a', 'b'));
",
)
}
#[test]
fn issue_8886() {
run_default_exec_test(
"const bar = ((v) => v)(1);
const foo = ((v) => v)(2);
console.log(eval(bar));
console.log(eval(foo));",
);
}
#[test]
fn issue_8942() {
run_default_exec_test(
"
'use strict';
const k = (() => {
let x = 1;
x **= undefined / x;
return x;
})();
console.log(k);
",
);
}
#[test]
fn issue_8937() {
run_default_exec_test(
"
class Container {
constructor(v) {
this.a= v;
}
add(x) {
this.a += x;
}
toString() {
return this.a.toString();
}
};
let x = Math.random();
let a = new Container(x);
let b = new Container(x+1);
let comp = a < b;
while (a < b) {
a.add(1);
}
console.log(comp ? 'smaller' : 'not smaller');
",
);
}
#[test]
fn issue_8943() {
run_default_exec_test(
"
'use strict';
const k = (() => {
return '👨👩👦'.charCodeAt(0);
});
console.log(k());
",
);
}
#[test]
fn issue_8964() {
run_default_exec_test(
"
function foo(bit) {
a = !(bit & 1)
b = !(bit & 2)
return a + b
};
console.log(foo(1));
",
);
}
#[test]
fn issue_9008() {
run_default_exec_test("console.log('💖'[0]);")
}
#[test]
fn issue_8982_1() {
run_default_exec_test(
"
console.log(Math.max(0, -0));
",
);
}
#[test]
fn issue_8982_2() {
run_default_exec_test(
"
console.log(Math.min(0, -0));
",
);
}
#[test]
fn issue_9010() {
run_default_exec_test(
r#"
console.log(-0 + [])
"#,
);
}
#[test]
fn issue_9184() {
run_default_exec_test(
r#"
let pi= Math.random() >1.1 ? "foo": "bar";
console.log(`(${`${pi}`} - ${`\\*${pi}`})`)
"#,
);
}
#[test]
fn issue_9184_2() {
run_default_exec_test(
r#"
let pi= Math.random() < -1 ? "foo": "bar";
console.log(`(${`${pi}`} - ${`\\*${pi}`})`)
"#,
);
}
#[test]
fn issue_9499() {
run_default_exec_test(
"
const o = {'a': 1, 'b': 2};
function fn() {
return 'a' in o;
}
console.log(fn());
",
)
}
#[test]
fn issue_9356() {
run_default_exec_test("console.log((function ({ } = 42) { }).length)");
}
#[test]
fn isssue_9498() {
run_default_exec_test(
"
const x = {a: 1};
const y = {...x, a: 2};
console.log(y.a);
",
)
}
#[test]
fn issue_10095() {
run_exec_test(
"
function module() {
function a() {
if (a.isInit) return;
a.isInit = true;
console.log('run')
}
function b() {
a();
console.log('after');
}
b();
b();
}
module();
",
r#"{
"defaults": true,
"arguments": false,
"arrows": false,
"booleans": false,
"booleans_as_integers": false,
"collapse_vars": false,
"comparisons": false,
"computed_props": false,
"conditionals": false,
"dead_code": false,
"directives": false,
"drop_console": false,
"drop_debugger": false,
"evaluate": false,
"expression": false,
"hoist_funs": false,
"hoist_props": false,
"hoist_vars": false,
"if_return": false,
"join_vars": false,
"keep_classnames": false,
"keep_fargs": false,
"keep_fnames": false,
"keep_infinity": false,
"loops": false,
"negate_iife": false,
"properties": false,
"reduce_funcs": false,
"reduce_vars": false,
"side_effects": false,
"switches": false,
"typeofs": false,
"unsafe": false,
"unsafe_arrows": false,
"unsafe_comps": false,
"unsafe_Function": false,
"unsafe_math": false,
"unsafe_symbols": false,
"unsafe_methods": false,
"unsafe_proto": false,
"unsafe_regexp": false,
"unsafe_undefined": false,
"unused": false,
"const_to_let": false,
"pristine_globals": false
}"#,
false,
);
}
#[test]
fn issue_10133() {
run_default_exec_test(
"
function splineCurve(firstPoint, middlePoint, afterPoint) {
const previous = firstPoint.skip ? middlePoint : firstPoint;
const current = middlePoint;
const next = afterPoint;
return {
x: current.x - (next.x - previous.x),
y: current.y - (next.y - previous.y)
};
}
function _updateBezierControlPoints(points) {
let i, ilen, point, controlPoints;
let prev = points[0];
for(i = 0, ilen = points.length; i < ilen; ++i){
point = points[i];
controlPoints = splineCurve(prev, point, points[Math.min(i + 1, ilen - 1)]);
point.cp1x = controlPoints.x;
prev = point;
}
}
let points = [{x: 1, y: 2}, {x: 2, y: 1}, {x: 3, y: 2}];
_updateBezierControlPoints(points);
console.log(points)
",
);
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/check/1/input.js | JavaScript | import { upper } from "module";
let foobar = "foo";
export const foo = foobar;
const bar = "bar";
foobar += bar;
let foobarCopy = foobar;
foobar += "foo";
console.log(foobarCopy);
foobarCopy += "Unused";
function internal() {
return upper(foobar);
}
// export function external1() {
// return internal() + foobar;
// }
// export function external2() {
// foobar += ".";
// } | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/check/1/output.js | JavaScript | import "module";
let foobar = "foo";
export const foo = foobar;
let foobarCopy = foobar += "bar";
foobar += "foo", console.log(foobarCopy);
// export function external1() {
// return internal() + foobar;
// }
// export function external2() {
// foobar += ".";
// }
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/comparison/1/.input.js | JavaScript | self.push({
9111: (function (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
/* harmony export */
__webpack_require__.d(__webpack_exports__, {
/* harmony export */
"F": function () {
return /* binding */ composeRefs;
},
/* harmony export */
"e": function () {
return /* binding */ useComposedRefs;
}
/* harmony export */
});
/* harmony import */
var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(27378);
function composeRefs(...o) {
return e => o.forEach((o => function (o, e) {
"function" == typeof o ? o(e) : null != o && (o.current = e)
}(o, e)))
}
function useComposedRefs(...e) {
return react__WEBPACK_IMPORTED_MODULE_0__.useCallback(composeRefs(...e), e)
}
//# sourceMappingURL=index.module.js.map
/***/
})
}) | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/comparison/2/.input.js | JavaScript | self.push({
58354: function (__unused_webpack_module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.d(__webpack_exports__, {
do: function () {
return ResizeObserver
}
});
var ResizeObserverBoxOptions, trigger, ResizeObserverBoxOptions, resizeObservers = [],
msg = "ResizeObserver loop completed with undelivered notifications.",
deliverResizeLoopError = function () {
var event;
"function" == typeof ErrorEvent ? event = new ErrorEvent("error", {
message: msg
}) : ((event = document.createEvent("Event")).initEvent("error", !1, !1), event.message = msg), window.dispatchEvent(event)
};
(ResizeObserverBoxOptions = ResizeObserverBoxOptions || (ResizeObserverBoxOptions = {})).BORDER_BOX = "border-box", ResizeObserverBoxOptions.CONTENT_BOX = "content-box", ResizeObserverBoxOptions.DEVICE_PIXEL_CONTENT_BOX = "device-pixel-content-box";
var freeze = function (obj) {
return Object.freeze(obj)
};
return function () {
function DOMRectReadOnly(x, y, width, height) {
return this.x = x, this.y = y, this.width = width, this.height = height, this.top = this.y, this.left = this.x, this.bottom = this.top + this.height, this.right = this.left + this.width, freeze(this)
}
return DOMRectReadOnly.prototype.toJSON = function () {
var width, x = this.x,
y = this.y,
top = this.top,
right = this.right,
bottom = this.bottom,
left = this.left;
return {
x: x,
y: y,
top: top,
right: right,
bottom: bottom,
left: left,
width: this.width,
height: this.height
}
}, DOMRectReadOnly.fromRect = function (rectangle) {
return new DOMRectReadOnly(rectangle.x, rectangle.y, rectangle.width, rectangle.height)
}, DOMRectReadOnly
}()
},
}) | willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/10041/input.js | JavaScript | (function () {
function entry() {
var struct = {
a: [],
b: 0,
};
setName(struct, "Alice");
}
function setName(struct, str) {
writeString(struct.a, struct.b, str);
}
function writeString(buffer, offset, c) {
for (var i = 0, v = c.length; i < v; i = (i + 1) | 0) {
buffer[(offset + i) | 0] = c.charCodeAt(i);
}
}
entry();
})();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/10041/output.js | JavaScript | var struct;
!function(buffer, offset, c) {
for(var i = 0, v = c.length; i < v; i = i + 1 | 0)buffer[offset + i | 0] = c.charCodeAt(i);
}((struct = {
a: [],
b: 0
}).a, struct.b, "Alice");
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2011/actual/input.js | JavaScript | function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true,
});
} else {
obj[key] = value;
}
return obj;
}
var ClassA = function ClassA() {
"use strict";
_classCallCheck(this, ClassA);
};
module.exports = (function () {
var ClassB = /*#__PURE__*/ (function () {
"use strict";
function ClassB() {
_classCallCheck(this, ClassB);
}
_createClass(ClassB, [
{
key: "it",
value: function it() {
this.bb = new ClassB.MyA();
},
},
]);
return ClassB;
})();
_defineProperty(ClassB, "MyA", ClassA);
return ClassB;
})();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2011/actual/output.js | JavaScript | var ClassB, obj, value;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) throw TypeError("Cannot call a class as a function");
}
module.exports = (obj = ClassB = /*#__PURE__*/ function() {
"use strict";
var protoProps;
function ClassB() {
_classCallCheck(this, ClassB);
}
return protoProps = [
{
key: "it",
value: function() {
this.bb = new ClassB.MyA();
}
}
], function(target, props) {
for(var i = 0; i < props.length; i++){
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor);
}
}(ClassB.prototype, protoProps), ClassB;
}(), value = function ClassA() {
"use strict";
_classCallCheck(this, ClassA);
}, "MyA" in obj ? Object.defineProperty(obj, "MyA", {
value: value,
enumerable: !0,
configurable: !0,
writable: !0
}) : obj.MyA = value, ClassB);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2011/reduced/input.js | JavaScript | class ClassA {}
module.exports = class ClassB {
static MyA = ClassA;
it() {
this.bb = new ClassB.MyA();
}
};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2011/reduced/output.js | JavaScript | class ClassA {
}
module.exports = class ClassB {
static MyA = ClassA;
it() {
this.bb = new ClassB.MyA();
}
};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2028/input.js | JavaScript | function isSymbol(s) {
return s != null;
}
function isKey(value, object) {
if (value == null || isSymbol(value)) {
return true;
}
return false;
}
module.exports = isKey;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2028/output.js | JavaScript | module.exports = function(value, object) {
return null == value || null != value;
};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2044/full/input.js | JavaScript | function createCommonjsModule(fn) {
var module = { exports: {} };
return fn(module, module.exports), module.exports;
}
const isFile = (config) => true;
const pkgBrowserslist = {};
const config = {};
createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true,
});
});
createCommonjsModule(function (module) {
module.exports = {
findConfig: function findConfig(from) {
var resolved = function (dir) {
if (2) {
throw new Error("");
} else if (pkgBrowserslist) {
throw new Error("");
} else if (1) {
throw new Error("");
} else if (true) {
return module.exports.findConfig(null);
} else if (true) {
return module.exports.findConfig(null);
}
};
return resolved;
},
};
});
createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true,
});
});
createCommonjsModule(function (module, exports) {
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
_interopRequireDefault();
var _node = _interopRequireDefault();
});
createCommonjsModule(function (module, exports) {
exports.default = null;
module.exports = exports.default;
});
createCommonjsModule(function (module, exports) {
exports.default = void 0;
});
var namespace$1 = createCommonjsModule(function (module, exports) {
exports.default = void 0;
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
module.exports = exports.default;
});
createCommonjsModule(function (module, exports) {
exports.default = void 0;
module.exports = exports.default;
});
createCommonjsModule(function (module, exports) {
exports.default = void 0;
exports.default = String;
});
createCommonjsModule(function (module, exports) {
exports.default = void 0;
var Pseudo = null;
exports.default = String;
});
createCommonjsModule(function (module, exports) {
exports.__esModule = true;
});
createCommonjsModule(function (module, exports) {
exports.__esModule = true;
});
createCommonjsModule(function (module, exports) {
exports.__esModule = true;
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2044/full/output.js | JavaScript | function createCommonjsModule(fn) {
var module = {
exports: {}
};
return fn(module, module.exports), module.exports;
}
createCommonjsModule(function(module, exports) {
Object.defineProperty(exports, "__esModule", {
value: !0
});
}), createCommonjsModule(function(module) {
module.exports = {
findConfig: function(from) {
return function(dir) {
throw Error("");
};
}
};
}), createCommonjsModule(function(module, exports) {
Object.defineProperty(exports, "__esModule", {
value: !0
});
}), createCommonjsModule(function(module, exports) {
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
_interopRequireDefault(), _interopRequireDefault();
}), createCommonjsModule(function(module, exports) {
exports.default = null, module.exports = exports.default;
}), createCommonjsModule(function(module, exports) {
exports.default = void 0;
}), createCommonjsModule(function(module, exports) {
exports.default = void 0, module.exports = exports.default;
}), createCommonjsModule(function(module, exports) {
exports.default = void 0, module.exports = exports.default;
}), createCommonjsModule(function(module, exports) {
exports.default = void 0, exports.default = String;
}), createCommonjsModule(function(module, exports) {
exports.default = void 0, exports.default = String;
}), createCommonjsModule(function(module, exports) {
exports.__esModule = !0;
}), createCommonjsModule(function(module, exports) {
exports.__esModule = !0;
}), createCommonjsModule(function(module, exports) {
exports.__esModule = !0;
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2044/pass-1/input.js | JavaScript | function createCommonjsModule(fn) {
return fn();
}
const isFile = (config) => true;
const pkgBrowserslist = {};
const config = {};
createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true,
});
});
createCommonjsModule(function (module) {
module.exports = {
findConfig: function findConfig(from) {
var resolved = function (dir) {
if (2) {
throw new Error("");
} else if (pkgBrowserslist) {
throw new Error("");
} else if (1) {
throw new Error("");
} else if (true) {
return module.exports.findConfig(null);
} else if (true) {
return module.exports.findConfig(null);
}
};
return resolved;
},
};
});
createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true,
});
});
createCommonjsModule(function (module, exports) {
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
_interopRequireDefault();
var _node = _interopRequireDefault();
});
createCommonjsModule(function (module, exports) {
exports.default = null;
module.exports = exports.default;
});
createCommonjsModule(function (module, exports) {
exports.default = void 0;
});
var namespace$1 = createCommonjsModule(function (module, exports) {
exports.default = void 0;
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
module.exports = exports.default;
});
createCommonjsModule(function (module, exports) {
exports.default = void 0;
module.exports = exports.default;
});
createCommonjsModule(function (module, exports) {
exports.default = void 0;
exports.default = String;
});
createCommonjsModule(function (module, exports) {
exports.default = void 0;
var Pseudo = null;
exports.default = String;
});
createCommonjsModule(function (module, exports) {
exports.__esModule = true;
});
createCommonjsModule(function (module, exports) {
exports.__esModule = true;
});
createCommonjsModule(function (module, exports) {
exports.__esModule = true;
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2044/pass-1/output.js | JavaScript | function createCommonjsModule(fn) {
return fn();
}
const isFile = (config)=>!0, pkgBrowserslist = {}, config = {};
createCommonjsModule(function(module, exports) {
Object.defineProperty(exports, "__esModule", {
value: !0
});
}), createCommonjsModule(function(module) {
module.exports = {
findConfig: function(from) {
return function(dir) {
throw Error("");
};
}
};
}), createCommonjsModule(function(module, exports) {
Object.defineProperty(exports, "__esModule", {
value: !0
});
}), createCommonjsModule(function(module, exports) {
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
_interopRequireDefault(), _interopRequireDefault();
}), createCommonjsModule(function(module, exports) {
exports.default = null, module.exports = exports.default;
}), createCommonjsModule(function(module, exports) {
exports.default = void 0;
});
var namespace$1 = createCommonjsModule(function(module, exports) {
exports.default = void 0, module.exports = exports.default;
});
createCommonjsModule(function(module, exports) {
exports.default = void 0, module.exports = exports.default;
}), createCommonjsModule(function(module, exports) {
exports.default = void 0, exports.default = String;
}), createCommonjsModule(function(module, exports) {
exports.default = void 0, exports.default = String;
}), createCommonjsModule(function(module, exports) {
exports.__esModule = !0;
}), createCommonjsModule(function(module, exports) {
exports.__esModule = !0;
}), createCommonjsModule(function(module, exports) {
exports.__esModule = !0;
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2044/pass-10/input.js | JavaScript | function createCommonjsModule(fn) {
return fn();
}
const isFile = (config) => true;
const pkgBrowserslist = {};
const config = {};
createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true,
});
});
createCommonjsModule(function (module) {
module.exports = {
findConfig: function findConfig(from) {
var resolved = function (dir) {
if (2) {
throw new Error("");
} else if (pkgBrowserslist) {
throw new Error("");
} else if (1) {
throw new Error("");
} else if (true) {
return module.exports.findConfig(null);
} else if (true) {
return module.exports.findConfig(null);
}
};
return resolved;
},
};
});
createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", {
value: true,
});
});
createCommonjsModule(function (module, exports) {
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
_interopRequireDefault();
var _node = _interopRequireDefault();
});
createCommonjsModule(function (module, exports) {
exports.default = null;
module.exports = exports.default;
});
createCommonjsModule(function (module, exports) {
exports.default = void 0;
});
var namespace$1 = createCommonjsModule(function (module, exports) {
exports.default = void 0;
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
module.exports = exports.default;
});
createCommonjsModule(function (module, exports) {
exports.default = void 0;
module.exports = exports.default;
});
createCommonjsModule(function (module, exports) {
exports.default = void 0;
exports.default = String;
});
createCommonjsModule(function (module, exports) {
exports.default = void 0;
var Pseudo = null;
exports.default = String;
});
createCommonjsModule(function (module, exports) {
exports.__esModule = true;
});
createCommonjsModule(function (module, exports) {
exports.__esModule = true;
});
createCommonjsModule(function (module, exports) {
exports.__esModule = true;
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2044/pass-10/output.js | JavaScript | function createCommonjsModule(fn) {
return fn();
}
const isFile = (config)=>!0, pkgBrowserslist = {}, config = {};
createCommonjsModule(function(module, exports) {
Object.defineProperty(exports, "__esModule", {
value: !0
});
}), createCommonjsModule(function(module) {
module.exports = {
findConfig: function(from) {
return function(dir) {
throw Error("");
};
}
};
}), createCommonjsModule(function(module, exports) {
Object.defineProperty(exports, "__esModule", {
value: !0
});
}), createCommonjsModule(function(module, exports) {
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
_interopRequireDefault(), _interopRequireDefault();
}), createCommonjsModule(function(module, exports) {
exports.default = null, module.exports = exports.default;
}), createCommonjsModule(function(module, exports) {
exports.default = void 0;
});
var namespace$1 = createCommonjsModule(function(module, exports) {
exports.default = void 0, module.exports = exports.default;
});
createCommonjsModule(function(module, exports) {
exports.default = void 0, module.exports = exports.default;
}), createCommonjsModule(function(module, exports) {
exports.default = void 0, exports.default = String;
}), createCommonjsModule(function(module, exports) {
exports.default = void 0, exports.default = String;
}), createCommonjsModule(function(module, exports) {
exports.__esModule = !0;
}), createCommonjsModule(function(module, exports) {
exports.__esModule = !0;
}), createCommonjsModule(function(module, exports) {
exports.__esModule = !0;
});
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2072/1/input.js | JavaScript | function cost(oldItem, newItem) {
if (newItem.val === oldItem.val) {
return 0;
}
if (typeof oldItem.val === "object" && typeof newItem.val === "object") {
if (oldItem.key === undefined || newItem.key === undefined) {
return 1;
}
if (oldItem.key === newItem.key) {
return 0;
}
}
return 1;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2078/1/input.js | JavaScript | let rerenderQueue = [1];
let queue;
while (rerenderQueue.length > 0) {
queue = rerenderQueue.sort();
rerenderQueue = [];
queue.forEach((c) => console.log(c));
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2078/1/output.js | JavaScript | let queue, rerenderQueue = [
1
];
for(; rerenderQueue.length > 0;)queue = rerenderQueue.sort(), rerenderQueue = [], queue.forEach((c)=>console.log(c));
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2214/1/input.js | JavaScript | function f(a, b) {
if (a) {
if (b) return;
foo();
}
bar();
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2262/1/input.js | JavaScript | (() => {
"use strict";
var commonjsGlobal = globalThis;
function createEventEmitter(value) {}
var index = somethingGlobal;
const esm = index;
esm();
})();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2262/1/output.js | JavaScript | somethingGlobal();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2319/1/input.js | JavaScript | function foo(l, r) {
var lightGreeting;
if (l > 0) {
var greeting = "hello";
} else {
var greeting = "howdy";
}
if (r > 0) {
lightGreeting = greeting.substr(0, 2);
}
return lightGreeting;
}
module.exports = foo;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2319/1/output.js | JavaScript | module.exports = function(l, r) {
var lightGreeting;
if (l > 0) var greeting = "hello";
else var greeting = "howdy";
return r > 0 && (lightGreeting = greeting.substr(0, 2)), lightGreeting;
};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2558/1/input.js | JavaScript | /**!
* url-search-params-polyfill
*
* @author Jerry Bendy (https://github.com/jerrybendy)
* @licence MIT
*/
(function (self) {
"use strict";
var nativeURLSearchParams = (function () {
// #41 Fix issue in RN
try {
if (
self.URLSearchParams &&
new self.URLSearchParams("foo=bar").get("foo") === "bar"
) {
return self.URLSearchParams;
}
} catch (e) {}
return null;
})(),
isSupportObjectConstructor =
nativeURLSearchParams &&
new nativeURLSearchParams({ a: 1 }).toString() === "a=1",
// There is a bug in safari 10.1 (and earlier) that incorrectly decodes `%2B` as an empty space and not a plus.
decodesPlusesCorrectly =
nativeURLSearchParams &&
new nativeURLSearchParams("s=%2B").get("s") === "+",
__URLSearchParams__ = "__URLSearchParams__",
// Fix bug in Edge which cannot encode ' &' correctly
encodesAmpersandsCorrectly = nativeURLSearchParams
? (function () {
var ampersandTest = new nativeURLSearchParams();
ampersandTest.append("s", " &");
return ampersandTest.toString() === "s=+%26";
})()
: true,
prototype = URLSearchParamsPolyfill.prototype,
iterable = !!(self.Symbol && self.Symbol.iterator);
if (
nativeURLSearchParams &&
isSupportObjectConstructor &&
decodesPlusesCorrectly &&
encodesAmpersandsCorrectly
) {
return;
}
/**
* Make a URLSearchParams instance
*
* @param {object|string|URLSearchParams} search
* @constructor
*/
function URLSearchParamsPolyfill(search) {
search = search || "";
// support construct object with another URLSearchParams instance
if (
search instanceof URLSearchParams ||
search instanceof URLSearchParamsPolyfill
) {
search = search.toString();
}
this[__URLSearchParams__] = parseToDict(search);
}
/**
* Appends a specified key/value pair as a new search parameter.
*
* @param {string} name
* @param {string} value
*/
prototype.append = function (name, value) {
appendTo(this[__URLSearchParams__], name, value);
};
/**
* Deletes the given search parameter, and its associated value,
* from the list of all search parameters.
*
* @param {string} name
*/
prototype["delete"] = function (name) {
delete this[__URLSearchParams__][name];
};
/**
* Returns the first value associated to the given search parameter.
*
* @param {string} name
* @returns {string|null}
*/
prototype.get = function (name) {
var dict = this[__URLSearchParams__];
return this.has(name) ? dict[name][0] : null;
};
/**
* Returns all the values association with a given search parameter.
*
* @param {string} name
* @returns {Array}
*/
prototype.getAll = function (name) {
var dict = this[__URLSearchParams__];
return this.has(name) ? dict[name].slice(0) : [];
};
/**
* Returns a Boolean indicating if such a search parameter exists.
*
* @param {string} name
* @returns {boolean}
*/
prototype.has = function (name) {
return hasOwnProperty(this[__URLSearchParams__], name);
};
/**
* Sets the value associated to a given search parameter to
* the given value. If there were several values, delete the
* others.
*
* @param {string} name
* @param {string} value
*/
prototype.set = function set(name, value) {
this[__URLSearchParams__][name] = ["" + value];
};
/**
* Returns a string containg a query string suitable for use in a URL.
*
* @returns {string}
*/
prototype.toString = function () {
var dict = this[__URLSearchParams__],
query = [],
i,
key,
name,
value;
for (key in dict) {
name = encode(key);
for (i = 0, value = dict[key]; i < value.length; i++) {
query.push(name + "=" + encode(value[i]));
}
}
return query.join("&");
};
// There is a bug in Safari 10.1 and `Proxy`ing it is not enough.
var forSureUsePolyfill = !decodesPlusesCorrectly;
var useProxy =
!forSureUsePolyfill &&
nativeURLSearchParams &&
!isSupportObjectConstructor &&
self.Proxy;
var propValue;
if (useProxy) {
// Safari 10.0 doesn't support Proxy, so it won't extend URLSearchParams on safari 10.0
propValue = new Proxy(nativeURLSearchParams, {
construct: function (target, args) {
return new target(
new URLSearchParamsPolyfill(args[0]).toString()
);
},
});
// Chrome <=60 .toString() on a function proxy got error "Function.prototype.toString is not generic"
propValue.toString = Function.prototype.toString.bind(
URLSearchParamsPolyfill
);
} else {
propValue = URLSearchParamsPolyfill;
}
/*
* Apply polifill to global object and append other prototype into it
*/
Object.defineProperty(self, "URLSearchParams", {
value: propValue,
});
var USPProto = self.URLSearchParams.prototype;
USPProto.polyfill = true;
/**
*
* @param {function} callback
* @param {object} thisArg
*/
USPProto.forEach =
USPProto.forEach ||
function (callback, thisArg) {
var dict = parseToDict(this.toString());
Object.getOwnPropertyNames(dict).forEach(function (name) {
dict[name].forEach(function (value) {
callback.call(thisArg, value, name, this);
}, this);
}, this);
};
/**
* Sort all name-value pairs
*/
USPProto.sort =
USPProto.sort ||
function () {
var dict = parseToDict(this.toString()),
keys = [],
k,
i,
j;
for (k in dict) {
keys.push(k);
}
keys.sort();
for (i = 0; i < keys.length; i++) {
this["delete"](keys[i]);
}
for (i = 0; i < keys.length; i++) {
var key = keys[i],
values = dict[key];
for (j = 0; j < values.length; j++) {
this.append(key, values[j]);
}
}
};
/**
* Returns an iterator allowing to go through all keys of
* the key/value pairs contained in this object.
*
* @returns {function}
*/
USPProto.keys =
USPProto.keys ||
function () {
var items = [];
this.forEach(function (item, name) {
items.push(name);
});
return makeIterator(items);
};
/**
* Returns an iterator allowing to go through all values of
* the key/value pairs contained in this object.
*
* @returns {function}
*/
USPProto.values =
USPProto.values ||
function () {
var items = [];
this.forEach(function (item) {
items.push(item);
});
return makeIterator(items);
};
/**
* Returns an iterator allowing to go through all key/value
* pairs contained in this object.
*
* @returns {function}
*/
USPProto.entries =
USPProto.entries ||
function () {
var items = [];
this.forEach(function (item, name) {
items.push([name, item]);
});
return makeIterator(items);
};
if (iterable) {
USPProto[self.Symbol.iterator] =
USPProto[self.Symbol.iterator] || USPProto.entries;
}
function encode(str) {
var replace = {
"!": "%21",
"'": "%27",
"(": "%28",
")": "%29",
"~": "%7E",
"%20": "+",
"%00": "\x00",
};
return encodeURIComponent(str).replace(
/[!'\(\)~]|%20|%00/g,
function (match) {
return replace[match];
}
);
}
function decode(str) {
return str
.replace(/[ +]/g, "%20")
.replace(/(%[a-f0-9]{2})+/gi, function (match) {
return decodeURIComponent(match);
});
}
function makeIterator(arr) {
var iterator = {
next: function () {
var value = arr.shift();
return { done: value === undefined, value: value };
},
};
if (iterable) {
iterator[self.Symbol.iterator] = function () {
return iterator;
};
}
return iterator;
}
function parseToDict(search) {
var dict = {};
if (typeof search === "object") {
// if `search` is an array, treat it as a sequence
if (isArray(search)) {
for (var i = 0; i < search.length; i++) {
var item = search[i];
if (isArray(item) && item.length === 2) {
appendTo(dict, item[0], item[1]);
} else {
throw new TypeError(
"Failed to construct 'URLSearchParams': Sequence initializer must only contain pair elements"
);
}
}
} else {
for (var key in search) {
if (search.hasOwnProperty(key)) {
appendTo(dict, key, search[key]);
}
}
}
} else {
// remove first '?'
if (search.indexOf("?") === 0) {
search = search.slice(1);
}
var pairs = search.split("&");
for (var j = 0; j < pairs.length; j++) {
var value = pairs[j],
index = value.indexOf("=");
if (-1 < index) {
appendTo(
dict,
decode(value.slice(0, index)),
decode(value.slice(index + 1))
);
} else {
if (value) {
appendTo(dict, decode(value), "");
}
}
}
}
return dict;
}
function appendTo(dict, name, value) {
var val =
typeof value === "string"
? value
: value !== null &&
value !== undefined &&
typeof value.toString === "function"
? value.toString()
: JSON.stringify(value);
// #47 Prevent using `hasOwnProperty` as a property name
if (hasOwnProperty(dict, name)) {
dict[name].push(val);
} else {
dict[name] = [val];
}
}
function isArray(val) {
return (
!!val && "[object Array]" === Object.prototype.toString.call(val)
);
}
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
})(
typeof global !== "undefined"
? global
: typeof window !== "undefined"
? window
: this
);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2558/1/output.js | JavaScript | !/**!
* url-search-params-polyfill
*
* @author Jerry Bendy (https://github.com/jerrybendy)
* @licence MIT
*/ function(self) {
"use strict";
var ampersandTest, propValue, nativeURLSearchParams = function() {
// #41 Fix issue in RN
try {
if (self.URLSearchParams && "bar" === new self.URLSearchParams("foo=bar").get("foo")) return self.URLSearchParams;
} catch (e) {}
return null;
}(), isSupportObjectConstructor = nativeURLSearchParams && "a=1" === new nativeURLSearchParams({
a: 1
}).toString(), // There is a bug in safari 10.1 (and earlier) that incorrectly decodes `%2B` as an empty space and not a plus.
decodesPlusesCorrectly = nativeURLSearchParams && "+" === new nativeURLSearchParams("s=%2B").get("s"), __URLSearchParams__ = "__URLSearchParams__", // Fix bug in Edge which cannot encode ' &' correctly
encodesAmpersandsCorrectly = !nativeURLSearchParams || ((ampersandTest = new nativeURLSearchParams()).append("s", " &"), "s=+%26" === ampersandTest.toString()), prototype = URLSearchParamsPolyfill.prototype, iterable = !!(self.Symbol && self.Symbol.iterator);
if (!nativeURLSearchParams || !isSupportObjectConstructor || !decodesPlusesCorrectly || !encodesAmpersandsCorrectly) {
/**
* Appends a specified key/value pair as a new search parameter.
*
* @param {string} name
* @param {string} value
*/ prototype.append = function(name, value) {
appendTo(this[__URLSearchParams__], name, value);
}, /**
* Deletes the given search parameter, and its associated value,
* from the list of all search parameters.
*
* @param {string} name
*/ prototype.delete = function(name) {
delete this[__URLSearchParams__][name];
}, /**
* Returns the first value associated to the given search parameter.
*
* @param {string} name
* @returns {string|null}
*/ prototype.get = function(name) {
var dict = this[__URLSearchParams__];
return this.has(name) ? dict[name][0] : null;
}, /**
* Returns all the values association with a given search parameter.
*
* @param {string} name
* @returns {Array}
*/ prototype.getAll = function(name) {
var dict = this[__URLSearchParams__];
return this.has(name) ? dict[name].slice(0) : [];
}, /**
* Returns a Boolean indicating if such a search parameter exists.
*
* @param {string} name
* @returns {boolean}
*/ prototype.has = function(name) {
return hasOwnProperty(this[__URLSearchParams__], name);
}, /**
* Sets the value associated to a given search parameter to
* the given value. If there were several values, delete the
* others.
*
* @param {string} name
* @param {string} value
*/ prototype.set = function(name, value) {
this[__URLSearchParams__][name] = [
"" + value
];
}, /**
* Returns a string containg a query string suitable for use in a URL.
*
* @returns {string}
*/ prototype.toString = function() {
var i, key, name, value, dict = this[__URLSearchParams__], query = [];
for(key in dict)for(i = 0, name = encode(key), value = dict[key]; i < value.length; i++)query.push(name + "=" + encode(value[i]));
return query.join("&");
}, decodesPlusesCorrectly && nativeURLSearchParams && !isSupportObjectConstructor && self.Proxy ? // Chrome <=60 .toString() on a function proxy got error "Function.prototype.toString is not generic"
// Safari 10.0 doesn't support Proxy, so it won't extend URLSearchParams on safari 10.0
(propValue = new Proxy(nativeURLSearchParams, {
construct: function(target, args) {
return new target(new URLSearchParamsPolyfill(args[0]).toString());
}
})).toString = Function.prototype.toString.bind(URLSearchParamsPolyfill) : propValue = URLSearchParamsPolyfill, /*
* Apply polifill to global object and append other prototype into it
*/ Object.defineProperty(self, "URLSearchParams", {
value: propValue
});
var USPProto = self.URLSearchParams.prototype;
USPProto.polyfill = !0, /**
*
* @param {function} callback
* @param {object} thisArg
*/ USPProto.forEach = USPProto.forEach || function(callback, thisArg) {
var dict = parseToDict(this.toString());
Object.getOwnPropertyNames(dict).forEach(function(name) {
dict[name].forEach(function(value) {
callback.call(thisArg, value, name, this);
}, this);
}, this);
}, /**
* Sort all name-value pairs
*/ USPProto.sort = USPProto.sort || function() {
var k, i, j, dict = parseToDict(this.toString()), keys = [];
for(k in dict)keys.push(k);
for(keys.sort(), i = 0; i < keys.length; i++)this.delete(keys[i]);
for(i = 0; i < keys.length; i++){
var key = keys[i], values = dict[key];
for(j = 0; j < values.length; j++)this.append(key, values[j]);
}
}, /**
* Returns an iterator allowing to go through all keys of
* the key/value pairs contained in this object.
*
* @returns {function}
*/ USPProto.keys = USPProto.keys || function() {
var items = [];
return this.forEach(function(item, name) {
items.push(name);
}), makeIterator(items);
}, /**
* Returns an iterator allowing to go through all values of
* the key/value pairs contained in this object.
*
* @returns {function}
*/ USPProto.values = USPProto.values || function() {
var items = [];
return this.forEach(function(item) {
items.push(item);
}), makeIterator(items);
}, /**
* Returns an iterator allowing to go through all key/value
* pairs contained in this object.
*
* @returns {function}
*/ USPProto.entries = USPProto.entries || function() {
var items = [];
return this.forEach(function(item, name) {
items.push([
name,
item
]);
}), makeIterator(items);
}, iterable && (USPProto[self.Symbol.iterator] = USPProto[self.Symbol.iterator] || USPProto.entries);
}
/**
* Make a URLSearchParams instance
*
* @param {object|string|URLSearchParams} search
* @constructor
*/ function URLSearchParamsPolyfill(search) {
((search = search || "") instanceof URLSearchParams || search instanceof URLSearchParamsPolyfill) && (search = search.toString()), this[__URLSearchParams__] = parseToDict(search);
}
function encode(str) {
var replace = {
"!": "%21",
"'": "%27",
"(": "%28",
")": "%29",
"~": "%7E",
"%20": "+",
"%00": "\x00"
};
return encodeURIComponent(str).replace(/[!'\(\)~]|%20|%00/g, function(match) {
return replace[match];
});
}
function decode(str) {
return str.replace(/[ +]/g, "%20").replace(/(%[a-f0-9]{2})+/gi, function(match) {
return decodeURIComponent(match);
});
}
function makeIterator(arr) {
var iterator = {
next: function() {
var value = arr.shift();
return {
done: void 0 === value,
value: value
};
}
};
return iterable && (iterator[self.Symbol.iterator] = function() {
return iterator;
}), iterator;
}
function parseToDict(search) {
var dict = {};
if ("object" == typeof search) {
// if `search` is an array, treat it as a sequence
if (isArray(search)) for(var i = 0; i < search.length; i++){
var item = search[i];
if (isArray(item) && 2 === item.length) appendTo(dict, item[0], item[1]);
else throw TypeError("Failed to construct 'URLSearchParams': Sequence initializer must only contain pair elements");
}
else for(var key in search)search.hasOwnProperty(key) && appendTo(dict, key, search[key]);
} else {
// remove first '?'
0 === search.indexOf("?") && (search = search.slice(1));
for(var pairs = search.split("&"), j = 0; j < pairs.length; j++){
var value = pairs[j], index = value.indexOf("=");
-1 < index ? appendTo(dict, decode(value.slice(0, index)), decode(value.slice(index + 1))) : value && appendTo(dict, decode(value), "");
}
}
return dict;
}
function appendTo(dict, name, value) {
var val = "string" == typeof value ? value : null != value && "function" == typeof value.toString ? value.toString() : JSON.stringify(value);
// #47 Prevent using `hasOwnProperty` as a property name
hasOwnProperty(dict, name) ? dict[name].push(val) : dict[name] = [
val
];
}
function isArray(val) {
return !!val && "[object Array]" === Object.prototype.toString.call(val);
}
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}("undefined" != typeof global ? global : "undefined" != typeof window ? window : this);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2605/1/input.js | JavaScript | var a = function (state) {
return $6aPrw.atTheBeginningOfBlock(state) && $6aPrw.atTheEndOfBlock(state);
};
function b() {
findDeleteRange(state);
}
function findDeleteRange(state) {
if (!a(state) || $0204f19a3843e92f$export$7abbbf8335ec653(state)) {
return state;
} else {
return $04186525b01d7539$var$range();
}
}
function Foo() {
this.x = Foo;
this.insertFile = function () {
b();
};
}
console.log(cls);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2605/1/output.js | JavaScript | console.log(cls);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2614/1/input.js | JavaScript | expose(() => export_default);
var foo = require("70jDX");
var Value;
Value = foo.default;
var export_default = Value;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2614/1/output.js | JavaScript | expose(()=>export_default);
var export_default = require("70jDX").default;
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2679/input.js | JavaScript | (function () {
var a = {};
a.b = 1;
a = null;
})();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2679/output.js | JavaScript | !function() {
var a = {};
a.b = 1;
a = null;
}();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2779/1/input.js | JavaScript | const e = Math.random();
console.log(e === -1 / 0);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2779/1/output.js | JavaScript | console.log(Math.random() === -1 / 0);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2779/2/input.js | JavaScript | const t = Math.random();
console.log(1 / t == -1 / 0);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2779/2/output.js | JavaScript | console.log(1 / Math.random() == -1 / 0);
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2807/1/input.js | JavaScript | export default function A() {
console.log(123);
console.log.apply(console, arguments);
console.a.b.c(console, arguments);
console.any();
console.warn();
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2807/1/output.js | JavaScript | export default function A() {}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2923/1/input.js | JavaScript | export default function example(html) {
const test = () => {
return "test";
};
return html`${test()}`;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2923/1/output.js | JavaScript | export default function example(html) {
return html`${"test"}`;
}
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2926/1/input.js | JavaScript | export var webpackJsonpCallback = function (parentChunkLoadingFunction, data) {
/******/
var runtime = data[2];
//......
if (runtime) var result = runtime(__webpack_require__);
// return result
};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/2926/1/output.js | JavaScript | export var webpackJsonpCallback = function(parentChunkLoadingFunction, data) {
/******/ var runtime = data[2];
//......
runtime && runtime(__webpack_require__);
// return result
};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/3126/1/input.js | JavaScript | /******/ (() => {
// webpackBootstrap
/******/ var __webpack_modules__ = {
/***/ 746: /***/ (
__unused_webpack_module,
__unused_webpack___webpack_exports__,
__webpack_require__
) => {
// originally from react
const G = Object.prototype.hasOwnProperty;
// MY ACTUAL CODE
const baselinePx = 4;
const faderWidth = baselinePx * 12;
const faderHeight = baselinePx * 60;
const trackWidth = faderWidth / 3;
const trackHeight = faderHeight - faderWidth;
const trackMargin = (faderWidth - trackWidth) / 2;
// END MY ACTUAL CODE
/***/
},
/******/
};
/************************************************************************/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = __webpack_modules__;
/******/
/************************************************************************/
/******/ /* webpack/runtime/chunk loaded */
/******/ (() => {
/******/ __webpack_require__.O = (result, chunkIds, fn, priority) => {
/******/ for (var j = 0; j < chunkIds.length; j++) {
/******/ Object.keys(__webpack_require__.O).every((key) =>
__webpack_require__.O[key](chunkIds[j])
);
/******/
}
/******/
};
/******/
})();
/******/ var __webpack_exports__ = __webpack_require__.O(
undefined,
[532],
() => __webpack_require__(746)
);
/******/ __webpack_exports__ = __webpack_require__.O(__webpack_exports__);
/******/
})();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/3126/1/output.js | JavaScript | /******/ (()=>{
// webpackBootstrap
/******/ var __webpack_modules__ = {
/***/ 746: /***/ ()=>{
// originally from react
Object.prototype.hasOwnProperty;
// END MY ACTUAL CODE
/***/ }
};
/************************************************************************/ /******/ /******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = __webpack_modules__;
/******/ /************************************************************************/ /******/ /* webpack/runtime/chunk loaded */ /******/ (()=>{
/******/ __webpack_require__.O = (result, chunkIds)=>{
/******/ for(var j = 0; j < chunkIds.length; j++)/******/ Object.keys(__webpack_require__.O).every((key)=>__webpack_require__.O[key](chunkIds[j]));
/******/ };
/******/ })();
/******/ var __webpack_exports__ = __webpack_require__.O(void 0, [
532
], ()=>__webpack_require__(746));
/******/ __webpack_exports__ = __webpack_require__.O(__webpack_exports__);
/******/ })();
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University | |
crates/swc_ecma_minifier/tests/fixture/issues/3173/1/input.js | JavaScript | export const IndexPage = (value) => {
if (value === "loading") {
return 1;
} else if (value === "error") {
return 2;
} else {
return 3;
}
return 4;
};
| willcrichton/ilc-swc | 1 | Rust | willcrichton | Will Crichton | Brown University |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.