file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
copyfiles.py | from distutils.dir_util import copy_tree
import shutil
import os
def prepare_directory(path):
|
# copy resulting files into correct folders
print 'Copying files...',
in_out_dirs = [['./cpp', '../atom/src/proto'], ['./cs', '../client/AtomClientDX/proto']]
for curr in in_out_dirs:
prepare_directory(curr[1])
copy_tree(curr[0], curr[1])
print 'done!'
| shutil.rmtree(path, ignore_errors=True) # remove existing folder
if not os.path.isdir(path): # create folder
os.mkdir(path) |
complete_snippet.rs | //! FIXME: write short doc here
use crate::completion::{
completion_item::Builder, CompletionContext, CompletionItem, CompletionItemKind,
CompletionKind, Completions,
};
fn | (ctx: &CompletionContext, label: &str, snippet: &str) -> Builder {
CompletionItem::new(CompletionKind::Snippet, ctx.source_range(), label)
.insert_snippet(snippet)
.kind(CompletionItemKind::Snippet)
}
pub(super) fn complete_expr_snippet(acc: &mut Completions, ctx: &CompletionContext) {
if !(ctx.is_trivial_path && ctx.function_syntax.is_some()) {
return;
}
snippet(ctx, "pd", "eprintln!(\"$0 = {:?}\", $0);").add_to(acc);
snippet(ctx, "ppd", "eprintln!(\"$0 = {:#?}\", $0);").add_to(acc);
}
pub(super) fn complete_item_snippet(acc: &mut Completions, ctx: &CompletionContext) {
if !ctx.is_new_item {
return;
}
snippet(
ctx,
"Test function",
"\
#[test]
fn ${1:feature}() {
$0
}",
)
.lookup_by("tfn")
.add_to(acc);
snippet(ctx, "macro_rules", "macro_rules! $1 {\n\t($2) => {\n\t\t$0\n\t};\n}").add_to(acc);
snippet(ctx, "pub(crate)", "pub(crate) $0").add_to(acc);
}
#[cfg(test)]
mod tests {
use crate::completion::{test_utils::do_completion, CompletionItem, CompletionKind};
use insta::assert_debug_snapshot;
fn do_snippet_completion(code: &str) -> Vec<CompletionItem> {
do_completion(code, CompletionKind::Snippet)
}
#[test]
fn completes_snippets_in_expressions() {
assert_debug_snapshot!(
do_snippet_completion(r"fn foo(x: i32) { <|> }"),
@r###"
[
CompletionItem {
label: "pd",
source_range: [17; 17),
delete: [17; 17),
insert: "eprintln!(\"$0 = {:?}\", $0);",
kind: Snippet,
},
CompletionItem {
label: "ppd",
source_range: [17; 17),
delete: [17; 17),
insert: "eprintln!(\"$0 = {:#?}\", $0);",
kind: Snippet,
},
]
"###
);
}
#[test]
fn should_not_complete_snippets_in_path() {
assert_debug_snapshot!(
do_snippet_completion(r"fn foo(x: i32) { ::foo<|> }"),
@"[]"
);
assert_debug_snapshot!(
do_snippet_completion(r"fn foo(x: i32) { ::<|> }"),
@"[]"
);
}
#[test]
fn completes_snippets_in_items() {
assert_debug_snapshot!(
do_snippet_completion(
r"
#[cfg(test)]
mod tests {
<|>
}
"
),
@r###"
[
CompletionItem {
label: "Test function",
source_range: [78; 78),
delete: [78; 78),
insert: "#[test]\nfn ${1:feature}() {\n $0\n}",
kind: Snippet,
lookup: "tfn",
},
CompletionItem {
label: "macro_rules",
source_range: [78; 78),
delete: [78; 78),
insert: "macro_rules! $1 {\n\t($2) => {\n\t\t$0\n\t};\n}",
kind: Snippet,
},
CompletionItem {
label: "pub(crate)",
source_range: [78; 78),
delete: [78; 78),
insert: "pub(crate) $0",
kind: Snippet,
},
]
"###
);
}
}
| snippet |
geometry.rs | use std::fmt;
use std::cmp::{ max, min };
use std::ops::{ Sub, Add, Mul, BitXor };
#[derive(Debug, Clone, Copy)]
pub struct Vector2D<T> {
pub x: T,
pub y: T,
}
impl<T> Vector2D<T> {
pub fn new(x: T, y: T) -> Vector2D<T> {
Vector2D {
x,
y,
}
}
}
impl<T: fmt::Display> fmt::Display for Vector2D<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(x={}, y={})", self.x, self.y)
}
}
impl <T: Sub<Output = T>> Sub for Vector2D<T> {
type Output = Self;
fn sub(self, other: Vector2D<T>) -> Vector2D<T> {
Vector2D::new(self.x - other.x, self.y - other.y)
}
}
impl <T: Add<Output = T>> Add for Vector2D<T> {
type Output = Self;
| Vector2D::new(self.x + other.x, self.y + other.y)
}
}
impl <T: Mul<Output = T> + Add<Output = T>> Mul for Vector2D<T> {
type Output = T;
fn mul(self, other: Vector2D<T>) -> T {
self.x * other.x + self.y * other.y
}
}
impl <T: Mul<Output = T> + Copy> Mul<T> for Vector2D<T> {
type Output = Self;
fn mul(self, other: T) -> Vector2D<T> {
Vector2D::new(self.x * other, self.y * other)
}
}
#[derive(Debug, Clone, Copy)]
pub struct Vector3D<T> {
pub x: T,
pub y: T,
pub z: T,
}
impl<T> Vector3D<T> {
pub fn new(x: T, y: T, z: T) -> Vector3D<T> {
Vector3D {
x,
y,
z,
}
}
}
impl Vector3D<f32> {
pub fn norm(self) -> f32 {
(self.x * self.x + self.y * self.y + self.z * self.z).sqrt()
}
pub fn normalize(self) -> Vector3D<f32> {
let length = self.norm();
let inv_length = 1. / length;
self * inv_length
}
}
impl<T: fmt::Display> fmt::Display for Vector3D<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "(x={}, y={}, z={})", self.x, self.y, self.z)
}
}
impl <T: Sub<Output = T>> Sub for Vector3D<T> {
type Output = Self;
fn sub(self, other: Vector3D<T>) -> Vector3D<T> {
Vector3D::new(self.x - other.x, self.y - other.y, self.z - other.z)
}
}
impl <T: Add<Output = T>> Add for Vector3D<T> {
type Output = Self;
fn add(self, other: Vector3D<T>) -> Vector3D<T> {
Vector3D::new(self.x + other.x, self.y + other.y, self.z + other.z)
}
}
impl <T: Mul<Output = T> + Add<Output = T>> Mul for Vector3D<T> {
type Output = T;
fn mul(self, other: Vector3D<T>) -> T {
self.x * other.x + self.y * other.y + self.z * other.z
}
}
impl <T: Mul<Output = T> + Copy> Mul<T> for Vector3D<T> {
type Output = Self;
fn mul(self, other: T) -> Vector3D<T> {
Vector3D::new(self.x * other, self.y * other, self.z * other)
}
}
impl <T: Mul<Output = T> + Sub<Output = T> + Copy> BitXor for Vector3D<T> {
type Output = Self;
fn bitxor(self, other: Vector3D<T>) -> Vector3D<T> {
Vector3D::new(
self.y * other.z - self.z * other.y,
self.z * other.x - self.x * other.z,
self.x * other.y - self.y * other.x,
)
}
}
pub fn barycentric(
p: Vector2D<i32>,
pts: [Vector2D<i32>; 3],
) -> Vector3D<f32> {
let [t0, t1, t2] = pts;
let v1 = Vector3D::new(
(t2.x - t0.x) as f32,
(t1.x - t0.x) as f32,
(t0.x - p.x) as f32
);
let v2 = Vector3D::new(
(t2.y - t0.y) as f32,
(t1.y - t0.y) as f32,
(t0.y - p.y) as f32
);
let u = v1 ^ v2;
if u.z.abs() < 1.0 {
return Vector3D::new(-1.0, 1.0, 1.0);
}
return Vector3D::new(1.0 - (u.x + u.y) / u.z, u.y / u.z, u.x / u.z);
}
pub fn find_triangle_bounding_box(
pts: &[Vector2D<i32>; 3],
) -> [Vector2D<i32>; 2] {
let [t0, t1, t2] = pts;
let min_x = min(t0.x, min(t1.x, t2.x));
let max_x = max(t0.x, max(t1.x, t2.x));
let min_y = min(t0.y, min(t1.y, t2.y));
let max_y = max(t0.y, max(t1.y, t2.y));
let top_left = Vector2D::new(min_x, max_y);
let bottom_right = Vector2D::new(max_x, min_y);
return [top_left, bottom_right];
}
pub fn is_in_triangle(
p: &Vector2D<i32>,
pts: &[Vector2D<i32>; 3],
) -> bool {
let [t0, t1, t2] = pts;
let a_side = (t0.y - t1.y) * p.x + (t1.x - t0.x) * p.y + (t0.x * t1.y - t1.x * t0.y);
let b_side = (t1.y - t2.y) * p.x + (t2.x - t1.x) * p.y + (t1.x * t2.y - t2.x * t1.y);
let c_side = (t2.y - t0.y) * p.x + (t0.x - t2.x) * p.y + (t2.x * t0.y - t0.x * t2.y);
return (a_side >= 0 && b_side >= 0 && c_side >=0) || (a_side < 0 && b_side < 0 && c_side < 0 );
} | fn add(self, other: Vector2D<T>) -> Vector2D<T> { |
setup.go | package cmca
import (
"time"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/source"
"github.com/openshift/ibm-roks-toolkit/pkg/cmd/cpoperator"
"github.com/openshift/ibm-roks-toolkit/pkg/controllers"
)
const (
ManagedConfigNamespace = "openshift-config-managed"
ControllerManagerAdditionalCAConfigMap = "controller-manager-additional-ca"
syncInterval = 10 * time.Minute
)
func Setup(cfg *cpoperator.ControlPlaneOperatorConfig) error {
if err := setupConfigMapObserver(cfg); err != nil {
return err
}
return nil
}
func setupConfigMapObserver(cfg *cpoperator.ControlPlaneOperatorConfig) error {
informerFactory := cfg.TargetKubeInformersForNamespaceWithInterval(ManagedConfigNamespace, syncInterval)
configMaps := informerFactory.Core().V1().ConfigMaps()
reconciler := &ManagedCAObserver{
InitialCA: cfg.InitialCA(),
Client: cfg.KubeClient(),
TargetClient: cfg.TargetKubeClient(),
Namespace: cfg.Namespace(),
Log: cfg.Logger().WithName("ManagedCAObserver"),
}
c, err := controller.New("ca-configmap-observer", cfg.Manager(), controller.Options{Reconciler: reconciler})
if err != nil {
return err
}
if err := c.Watch(&source.Informer{Informer: configMaps.Informer()}, controllers.NamedResourceHandler(RouterCAConfigMap, ServiceCAConfigMap)); err != nil |
return nil
}
| {
return err
} |
implements_impl.rs | #![ allow( missing_docs ) ]
#[ doc( hidden ) ] | macro_rules! _implements
{
( $V : expr => $( $Traits : tt )+ ) =>
{{
use ::core::marker::PhantomData;
trait False
{
fn get( self : &'_ Self ) -> bool { false }
}
impl< T > False
for &'_ PhantomData< T >
where T : ?Sized,
{}
trait True
{
fn get( self : &'_ Self ) -> bool { true }
}
impl< T > True
for PhantomData< T >
where T : $( $Traits )+ + ?Sized,
{}
fn does< T : Sized >( _ : &T ) -> PhantomData< T >
{
PhantomData
}
( &does( &$V ) ).get()
}}
} | #[ macro_export ] |
mod.rs | pub mod structs;
use structs::done::Done;
use structs::pending::Pending;
pub enum ItemTypes {
Pending(Pending), | /// This function builds and returns to do structs.
///
/// # Augments
/// * item_type (String): the type of struct to be built and returned
/// * item_title (String): the title for the item to be built
///
/// # Returns
/// (Result<ItemTypes, &'templates str>):
pub fn to_do_factory(item_type: String, item_title: String) -> Result<ItemTypes, &'static str> {
if item_type == "pending" {
let pending_item = Pending::new(item_title);
Ok(ItemTypes::Pending(pending_item))
}
else if item_type == "done" {
let done_item = Done::new(item_title);
Ok(ItemTypes::Done(done_item))
}
else {
Err("this is not accepted")
}
} | Done(Done)
}
|
global_vars.py | import os
| PROJECT_DIR = os.path.abspath(os.pardir)
RUN_DIR = os.path.join(PROJECT_DIR, "runs/")
DATA_DIR = os.path.join(PROJECT_DIR, "data/")
EMBEDDINGS_DIR = os.path.join(PROJECT_DIR, "embeddings/") |
|
intrinsics.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! rustc compiler intrinsics.
//!
//! The corresponding definitions are in librustc_trans/intrinsic.rs.
//!
//! # Volatiles
//!
//! The volatile intrinsics provide operations intended to act on I/O
//! memory, which are guaranteed to not be reordered by the compiler
//! across other volatile intrinsics. See the LLVM documentation on
//! [[volatile]].
//!
//! [volatile]: http://llvm.org/docs/LangRef.html#volatile-memory-accesses
//!
//! # Atomics
//!
//! The atomic intrinsics provide common atomic operations on machine
//! words, with multiple possible memory orderings. They obey the same
//! semantics as C++11. See the LLVM documentation on [[atomics]].
//!
//! [atomics]: http://llvm.org/docs/Atomics.html
//!
//! A quick refresher on memory ordering:
//!
//! * Acquire - a barrier for acquiring a lock. Subsequent reads and writes
//! take place after the barrier.
//! * Release - a barrier for releasing a lock. Preceding reads and writes
//! take place before the barrier.
//! * Sequentially consistent - sequentially consistent operations are
//! guaranteed to happen in order. This is the standard mode for working
//! with atomic types and is equivalent to Java's `volatile`.
#![unstable(feature = "core_intrinsics",
reason = "intrinsics are unlikely to ever be stabilized, instead \
they should be used through stabilized interfaces \
in the rest of the standard library",
issue = "0")]
#![allow(missing_docs)]
#[stable(feature = "drop_in_place", since = "1.8.0")]
#[rustc_deprecated(reason = "no longer an intrinsic - use `ptr::drop_in_place` directly",
since = "1.18.0")]
pub use ptr::drop_in_place;
extern "rust-intrinsic" {
// NB: These intrinsics take raw pointers because they mutate aliased
// memory, which is not valid for either `&` or `&mut`.
/// Stores a value if the current value is the same as the `old` value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `compare_exchange` method by passing
/// [`Ordering::SeqCst`](../../std/sync/atomic/enum.Ordering.html)
/// as both the `success` and `failure` parameters. For example,
/// [`AtomicBool::compare_exchange`][compare_exchange].
///
/// [compare_exchange]: ../../std/sync/atomic/struct.AtomicBool.html#method.compare_exchange
pub fn atomic_cxchg<T>(dst: *mut T, old: T, src: T) -> (T, bool);
/// Stores a value if the current value is the same as the `old` value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `compare_exchange` method by passing
/// [`Ordering::Acquire`](../../std/sync/atomic/enum.Ordering.html)
/// as both the `success` and `failure` parameters. For example,
/// [`AtomicBool::compare_exchange`][compare_exchange].
///
/// [compare_exchange]: ../../std/sync/atomic/struct.AtomicBool.html#method.compare_exchange
pub fn atomic_cxchg_acq<T>(dst: *mut T, old: T, src: T) -> (T, bool);
/// Stores a value if the current value is the same as the `old` value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `compare_exchange` method by passing
/// [`Ordering::Release`](../../std/sync/atomic/enum.Ordering.html)
/// as the `success` and
/// [`Ordering::Relaxed`](../../std/sync/atomic/enum.Ordering.html)
/// as the `failure` parameters. For example,
/// [`AtomicBool::compare_exchange`][compare_exchange].
///
/// [compare_exchange]: ../../std/sync/atomic/struct.AtomicBool.html#method.compare_exchange
pub fn atomic_cxchg_rel<T>(dst: *mut T, old: T, src: T) -> (T, bool);
/// Stores a value if the current value is the same as the `old` value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `compare_exchange` method by passing
/// [`Ordering::AcqRel`](../../std/sync/atomic/enum.Ordering.html)
/// as the `success` and
/// [`Ordering::Acquire`](../../std/sync/atomic/enum.Ordering.html)
/// as the `failure` parameters. For example,
/// [`AtomicBool::compare_exchange`][compare_exchange].
///
/// [compare_exchange]: ../../std/sync/atomic/struct.AtomicBool.html#method.compare_exchange
pub fn atomic_cxchg_acqrel<T>(dst: *mut T, old: T, src: T) -> (T, bool);
/// Stores a value if the current value is the same as the `old` value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `compare_exchange` method by passing
/// [`Ordering::Relaxed`](../../std/sync/atomic/enum.Ordering.html)
/// as both the `success` and `failure` parameters. For example,
/// [`AtomicBool::compare_exchange`][compare_exchange].
///
/// [compare_exchange]: ../../std/sync/atomic/struct.AtomicBool.html#method.compare_exchange
pub fn atomic_cxchg_relaxed<T>(dst: *mut T, old: T, src: T) -> (T, bool);
/// Stores a value if the current value is the same as the `old` value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `compare_exchange` method by passing
/// [`Ordering::SeqCst`](../../std/sync/atomic/enum.Ordering.html)
/// as the `success` and
/// [`Ordering::Relaxed`](../../std/sync/atomic/enum.Ordering.html)
/// as the `failure` parameters. For example,
/// [`AtomicBool::compare_exchange`][compare_exchange].
///
/// [compare_exchange]: ../../std/sync/atomic/struct.AtomicBool.html#method.compare_exchange
pub fn atomic_cxchg_failrelaxed<T>(dst: *mut T, old: T, src: T) -> (T, bool);
/// Stores a value if the current value is the same as the `old` value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `compare_exchange` method by passing
/// [`Ordering::SeqCst`](../../std/sync/atomic/enum.Ordering.html)
/// as the `success` and
/// [`Ordering::Acquire`](../../std/sync/atomic/enum.Ordering.html)
/// as the `failure` parameters. For example,
/// [`AtomicBool::compare_exchange`][compare_exchange].
///
/// [compare_exchange]: ../../std/sync/atomic/struct.AtomicBool.html#method.compare_exchange
pub fn atomic_cxchg_failacq<T>(dst: *mut T, old: T, src: T) -> (T, bool);
/// Stores a value if the current value is the same as the `old` value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `compare_exchange` method by passing
/// [`Ordering::Acquire`](../../std/sync/atomic/enum.Ordering.html)
/// as the `success` and
/// [`Ordering::Relaxed`](../../std/sync/atomic/enum.Ordering.html)
/// as the `failure` parameters. For example,
/// [`AtomicBool::compare_exchange`][compare_exchange].
///
/// [compare_exchange]: ../../std/sync/atomic/struct.AtomicBool.html#method.compare_exchange
pub fn atomic_cxchg_acq_failrelaxed<T>(dst: *mut T, old: T, src: T) -> (T, bool);
/// Stores a value if the current value is the same as the `old` value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `compare_exchange` method by passing
/// [`Ordering::AcqRel`](../../std/sync/atomic/enum.Ordering.html)
/// as the `success` and
/// [`Ordering::Relaxed`](../../std/sync/atomic/enum.Ordering.html)
/// as the `failure` parameters. For example,
/// [`AtomicBool::compare_exchange`][compare_exchange].
///
/// [compare_exchange]: ../../std/sync/atomic/struct.AtomicBool.html#method.compare_exchange
pub fn atomic_cxchg_acqrel_failrelaxed<T>(dst: *mut T, old: T, src: T) -> (T, bool);
/// Stores a value if the current value is the same as the `old` value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `compare_exchange_weak` method by passing
/// [`Ordering::SeqCst`](../../std/sync/atomic/enum.Ordering.html)
/// as both the `success` and `failure` parameters. For example,
/// [`AtomicBool::compare_exchange_weak`][cew].
///
/// [cew]: ../../std/sync/atomic/struct.AtomicBool.html#method.compare_exchange_weak
pub fn atomic_cxchgweak<T>(dst: *mut T, old: T, src: T) -> (T, bool);
/// Stores a value if the current value is the same as the `old` value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `compare_exchange_weak` method by passing
/// [`Ordering::Acquire`](../../std/sync/atomic/enum.Ordering.html)
/// as both the `success` and `failure` parameters. For example,
/// [`AtomicBool::compare_exchange_weak`][cew].
///
/// [cew]: ../../std/sync/atomic/struct.AtomicBool.html#method.compare_exchange_weak
pub fn atomic_cxchgweak_acq<T>(dst: *mut T, old: T, src: T) -> (T, bool);
/// Stores a value if the current value is the same as the `old` value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `compare_exchange_weak` method by passing
/// [`Ordering::Release`](../../std/sync/atomic/enum.Ordering.html)
/// as the `success` and
/// [`Ordering::Relaxed`](../../std/sync/atomic/enum.Ordering.html)
/// as the `failure` parameters. For example,
/// [`AtomicBool::compare_exchange_weak`][cew].
///
/// [cew]: ../../std/sync/atomic/struct.AtomicBool.html#method.compare_exchange_weak
pub fn atomic_cxchgweak_rel<T>(dst: *mut T, old: T, src: T) -> (T, bool);
/// Stores a value if the current value is the same as the `old` value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `compare_exchange_weak` method by passing
/// [`Ordering::AcqRel`](../../std/sync/atomic/enum.Ordering.html)
/// as the `success` and
/// [`Ordering::Acquire`](../../std/sync/atomic/enum.Ordering.html)
/// as the `failure` parameters. For example,
/// [`AtomicBool::compare_exchange_weak`][cew].
///
/// [cew]: ../../std/sync/atomic/struct.AtomicBool.html#method.compare_exchange_weak
pub fn atomic_cxchgweak_acqrel<T>(dst: *mut T, old: T, src: T) -> (T, bool);
/// Stores a value if the current value is the same as the `old` value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `compare_exchange_weak` method by passing
/// [`Ordering::Relaxed`](../../std/sync/atomic/enum.Ordering.html)
/// as both the `success` and `failure` parameters. For example,
/// [`AtomicBool::compare_exchange_weak`][cew].
///
/// [cew]: ../../std/sync/atomic/struct.AtomicBool.html#method.compare_exchange_weak
pub fn atomic_cxchgweak_relaxed<T>(dst: *mut T, old: T, src: T) -> (T, bool);
/// Stores a value if the current value is the same as the `old` value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `compare_exchange_weak` method by passing
/// [`Ordering::SeqCst`](../../std/sync/atomic/enum.Ordering.html)
/// as the `success` and
/// [`Ordering::Relaxed`](../../std/sync/atomic/enum.Ordering.html)
/// as the `failure` parameters. For example,
/// [`AtomicBool::compare_exchange_weak`][cew].
///
/// [cew]: ../../std/sync/atomic/struct.AtomicBool.html#method.compare_exchange_weak
pub fn atomic_cxchgweak_failrelaxed<T>(dst: *mut T, old: T, src: T) -> (T, bool);
/// Stores a value if the current value is the same as the `old` value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `compare_exchange_weak` method by passing
/// [`Ordering::SeqCst`](../../std/sync/atomic/enum.Ordering.html)
/// as the `success` and
/// [`Ordering::Acquire`](../../std/sync/atomic/enum.Ordering.html)
/// as the `failure` parameters. For example,
/// [`AtomicBool::compare_exchange_weak`][cew].
///
/// [cew]: ../../std/sync/atomic/struct.AtomicBool.html#method.compare_exchange_weak
pub fn atomic_cxchgweak_failacq<T>(dst: *mut T, old: T, src: T) -> (T, bool);
/// Stores a value if the current value is the same as the `old` value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `compare_exchange_weak` method by passing
/// [`Ordering::Acquire`](../../std/sync/atomic/enum.Ordering.html)
/// as the `success` and
/// [`Ordering::Relaxed`](../../std/sync/atomic/enum.Ordering.html)
/// as the `failure` parameters. For example,
/// [`AtomicBool::compare_exchange_weak`][cew].
///
/// [cew]: ../../std/sync/atomic/struct.AtomicBool.html#method.compare_exchange_weak
pub fn atomic_cxchgweak_acq_failrelaxed<T>(dst: *mut T, old: T, src: T) -> (T, bool);
/// Stores a value if the current value is the same as the `old` value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `compare_exchange_weak` method by passing
/// [`Ordering::AcqRel`](../../std/sync/atomic/enum.Ordering.html)
/// as the `success` and
/// [`Ordering::Relaxed`](../../std/sync/atomic/enum.Ordering.html)
/// as the `failure` parameters. For example,
/// [`AtomicBool::compare_exchange_weak`][cew].
///
/// [cew]: ../../std/sync/atomic/struct.AtomicBool.html#method.compare_exchange_weak
pub fn atomic_cxchgweak_acqrel_failrelaxed<T>(dst: *mut T, old: T, src: T) -> (T, bool);
/// Loads the current value of the pointer.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `load` method by passing
/// [`Ordering::SeqCst`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::load`](../../std/sync/atomic/struct.AtomicBool.html#method.load).
pub fn atomic_load<T>(src: *const T) -> T;
/// Loads the current value of the pointer.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `load` method by passing
/// [`Ordering::Acquire`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::load`](../../std/sync/atomic/struct.AtomicBool.html#method.load).
pub fn atomic_load_acq<T>(src: *const T) -> T;
/// Loads the current value of the pointer.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `load` method by passing
/// [`Ordering::Relaxed`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::load`](../../std/sync/atomic/struct.AtomicBool.html#method.load).
pub fn atomic_load_relaxed<T>(src: *const T) -> T;
pub fn atomic_load_unordered<T>(src: *const T) -> T;
/// Stores the value at the specified memory location.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `store` method by passing
/// [`Ordering::SeqCst`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::store`](../../std/sync/atomic/struct.AtomicBool.html#method.store).
pub fn atomic_store<T>(dst: *mut T, val: T);
/// Stores the value at the specified memory location.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `store` method by passing
/// [`Ordering::Release`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::store`](../../std/sync/atomic/struct.AtomicBool.html#method.store).
pub fn atomic_store_rel<T>(dst: *mut T, val: T);
/// Stores the value at the specified memory location.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `store` method by passing
/// [`Ordering::Relaxed`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::store`](../../std/sync/atomic/struct.AtomicBool.html#method.store).
pub fn atomic_store_relaxed<T>(dst: *mut T, val: T);
pub fn atomic_store_unordered<T>(dst: *mut T, val: T);
/// Stores the value at the specified memory location, returning the old value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `swap` method by passing
/// [`Ordering::SeqCst`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::swap`](../../std/sync/atomic/struct.AtomicBool.html#method.swap).
pub fn atomic_xchg<T>(dst: *mut T, src: T) -> T;
/// Stores the value at the specified memory location, returning the old value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `swap` method by passing
/// [`Ordering::Acquire`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::swap`](../../std/sync/atomic/struct.AtomicBool.html#method.swap).
pub fn atomic_xchg_acq<T>(dst: *mut T, src: T) -> T;
/// Stores the value at the specified memory location, returning the old value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `swap` method by passing
/// [`Ordering::Release`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::swap`](../../std/sync/atomic/struct.AtomicBool.html#method.swap).
pub fn atomic_xchg_rel<T>(dst: *mut T, src: T) -> T;
/// Stores the value at the specified memory location, returning the old value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `swap` method by passing
/// [`Ordering::AcqRel`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::swap`](../../std/sync/atomic/struct.AtomicBool.html#method.swap).
pub fn atomic_xchg_acqrel<T>(dst: *mut T, src: T) -> T;
/// Stores the value at the specified memory location, returning the old value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `swap` method by passing
/// [`Ordering::Relaxed`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::swap`](../../std/sync/atomic/struct.AtomicBool.html#method.swap).
pub fn atomic_xchg_relaxed<T>(dst: *mut T, src: T) -> T;
/// Add to the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_add` method by passing
/// [`Ordering::SeqCst`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicIsize::fetch_add`](../../std/sync/atomic/struct.AtomicIsize.html#method.fetch_add).
pub fn atomic_xadd<T>(dst: *mut T, src: T) -> T;
/// Add to the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_add` method by passing
/// [`Ordering::Acquire`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicIsize::fetch_add`](../../std/sync/atomic/struct.AtomicIsize.html#method.fetch_add).
pub fn atomic_xadd_acq<T>(dst: *mut T, src: T) -> T;
/// Add to the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_add` method by passing
/// [`Ordering::Release`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicIsize::fetch_add`](../../std/sync/atomic/struct.AtomicIsize.html#method.fetch_add).
pub fn atomic_xadd_rel<T>(dst: *mut T, src: T) -> T;
/// Add to the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_add` method by passing
/// [`Ordering::AcqRel`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicIsize::fetch_add`](../../std/sync/atomic/struct.AtomicIsize.html#method.fetch_add).
pub fn atomic_xadd_acqrel<T>(dst: *mut T, src: T) -> T;
/// Add to the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_add` method by passing
/// [`Ordering::Relaxed`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicIsize::fetch_add`](../../std/sync/atomic/struct.AtomicIsize.html#method.fetch_add).
pub fn atomic_xadd_relaxed<T>(dst: *mut T, src: T) -> T;
/// Subtract from the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_sub` method by passing
/// [`Ordering::SeqCst`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicIsize::fetch_sub`](../../std/sync/atomic/struct.AtomicIsize.html#method.fetch_sub).
pub fn atomic_xsub<T>(dst: *mut T, src: T) -> T;
/// Subtract from the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_sub` method by passing
/// [`Ordering::Acquire`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicIsize::fetch_sub`](../../std/sync/atomic/struct.AtomicIsize.html#method.fetch_sub).
pub fn atomic_xsub_acq<T>(dst: *mut T, src: T) -> T;
/// Subtract from the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_sub` method by passing
/// [`Ordering::Release`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicIsize::fetch_sub`](../../std/sync/atomic/struct.AtomicIsize.html#method.fetch_sub).
pub fn atomic_xsub_rel<T>(dst: *mut T, src: T) -> T;
/// Subtract from the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_sub` method by passing
/// [`Ordering::AcqRel`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicIsize::fetch_sub`](../../std/sync/atomic/struct.AtomicIsize.html#method.fetch_sub).
pub fn atomic_xsub_acqrel<T>(dst: *mut T, src: T) -> T;
/// Subtract from the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_sub` method by passing
/// [`Ordering::Relaxed`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicIsize::fetch_sub`](../../std/sync/atomic/struct.AtomicIsize.html#method.fetch_sub).
pub fn atomic_xsub_relaxed<T>(dst: *mut T, src: T) -> T;
/// Bitwise and with the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_and` method by passing
/// [`Ordering::SeqCst`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::fetch_and`](../../std/sync/atomic/struct.AtomicBool.html#method.fetch_and).
pub fn atomic_and<T>(dst: *mut T, src: T) -> T;
/// Bitwise and with the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_and` method by passing
/// [`Ordering::Acquire`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::fetch_and`](../../std/sync/atomic/struct.AtomicBool.html#method.fetch_and).
pub fn atomic_and_acq<T>(dst: *mut T, src: T) -> T;
/// Bitwise and with the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_and` method by passing
/// [`Ordering::Release`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::fetch_and`](../../std/sync/atomic/struct.AtomicBool.html#method.fetch_and).
pub fn atomic_and_rel<T>(dst: *mut T, src: T) -> T;
/// Bitwise and with the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_and` method by passing
/// [`Ordering::AcqRel`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::fetch_and`](../../std/sync/atomic/struct.AtomicBool.html#method.fetch_and).
pub fn atomic_and_acqrel<T>(dst: *mut T, src: T) -> T;
/// Bitwise and with the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_and` method by passing
/// [`Ordering::Relaxed`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::fetch_and`](../../std/sync/atomic/struct.AtomicBool.html#method.fetch_and).
pub fn atomic_and_relaxed<T>(dst: *mut T, src: T) -> T;
/// Bitwise nand with the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic::AtomicBool` type via the `fetch_nand` method by passing
/// [`Ordering::SeqCst`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::fetch_nand`](../../std/sync/atomic/struct.AtomicBool.html#method.fetch_nand).
pub fn atomic_nand<T>(dst: *mut T, src: T) -> T;
/// Bitwise nand with the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic::AtomicBool` type via the `fetch_nand` method by passing
/// [`Ordering::Acquire`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::fetch_nand`](../../std/sync/atomic/struct.AtomicBool.html#method.fetch_nand).
pub fn atomic_nand_acq<T>(dst: *mut T, src: T) -> T;
/// Bitwise nand with the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic::AtomicBool` type via the `fetch_nand` method by passing
/// [`Ordering::Release`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::fetch_nand`](../../std/sync/atomic/struct.AtomicBool.html#method.fetch_nand).
pub fn atomic_nand_rel<T>(dst: *mut T, src: T) -> T;
/// Bitwise nand with the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic::AtomicBool` type via the `fetch_nand` method by passing
/// [`Ordering::AcqRel`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::fetch_nand`](../../std/sync/atomic/struct.AtomicBool.html#method.fetch_nand).
pub fn atomic_nand_acqrel<T>(dst: *mut T, src: T) -> T;
/// Bitwise nand with the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic::AtomicBool` type via the `fetch_nand` method by passing
/// [`Ordering::Relaxed`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::fetch_nand`](../../std/sync/atomic/struct.AtomicBool.html#method.fetch_nand).
pub fn atomic_nand_relaxed<T>(dst: *mut T, src: T) -> T;
/// Bitwise or with the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_or` method by passing
/// [`Ordering::SeqCst`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::fetch_or`](../../std/sync/atomic/struct.AtomicBool.html#method.fetch_or).
pub fn atomic_or<T>(dst: *mut T, src: T) -> T;
/// Bitwise or with the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_or` method by passing
/// [`Ordering::Acquire`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::fetch_or`](../../std/sync/atomic/struct.AtomicBool.html#method.fetch_or).
pub fn atomic_or_acq<T>(dst: *mut T, src: T) -> T;
/// Bitwise or with the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_or` method by passing
/// [`Ordering::Release`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::fetch_or`](../../std/sync/atomic/struct.AtomicBool.html#method.fetch_or).
pub fn atomic_or_rel<T>(dst: *mut T, src: T) -> T;
/// Bitwise or with the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_or` method by passing
/// [`Ordering::AcqRel`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::fetch_or`](../../std/sync/atomic/struct.AtomicBool.html#method.fetch_or).
pub fn atomic_or_acqrel<T>(dst: *mut T, src: T) -> T;
/// Bitwise or with the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_or` method by passing
/// [`Ordering::Relaxed`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::fetch_or`](../../std/sync/atomic/struct.AtomicBool.html#method.fetch_or).
pub fn atomic_or_relaxed<T>(dst: *mut T, src: T) -> T;
/// Bitwise xor with the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_xor` method by passing
/// [`Ordering::SeqCst`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::fetch_xor`](../../std/sync/atomic/struct.AtomicBool.html#method.fetch_xor).
pub fn atomic_xor<T>(dst: *mut T, src: T) -> T;
/// Bitwise xor with the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_xor` method by passing
/// [`Ordering::Acquire`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::fetch_xor`](../../std/sync/atomic/struct.AtomicBool.html#method.fetch_xor).
pub fn atomic_xor_acq<T>(dst: *mut T, src: T) -> T;
/// Bitwise xor with the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_xor` method by passing
/// [`Ordering::Release`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::fetch_xor`](../../std/sync/atomic/struct.AtomicBool.html#method.fetch_xor).
pub fn atomic_xor_rel<T>(dst: *mut T, src: T) -> T;
/// Bitwise xor with the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_xor` method by passing
/// [`Ordering::AcqRel`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::fetch_xor`](../../std/sync/atomic/struct.AtomicBool.html#method.fetch_xor).
pub fn atomic_xor_acqrel<T>(dst: *mut T, src: T) -> T;
/// Bitwise xor with the current value, returning the previous value.
/// The stabilized version of this intrinsic is available on the
/// `std::sync::atomic` types via the `fetch_xor` method by passing
/// [`Ordering::Relaxed`](../../std/sync/atomic/enum.Ordering.html)
/// as the `order`. For example,
/// [`AtomicBool::fetch_xor`](../../std/sync/atomic/struct.AtomicBool.html#method.fetch_xor).
pub fn atomic_xor_relaxed<T>(dst: *mut T, src: T) -> T;
pub fn atomic_max<T>(dst: *mut T, src: T) -> T;
pub fn atomic_max_acq<T>(dst: *mut T, src: T) -> T;
pub fn atomic_max_rel<T>(dst: *mut T, src: T) -> T;
pub fn atomic_max_acqrel<T>(dst: *mut T, src: T) -> T;
pub fn atomic_max_relaxed<T>(dst: *mut T, src: T) -> T;
pub fn atomic_min<T>(dst: *mut T, src: T) -> T;
pub fn atomic_min_acq<T>(dst: *mut T, src: T) -> T; |
pub fn atomic_umin<T>(dst: *mut T, src: T) -> T;
pub fn atomic_umin_acq<T>(dst: *mut T, src: T) -> T;
pub fn atomic_umin_rel<T>(dst: *mut T, src: T) -> T;
pub fn atomic_umin_acqrel<T>(dst: *mut T, src: T) -> T;
pub fn atomic_umin_relaxed<T>(dst: *mut T, src: T) -> T;
pub fn atomic_umax<T>(dst: *mut T, src: T) -> T;
pub fn atomic_umax_acq<T>(dst: *mut T, src: T) -> T;
pub fn atomic_umax_rel<T>(dst: *mut T, src: T) -> T;
pub fn atomic_umax_acqrel<T>(dst: *mut T, src: T) -> T;
pub fn atomic_umax_relaxed<T>(dst: *mut T, src: T) -> T;
/// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction
/// if supported; otherwise, it is a noop.
/// Prefetches have no effect on the behavior of the program but can change its performance
/// characteristics.
///
/// The `locality` argument must be a constant integer and is a temporal locality specifier
/// ranging from (0) - no locality, to (3) - extremely local keep in cache
pub fn prefetch_read_data<T>(data: *const T, locality: i32);
/// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction
/// if supported; otherwise, it is a noop.
/// Prefetches have no effect on the behavior of the program but can change its performance
/// characteristics.
///
/// The `locality` argument must be a constant integer and is a temporal locality specifier
/// ranging from (0) - no locality, to (3) - extremely local keep in cache
pub fn prefetch_write_data<T>(data: *const T, locality: i32);
/// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction
/// if supported; otherwise, it is a noop.
/// Prefetches have no effect on the behavior of the program but can change its performance
/// characteristics.
///
/// The `locality` argument must be a constant integer and is a temporal locality specifier
/// ranging from (0) - no locality, to (3) - extremely local keep in cache
pub fn prefetch_read_instruction<T>(data: *const T, locality: i32);
/// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction
/// if supported; otherwise, it is a noop.
/// Prefetches have no effect on the behavior of the program but can change its performance
/// characteristics.
///
/// The `locality` argument must be a constant integer and is a temporal locality specifier
/// ranging from (0) - no locality, to (3) - extremely local keep in cache
pub fn prefetch_write_instruction<T>(data: *const T, locality: i32);
}
extern "rust-intrinsic" {
pub fn atomic_fence();
pub fn atomic_fence_acq();
pub fn atomic_fence_rel();
pub fn atomic_fence_acqrel();
/// A compiler-only memory barrier.
///
/// Memory accesses will never be reordered across this barrier by the
/// compiler, but no instructions will be emitted for it. This is
/// appropriate for operations on the same thread that may be preempted,
/// such as when interacting with signal handlers.
pub fn atomic_singlethreadfence();
pub fn atomic_singlethreadfence_acq();
pub fn atomic_singlethreadfence_rel();
pub fn atomic_singlethreadfence_acqrel();
/// Magic intrinsic that derives its meaning from attributes
/// attached to the function.
///
/// For example, dataflow uses this to inject static assertions so
/// that `rustc_peek(potentially_uninitialized)` would actually
/// double-check that dataflow did indeed compute that it is
/// uninitialized at that point in the control flow.
pub fn rustc_peek<T>(_: T) -> T;
/// Aborts the execution of the process.
pub fn abort() -> !;
/// Tells LLVM that this point in the code is not reachable, enabling
/// further optimizations.
///
/// NB: This is very different from the `unreachable!()` macro: Unlike the
/// macro, which panics when it is executed, it is *undefined behavior* to
/// reach code marked with this function.
pub fn unreachable() -> !;
/// Informs the optimizer that a condition is always true.
/// If the condition is false, the behavior is undefined.
///
/// No code is generated for this intrinsic, but the optimizer will try
/// to preserve it (and its condition) between passes, which may interfere
/// with optimization of surrounding code and reduce performance. It should
/// not be used if the invariant can be discovered by the optimizer on its
/// own, or if it does not enable any significant optimizations.
pub fn assume(b: bool);
/// Hints to the compiler that branch condition is likely to be true.
/// Returns the value passed to it.
///
/// Any use other than with `if` statements will probably not have an effect.
pub fn likely(b: bool) -> bool;
/// Hints to the compiler that branch condition is likely to be false.
/// Returns the value passed to it.
///
/// Any use other than with `if` statements will probably not have an effect.
pub fn unlikely(b: bool) -> bool;
/// Executes a breakpoint trap, for inspection by a debugger.
pub fn breakpoint();
/// The size of a type in bytes.
///
/// More specifically, this is the offset in bytes between successive
/// items of the same type, including alignment padding.
pub fn size_of<T>() -> usize;
/// Moves a value to an uninitialized memory location.
///
/// Drop glue is not run on the destination.
pub fn move_val_init<T>(dst: *mut T, src: T);
pub fn min_align_of<T>() -> usize;
pub fn pref_align_of<T>() -> usize;
pub fn size_of_val<T: ?Sized>(_: &T) -> usize;
pub fn min_align_of_val<T: ?Sized>(_: &T) -> usize;
/// Gets a static string slice containing the name of a type.
pub fn type_name<T: ?Sized>() -> &'static str;
/// Gets an identifier which is globally unique to the specified type. This
/// function will return the same value for a type regardless of whichever
/// crate it is invoked in.
pub fn type_id<T: ?Sized + 'static>() -> u64;
/// Creates a value initialized to zero.
///
/// `init` is unsafe because it returns a zeroed-out datum,
/// which is unsafe unless T is `Copy`. Also, even if T is
/// `Copy`, an all-zero value may not correspond to any legitimate
/// state for the type in question.
pub fn init<T>() -> T;
/// Creates an uninitialized value.
///
/// `uninit` is unsafe because there is no guarantee of what its
/// contents are. In particular its drop-flag may be set to any
/// state, which means it may claim either dropped or
/// undropped. In the general case one must use `ptr::write` to
/// initialize memory previous set to the result of `uninit`.
pub fn uninit<T>() -> T;
/// Reinterprets the bits of a value of one type as another type.
///
/// Both types must have the same size. Neither the original, nor the result,
/// may be an [invalid value](../../nomicon/meet-safe-and-unsafe.html).
///
/// `transmute` is semantically equivalent to a bitwise move of one type
/// into another. It copies the bits from the source value into the
/// destination value, then forgets the original. It's equivalent to C's
/// `memcpy` under the hood, just like `transmute_copy`.
///
/// `transmute` is **incredibly** unsafe. There are a vast number of ways to
/// cause [undefined behavior][ub] with this function. `transmute` should be
/// the absolute last resort.
///
/// The [nomicon](../../nomicon/transmutes.html) has additional
/// documentation.
///
/// [ub]: ../../reference/behavior-considered-undefined.html
///
/// # Examples
///
/// There are a few things that `transmute` is really useful for.
///
/// Getting the bitpattern of a floating point type (or, more generally,
/// type punning, when `T` and `U` aren't pointers):
///
/// ```
/// let bitpattern = unsafe {
/// std::mem::transmute::<f32, u32>(1.0)
/// };
/// assert_eq!(bitpattern, 0x3F800000);
/// ```
///
/// Turning a pointer into a function pointer. This is *not* portable to
/// machines where function pointers and data pointers have different sizes.
///
/// ```
/// fn foo() -> i32 {
/// 0
/// }
/// let pointer = foo as *const ();
/// let function = unsafe {
/// std::mem::transmute::<*const (), fn() -> i32>(pointer)
/// };
/// assert_eq!(function(), 0);
/// ```
///
/// Extending a lifetime, or shortening an invariant lifetime. This is
/// advanced, very unsafe Rust!
///
/// ```
/// struct R<'a>(&'a i32);
/// unsafe fn extend_lifetime<'b>(r: R<'b>) -> R<'static> {
/// std::mem::transmute::<R<'b>, R<'static>>(r)
/// }
///
/// unsafe fn shorten_invariant_lifetime<'b, 'c>(r: &'b mut R<'static>)
/// -> &'b mut R<'c> {
/// std::mem::transmute::<&'b mut R<'static>, &'b mut R<'c>>(r)
/// }
/// ```
///
/// # Alternatives
///
/// Don't despair: many uses of `transmute` can be achieved through other means.
/// Below are common applications of `transmute` which can be replaced with safer
/// constructs.
///
/// Turning a pointer into a `usize`:
///
/// ```
/// let ptr = &0;
/// let ptr_num_transmute = unsafe {
/// std::mem::transmute::<&i32, usize>(ptr)
/// };
///
/// // Use an `as` cast instead
/// let ptr_num_cast = ptr as *const i32 as usize;
/// ```
///
/// Turning a `*mut T` into an `&mut T`:
///
/// ```
/// let ptr: *mut i32 = &mut 0;
/// let ref_transmuted = unsafe {
/// std::mem::transmute::<*mut i32, &mut i32>(ptr)
/// };
///
/// // Use a reborrow instead
/// let ref_casted = unsafe { &mut *ptr };
/// ```
///
/// Turning an `&mut T` into an `&mut U`:
///
/// ```
/// let ptr = &mut 0;
/// let val_transmuted = unsafe {
/// std::mem::transmute::<&mut i32, &mut u32>(ptr)
/// };
///
/// // Now, put together `as` and reborrowing - note the chaining of `as`
/// // `as` is not transitive
/// let val_casts = unsafe { &mut *(ptr as *mut i32 as *mut u32) };
/// ```
///
/// Turning an `&str` into an `&[u8]`:
///
/// ```
/// // this is not a good way to do this.
/// let slice = unsafe { std::mem::transmute::<&str, &[u8]>("Rust") };
/// assert_eq!(slice, &[82, 117, 115, 116]);
///
/// // You could use `str::as_bytes`
/// let slice = "Rust".as_bytes();
/// assert_eq!(slice, &[82, 117, 115, 116]);
///
/// // Or, just use a byte string, if you have control over the string
/// // literal
/// assert_eq!(b"Rust", &[82, 117, 115, 116]);
/// ```
///
/// Turning a `Vec<&T>` into a `Vec<Option<&T>>`:
///
/// ```
/// let store = [0, 1, 2, 3];
/// let mut v_orig = store.iter().collect::<Vec<&i32>>();
///
/// // Using transmute: this is Undefined Behavior, and a bad idea.
/// // However, it is no-copy.
/// let v_transmuted = unsafe {
/// std::mem::transmute::<Vec<&i32>, Vec<Option<&i32>>>(
/// v_orig.clone())
/// };
///
/// // This is the suggested, safe way.
/// // It does copy the entire vector, though, into a new array.
/// let v_collected = v_orig.clone()
/// .into_iter()
/// .map(|r| Some(r))
/// .collect::<Vec<Option<&i32>>>();
///
/// // The no-copy, unsafe way, still using transmute, but not UB.
/// // This is equivalent to the original, but safer, and reuses the
/// // same Vec internals. Therefore the new inner type must have the
/// // exact same size, and the same alignment, as the old type.
/// // The same caveats exist for this method as transmute, for
/// // the original inner type (`&i32`) to the converted inner type
/// // (`Option<&i32>`), so read the nomicon pages linked above.
/// let v_from_raw = unsafe {
/// Vec::from_raw_parts(v_orig.as_mut_ptr() as *mut Option<&i32>,
/// v_orig.len(),
/// v_orig.capacity())
/// };
/// std::mem::forget(v_orig);
/// ```
///
/// Implementing `split_at_mut`:
///
/// ```
/// use std::{slice, mem};
///
/// // There are multiple ways to do this; and there are multiple problems
/// // with the following, transmute, way.
/// fn split_at_mut_transmute<T>(slice: &mut [T], mid: usize)
/// -> (&mut [T], &mut [T]) {
/// let len = slice.len();
/// assert!(mid <= len);
/// unsafe {
/// let slice2 = mem::transmute::<&mut [T], &mut [T]>(slice);
/// // first: transmute is not typesafe; all it checks is that T and
/// // U are of the same size. Second, right here, you have two
/// // mutable references pointing to the same memory.
/// (&mut slice[0..mid], &mut slice2[mid..len])
/// }
/// }
///
/// // This gets rid of the typesafety problems; `&mut *` will *only* give
/// // you an `&mut T` from an `&mut T` or `*mut T`.
/// fn split_at_mut_casts<T>(slice: &mut [T], mid: usize)
/// -> (&mut [T], &mut [T]) {
/// let len = slice.len();
/// assert!(mid <= len);
/// unsafe {
/// let slice2 = &mut *(slice as *mut [T]);
/// // however, you still have two mutable references pointing to
/// // the same memory.
/// (&mut slice[0..mid], &mut slice2[mid..len])
/// }
/// }
///
/// // This is how the standard library does it. This is the best method, if
/// // you need to do something like this
/// fn split_at_stdlib<T>(slice: &mut [T], mid: usize)
/// -> (&mut [T], &mut [T]) {
/// let len = slice.len();
/// assert!(mid <= len);
/// unsafe {
/// let ptr = slice.as_mut_ptr();
/// // This now has three mutable references pointing at the same
/// // memory. `slice`, the rvalue ret.0, and the rvalue ret.1.
/// // `slice` is never used after `let ptr = ...`, and so one can
/// // treat it as "dead", and therefore, you only have two real
/// // mutable slices.
/// (slice::from_raw_parts_mut(ptr, mid),
/// slice::from_raw_parts_mut(ptr.offset(mid as isize), len - mid))
/// }
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn transmute<T, U>(e: T) -> U;
/// Returns `true` if the actual type given as `T` requires drop
/// glue; returns `false` if the actual type provided for `T`
/// implements `Copy`.
///
/// If the actual type neither requires drop glue nor implements
/// `Copy`, then may return `true` or `false`.
pub fn needs_drop<T>() -> bool;
/// Calculates the offset from a pointer.
///
/// This is implemented as an intrinsic to avoid converting to and from an
/// integer, since the conversion would throw away aliasing information.
///
/// # Safety
///
/// Both the starting and resulting pointer must be either in bounds or one
/// byte past the end of an allocated object. If either pointer is out of
/// bounds or arithmetic overflow occurs then any further use of the
/// returned value will result in undefined behavior.
pub fn offset<T>(dst: *const T, offset: isize) -> *const T;
/// Calculates the offset from a pointer, potentially wrapping.
///
/// This is implemented as an intrinsic to avoid converting to and from an
/// integer, since the conversion inhibits certain optimizations.
///
/// # Safety
///
/// Unlike the `offset` intrinsic, this intrinsic does not restrict the
/// resulting pointer to point into or one byte past the end of an allocated
/// object, and it wraps with two's complement arithmetic. The resulting
/// value is not necessarily valid to be used to actually access memory.
pub fn arith_offset<T>(dst: *const T, offset: isize) -> *const T;
/// Copies `count * size_of<T>` bytes from `src` to `dst`. The source
/// and destination may *not* overlap.
///
/// `copy_nonoverlapping` is semantically equivalent to C's `memcpy`.
///
/// # Safety
///
/// Beyond requiring that the program must be allowed to access both regions
/// of memory, it is Undefined Behavior for source and destination to
/// overlap. Care must also be taken with the ownership of `src` and
/// `dst`. This method semantically moves the values of `src` into `dst`.
/// However it does not drop the contents of `dst`, or prevent the contents
/// of `src` from being dropped or used.
///
/// # Examples
///
/// A safe swap function:
///
/// ```
/// use std::mem;
/// use std::ptr;
///
/// # #[allow(dead_code)]
/// fn swap<T>(x: &mut T, y: &mut T) {
/// unsafe {
/// // Give ourselves some scratch space to work with
/// let mut t: T = mem::uninitialized();
///
/// // Perform the swap, `&mut` pointers never alias
/// ptr::copy_nonoverlapping(x, &mut t, 1);
/// ptr::copy_nonoverlapping(y, x, 1);
/// ptr::copy_nonoverlapping(&t, y, 1);
///
/// // y and t now point to the same thing, but we need to completely forget `tmp`
/// // because it's no longer relevant.
/// mem::forget(t);
/// }
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize);
/// Copies `count * size_of<T>` bytes from `src` to `dst`. The source
/// and destination may overlap.
///
/// `copy` is semantically equivalent to C's `memmove`.
///
/// # Safety
///
/// Care must be taken with the ownership of `src` and `dst`.
/// This method semantically moves the values of `src` into `dst`.
/// However it does not drop the contents of `dst`, or prevent the contents of `src`
/// from being dropped or used.
///
/// # Examples
///
/// Efficiently create a Rust vector from an unsafe buffer:
///
/// ```
/// use std::ptr;
///
/// # #[allow(dead_code)]
/// unsafe fn from_buf_raw<T>(ptr: *const T, elts: usize) -> Vec<T> {
/// let mut dst = Vec::with_capacity(elts);
/// dst.set_len(elts);
/// ptr::copy(ptr, dst.as_mut_ptr(), elts);
/// dst
/// }
/// ```
///
#[stable(feature = "rust1", since = "1.0.0")]
pub fn copy<T>(src: *const T, dst: *mut T, count: usize);
/// Invokes memset on the specified pointer, setting `count * size_of::<T>()`
/// bytes of memory starting at `dst` to `val`.
///
/// # Examples
///
/// ```
/// use std::ptr;
///
/// let mut vec = vec![0; 4];
/// unsafe {
/// let vec_ptr = vec.as_mut_ptr();
/// ptr::write_bytes(vec_ptr, b'a', 2);
/// }
/// assert_eq!(vec, [b'a', b'a', 0, 0]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn write_bytes<T>(dst: *mut T, val: u8, count: usize);
/// Equivalent to the appropriate `llvm.memcpy.p0i8.0i8.*` intrinsic, with
/// a size of `count` * `size_of::<T>()` and an alignment of
/// `min_align_of::<T>()`
///
/// The volatile parameter is set to `true`, so it will not be optimized out
/// unless size is equal to zero.
pub fn volatile_copy_nonoverlapping_memory<T>(dst: *mut T, src: *const T,
count: usize);
/// Equivalent to the appropriate `llvm.memmove.p0i8.0i8.*` intrinsic, with
/// a size of `count` * `size_of::<T>()` and an alignment of
/// `min_align_of::<T>()`
///
/// The volatile parameter is set to `true`, so it will not be optimized out
/// unless size is equal to zero..
pub fn volatile_copy_memory<T>(dst: *mut T, src: *const T, count: usize);
/// Equivalent to the appropriate `llvm.memset.p0i8.*` intrinsic, with a
/// size of `count` * `size_of::<T>()` and an alignment of
/// `min_align_of::<T>()`.
///
/// The volatile parameter is set to `true`, so it will not be optimized out
/// unless size is equal to zero.
pub fn volatile_set_memory<T>(dst: *mut T, val: u8, count: usize);
/// Perform a volatile load from the `src` pointer.
/// The stabilized version of this intrinsic is
/// [`std::ptr::read_volatile`](../../std/ptr/fn.read_volatile.html).
pub fn volatile_load<T>(src: *const T) -> T;
/// Perform a volatile store to the `dst` pointer.
/// The stabilized version of this intrinsic is
/// [`std::ptr::write_volatile`](../../std/ptr/fn.write_volatile.html).
pub fn volatile_store<T>(dst: *mut T, val: T);
/// Returns the square root of an `f32`
pub fn sqrtf32(x: f32) -> f32;
/// Returns the square root of an `f64`
pub fn sqrtf64(x: f64) -> f64;
/// Raises an `f32` to an integer power.
pub fn powif32(a: f32, x: i32) -> f32;
/// Raises an `f64` to an integer power.
pub fn powif64(a: f64, x: i32) -> f64;
/// Returns the sine of an `f32`.
pub fn sinf32(x: f32) -> f32;
/// Returns the sine of an `f64`.
pub fn sinf64(x: f64) -> f64;
/// Returns the cosine of an `f32`.
pub fn cosf32(x: f32) -> f32;
/// Returns the cosine of an `f64`.
pub fn cosf64(x: f64) -> f64;
/// Raises an `f32` to an `f32` power.
pub fn powf32(a: f32, x: f32) -> f32;
/// Raises an `f64` to an `f64` power.
pub fn powf64(a: f64, x: f64) -> f64;
/// Returns the exponential of an `f32`.
pub fn expf32(x: f32) -> f32;
/// Returns the exponential of an `f64`.
pub fn expf64(x: f64) -> f64;
/// Returns 2 raised to the power of an `f32`.
pub fn exp2f32(x: f32) -> f32;
/// Returns 2 raised to the power of an `f64`.
pub fn exp2f64(x: f64) -> f64;
/// Returns the natural logarithm of an `f32`.
pub fn logf32(x: f32) -> f32;
/// Returns the natural logarithm of an `f64`.
pub fn logf64(x: f64) -> f64;
/// Returns the base 10 logarithm of an `f32`.
pub fn log10f32(x: f32) -> f32;
/// Returns the base 10 logarithm of an `f64`.
pub fn log10f64(x: f64) -> f64;
/// Returns the base 2 logarithm of an `f32`.
pub fn log2f32(x: f32) -> f32;
/// Returns the base 2 logarithm of an `f64`.
pub fn log2f64(x: f64) -> f64;
/// Returns `a * b + c` for `f32` values.
pub fn fmaf32(a: f32, b: f32, c: f32) -> f32;
/// Returns `a * b + c` for `f64` values.
pub fn fmaf64(a: f64, b: f64, c: f64) -> f64;
/// Returns the absolute value of an `f32`.
pub fn fabsf32(x: f32) -> f32;
/// Returns the absolute value of an `f64`.
pub fn fabsf64(x: f64) -> f64;
/// Copies the sign from `y` to `x` for `f32` values.
pub fn copysignf32(x: f32, y: f32) -> f32;
/// Copies the sign from `y` to `x` for `f64` values.
pub fn copysignf64(x: f64, y: f64) -> f64;
/// Returns the largest integer less than or equal to an `f32`.
pub fn floorf32(x: f32) -> f32;
/// Returns the largest integer less than or equal to an `f64`.
pub fn floorf64(x: f64) -> f64;
/// Returns the smallest integer greater than or equal to an `f32`.
pub fn ceilf32(x: f32) -> f32;
/// Returns the smallest integer greater than or equal to an `f64`.
pub fn ceilf64(x: f64) -> f64;
/// Returns the integer part of an `f32`.
pub fn truncf32(x: f32) -> f32;
/// Returns the integer part of an `f64`.
pub fn truncf64(x: f64) -> f64;
/// Returns the nearest integer to an `f32`. May raise an inexact floating-point exception
/// if the argument is not an integer.
pub fn rintf32(x: f32) -> f32;
/// Returns the nearest integer to an `f64`. May raise an inexact floating-point exception
/// if the argument is not an integer.
pub fn rintf64(x: f64) -> f64;
/// Returns the nearest integer to an `f32`.
pub fn nearbyintf32(x: f32) -> f32;
/// Returns the nearest integer to an `f64`.
pub fn nearbyintf64(x: f64) -> f64;
/// Returns the nearest integer to an `f32`. Rounds half-way cases away from zero.
pub fn roundf32(x: f32) -> f32;
/// Returns the nearest integer to an `f64`. Rounds half-way cases away from zero.
pub fn roundf64(x: f64) -> f64;
/// Float addition that allows optimizations based on algebraic rules.
/// May assume inputs are finite.
pub fn fadd_fast<T>(a: T, b: T) -> T;
/// Float subtraction that allows optimizations based on algebraic rules.
/// May assume inputs are finite.
pub fn fsub_fast<T>(a: T, b: T) -> T;
/// Float multiplication that allows optimizations based on algebraic rules.
/// May assume inputs are finite.
pub fn fmul_fast<T>(a: T, b: T) -> T;
/// Float division that allows optimizations based on algebraic rules.
/// May assume inputs are finite.
pub fn fdiv_fast<T>(a: T, b: T) -> T;
/// Float remainder that allows optimizations based on algebraic rules.
/// May assume inputs are finite.
pub fn frem_fast<T>(a: T, b: T) -> T;
/// Returns the number of bits set in an integer type `T`
pub fn ctpop<T>(x: T) -> T;
/// Returns the number of leading unset bits (zeroes) in an integer type `T`.
///
/// # Examples
///
/// ```
/// #![feature(core_intrinsics)]
///
/// use std::intrinsics::ctlz;
///
/// let x = 0b0001_1100_u8;
/// let num_leading = unsafe { ctlz(x) };
/// assert_eq!(num_leading, 3);
/// ```
///
/// An `x` with value `0` will return the bit width of `T`.
///
/// ```
/// #![feature(core_intrinsics)]
///
/// use std::intrinsics::ctlz;
///
/// let x = 0u16;
/// let num_leading = unsafe { ctlz(x) };
/// assert_eq!(num_leading, 16);
/// ```
pub fn ctlz<T>(x: T) -> T;
/// Like `ctlz`, but extra-unsafe as it returns `undef` when
/// given an `x` with value `0`.
///
/// # Examples
///
/// ```
/// #![feature(core_intrinsics)]
///
/// use std::intrinsics::ctlz_nonzero;
///
/// let x = 0b0001_1100_u8;
/// let num_leading = unsafe { ctlz_nonzero(x) };
/// assert_eq!(num_leading, 3);
/// ```
pub fn ctlz_nonzero<T>(x: T) -> T;
/// Returns the number of trailing unset bits (zeroes) in an integer type `T`.
///
/// # Examples
///
/// ```
/// #![feature(core_intrinsics)]
///
/// use std::intrinsics::cttz;
///
/// let x = 0b0011_1000_u8;
/// let num_trailing = unsafe { cttz(x) };
/// assert_eq!(num_trailing, 3);
/// ```
///
/// An `x` with value `0` will return the bit width of `T`:
///
/// ```
/// #![feature(core_intrinsics)]
///
/// use std::intrinsics::cttz;
///
/// let x = 0u16;
/// let num_trailing = unsafe { cttz(x) };
/// assert_eq!(num_trailing, 16);
/// ```
pub fn cttz<T>(x: T) -> T;
/// Like `cttz`, but extra-unsafe as it returns `undef` when
/// given an `x` with value `0`.
///
/// # Examples
///
/// ```
/// #![feature(core_intrinsics)]
///
/// use std::intrinsics::cttz_nonzero;
///
/// let x = 0b0011_1000_u8;
/// let num_trailing = unsafe { cttz_nonzero(x) };
/// assert_eq!(num_trailing, 3);
/// ```
pub fn cttz_nonzero<T>(x: T) -> T;
/// Reverses the bytes in an integer type `T`.
pub fn bswap<T>(x: T) -> T;
/// Performs checked integer addition.
/// The stabilized versions of this intrinsic are available on the integer
/// primitives via the `overflowing_add` method. For example,
/// [`std::u32::overflowing_add`](../../std/primitive.u32.html#method.overflowing_add)
pub fn add_with_overflow<T>(x: T, y: T) -> (T, bool);
/// Performs checked integer subtraction
/// The stabilized versions of this intrinsic are available on the integer
/// primitives via the `overflowing_sub` method. For example,
/// [`std::u32::overflowing_sub`](../../std/primitive.u32.html#method.overflowing_sub)
pub fn sub_with_overflow<T>(x: T, y: T) -> (T, bool);
/// Performs checked integer multiplication
/// The stabilized versions of this intrinsic are available on the integer
/// primitives via the `overflowing_mul` method. For example,
/// [`std::u32::overflowing_mul`](../../std/primitive.u32.html#method.overflowing_mul)
pub fn mul_with_overflow<T>(x: T, y: T) -> (T, bool);
/// Performs an unchecked division, resulting in undefined behavior
/// where y = 0 or x = `T::min_value()` and y = -1
pub fn unchecked_div<T>(x: T, y: T) -> T;
/// Returns the remainder of an unchecked division, resulting in
/// undefined behavior where y = 0 or x = `T::min_value()` and y = -1
pub fn unchecked_rem<T>(x: T, y: T) -> T;
/// Performs an unchecked left shift, resulting in undefined behavior when
/// y < 0 or y >= N, where N is the width of T in bits.
pub fn unchecked_shl<T>(x: T, y: T) -> T;
/// Performs an unchecked right shift, resulting in undefined behavior when
/// y < 0 or y >= N, where N is the width of T in bits.
pub fn unchecked_shr<T>(x: T, y: T) -> T;
/// Returns (a + b) mod 2<sup>N</sup>, where N is the width of T in bits.
/// The stabilized versions of this intrinsic are available on the integer
/// primitives via the `wrapping_add` method. For example,
/// [`std::u32::wrapping_add`](../../std/primitive.u32.html#method.wrapping_add)
pub fn overflowing_add<T>(a: T, b: T) -> T;
/// Returns (a - b) mod 2<sup>N</sup>, where N is the width of T in bits.
/// The stabilized versions of this intrinsic are available on the integer
/// primitives via the `wrapping_sub` method. For example,
/// [`std::u32::wrapping_sub`](../../std/primitive.u32.html#method.wrapping_sub)
pub fn overflowing_sub<T>(a: T, b: T) -> T;
/// Returns (a * b) mod 2<sup>N</sup>, where N is the width of T in bits.
/// The stabilized versions of this intrinsic are available on the integer
/// primitives via the `wrapping_mul` method. For example,
/// [`std::u32::wrapping_mul`](../../std/primitive.u32.html#method.wrapping_mul)
pub fn overflowing_mul<T>(a: T, b: T) -> T;
/// Returns the value of the discriminant for the variant in 'v',
/// cast to a `u64`; if `T` has no discriminant, returns 0.
pub fn discriminant_value<T>(v: &T) -> u64;
/// Rust's "try catch" construct which invokes the function pointer `f` with
/// the data pointer `data`.
///
/// The third pointer is a target-specific data pointer which is filled in
/// with the specifics of the exception that occurred. For examples on Unix
/// platforms this is a `*mut *mut T` which is filled in by the compiler and
/// on MSVC it's `*mut [usize; 2]`. For more information see the compiler's
/// source as well as std's catch implementation.
pub fn try(f: fn(*mut u8), data: *mut u8, local_ptr: *mut u8) -> i32;
/// Computes the byte offset that needs to be applied to `ptr` in order to
/// make it aligned to `align`.
/// If it is not possible to align `ptr`, the implementation returns
/// `usize::max_value()`.
///
/// There are no guarantees whatsover that offsetting the pointer will not
/// overflow or go beyond the allocation that `ptr` points into.
/// It is up to the caller to ensure that the returned offset is correct
/// in all terms other than alignment.
///
/// # Examples
///
/// Accessing adjacent `u8` as `u16`
///
/// ```
/// # #![feature(core_intrinsics)]
/// # fn foo(n: usize) {
/// # use std::intrinsics::align_offset;
/// # use std::mem::align_of;
/// # unsafe {
/// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
/// let ptr = &x[n] as *const u8;
/// let offset = align_offset(ptr as *const (), align_of::<u16>());
/// if offset < x.len() - n - 1 {
/// let u16_ptr = ptr.offset(offset as isize) as *const u16;
/// assert_ne!(*u16_ptr, 500);
/// } else {
/// // while the pointer can be aligned via `offset`, it would point
/// // outside the allocation
/// }
/// # } }
/// ```
#[cfg(not(stage0))]
pub fn align_offset(ptr: *const (), align: usize) -> usize;
}
#[cfg(stage0)]
/// Computes the byte offset that needs to be applied to `ptr` in order to
/// make it aligned to `align`.
/// If it is not possible to align `ptr`, the implementation returns
/// `usize::max_value()`.
///
/// There are no guarantees whatsover that offsetting the pointer will not
/// overflow or go beyond the allocation that `ptr` points into.
/// It is up to the caller to ensure that the returned offset is correct
/// in all terms other than alignment.
///
/// # Examples
///
/// Accessing adjacent `u8` as `u16`
///
/// ```
/// # #![feature(core_intrinsics)]
/// # fn foo(n: usize) {
/// # use std::intrinsics::align_offset;
/// # use std::mem::align_of;
/// # unsafe {
/// let x = [5u8, 6u8, 7u8, 8u8, 9u8];
/// let ptr = &x[n] as *const u8;
/// let offset = align_offset(ptr as *const (), align_of::<u16>());
/// if offset < x.len() - n - 1 {
/// let u16_ptr = ptr.offset(offset as isize) as *const u16;
/// assert_ne!(*u16_ptr, 500);
/// } else {
/// // while the pointer can be aligned via `offset`, it would point
/// // outside the allocation
/// }
/// # } }
/// ```
pub unsafe fn align_offset(ptr: *const (), align: usize) -> usize {
let offset = ptr as usize % align;
if offset == 0 {
0
} else {
align - offset
}
} | pub fn atomic_min_rel<T>(dst: *mut T, src: T) -> T;
pub fn atomic_min_acqrel<T>(dst: *mut T, src: T) -> T;
pub fn atomic_min_relaxed<T>(dst: *mut T, src: T) -> T; |
plan_parser.rs | // Copyright 2020-2021 The Datafuse Authors.
//
// SPDX-License-Identifier: Apache-2.0.
use std::collections::HashMap;
use std::sync::Arc;
use common_datablocks::DataBlock;
use common_datavalues::prelude::*;
use common_exception::ErrorCode;
use common_exception::Result;
use common_functions::aggregates::AggregateFunctionFactory;
use common_infallible::Mutex;
use common_planners::expand_aggregate_arg_exprs;
use common_planners::expand_wildcard;
use common_planners::expr_as_column_expr;
use common_planners::extract_aliases;
use common_planners::find_aggregate_exprs;
use common_planners::find_columns_not_satisfy_exprs;
use common_planners::rebase_expr;
use common_planners::rebase_expr_from_input;
use common_planners::resolve_aliases_to_exprs;
use common_planners::sort_to_inner_expr;
use common_planners::unwrap_alias_exprs;
use common_planners::CreateDatabasePlan;
use common_planners::CreateTablePlan;
use common_planners::DescribeTablePlan;
use common_planners::DropDatabasePlan;
use common_planners::DropTablePlan;
use common_planners::ExplainPlan;
use common_planners::Expression;
use common_planners::InsertIntoPlan;
use common_planners::PlanBuilder;
use common_planners::PlanNode;
use common_planners::SelectPlan;
use common_planners::SettingPlan;
use common_planners::ShowCreateTablePlan;
use common_planners::TableScanInfo;
use common_planners::TruncateTablePlan;
use common_planners::UseDatabasePlan;
use common_planners::VarValue;
use common_tracing::tracing;
use sqlparser::ast::Expr;
use sqlparser::ast::FunctionArg;
use sqlparser::ast::Ident;
use sqlparser::ast::ObjectName;
use sqlparser::ast::OrderByExpr;
use sqlparser::ast::Query;
use sqlparser::ast::Statement;
use sqlparser::ast::TableFactor;
use crate::catalogs::catalog::Catalog;
use crate::functions::ContextFunction;
use crate::sessions::FuseQueryContextRef;
use crate::sql::sql_statement::DfCreateTable;
use crate::sql::sql_statement::DfDropDatabase;
use crate::sql::sql_statement::DfUseDatabase;
use crate::sql::DfCreateDatabase;
use crate::sql::DfDescribeTable;
use crate::sql::DfDropTable;
use crate::sql::DfExplain;
use crate::sql::DfHint;
use crate::sql::DfParser;
use crate::sql::DfShowCreateTable;
use crate::sql::DfStatement;
use crate::sql::DfTruncateTable;
use crate::sql::SQLCommon;
pub struct PlanParser {
ctx: FuseQueryContextRef,
}
impl PlanParser {
pub fn create(ctx: FuseQueryContextRef) -> Self {
Self { ctx }
}
pub fn build_from_sql(&self, query: &str) -> Result<PlanNode> {
tracing::debug!(query);
DfParser::parse_sql(query).and_then(|(stmts, _)| {
stmts
.first()
.map(|statement| self.statement_to_plan(statement))
.unwrap_or_else(|| {
Result::Err(ErrorCode::SyntaxException("Only support single query"))
})
})
}
pub fn build_with_hint_from_sql(&self, query: &str) -> (Result<PlanNode>, Vec<DfHint>) {
tracing::debug!(query);
let stmt_hints = DfParser::parse_sql(query);
match stmt_hints {
Ok((stmts, hints)) => match stmts.first() {
Some(stmt) => (self.statement_to_plan(stmt), hints),
None => (
Result::Err(ErrorCode::SyntaxException("Only support single query")),
vec![],
),
},
Err(e) => (Err(e), vec![]),
}
}
pub fn statement_to_plan(&self, statement: &DfStatement) -> Result<PlanNode> {
match statement {
DfStatement::Statement(v) => self.sql_statement_to_plan(v),
DfStatement::Explain(v) => self.sql_explain_to_plan(v),
DfStatement::ShowDatabases(_) => {
self.build_from_sql("SELECT name FROM system.databases ORDER BY name")
}
DfStatement::CreateDatabase(v) => self.sql_create_database_to_plan(v),
DfStatement::DropDatabase(v) => self.sql_drop_database_to_plan(v),
DfStatement::CreateTable(v) => self.sql_create_table_to_plan(v),
DfStatement::DescribeTable(v) => self.sql_describe_table_to_plan(v),
DfStatement::DropTable(v) => self.sql_drop_table_to_plan(v),
DfStatement::TruncateTable(v) => self.sql_truncate_table_to_plan(v),
DfStatement::UseDatabase(v) => self.sql_use_database_to_plan(v),
DfStatement::ShowCreateTable(v) => self.sql_show_create_table_to_plan(v),
// TODO: support like and other filters in show queries
DfStatement::ShowTables(_) => self.build_from_sql(
format!(
"SELECT name FROM system.tables where database = '{}' ORDER BY database, name",
self.ctx.get_current_database()
)
.as_str(),
),
DfStatement::ShowSettings(_) => self.build_from_sql("SELECT name FROM system.settings"),
DfStatement::ShowProcessList(_) => {
self.build_from_sql("SELECT * FROM system.processes")
}
}
}
/// Builds plan from AST statement.
#[tracing::instrument(level = "info", skip(self, statement))]
pub fn sql_statement_to_plan(&self, statement: &sqlparser::ast::Statement) -> Result<PlanNode> {
match statement {
Statement::Query(query) => self.query_to_plan(query),
Statement::SetVariable {
variable, value, ..
} => self.set_variable_to_plan(variable, value),
Statement::Insert {
table_name,
columns,
source,
..
} => self.insert_to_plan(table_name, columns, source),
_ => Result::Err(ErrorCode::SyntaxException(format!(
"Unsupported statement {:?}",
statement
))),
}
}
/// Generate a logic plan from an EXPLAIN
#[tracing::instrument(level = "info", skip(self, explain))]
pub fn sql_explain_to_plan(&self, explain: &DfExplain) -> Result<PlanNode> {
let plan = self.sql_statement_to_plan(&explain.statement)?;
Ok(PlanNode::Explain(ExplainPlan {
typ: explain.typ,
input: Arc::new(plan),
}))
}
/// DfCreateDatabase to plan.
#[tracing::instrument(level = "info", skip(self, create), fields(ctx.id = self.ctx.get_id().as_str()))]
pub fn sql_create_database_to_plan(&self, create: &DfCreateDatabase) -> Result<PlanNode> {
if create.name.0.is_empty() {
return Result::Err(ErrorCode::SyntaxException("Create database name is empty"));
}
let name = create.name.0[0].value.clone();
let mut options = HashMap::new();
for p in create.options.iter() {
options.insert(p.name.value.to_lowercase(), p.value.to_string());
}
Ok(PlanNode::CreateDatabase(CreateDatabasePlan {
if_not_exists: create.if_not_exists,
db: name,
engine: create.engine,
options,
}))
}
/// DfDropDatabase to plan.
#[tracing::instrument(level = "info", skip(self, drop), fields(ctx.id = self.ctx.get_id().as_str()))]
pub fn sql_drop_database_to_plan(&self, drop: &DfDropDatabase) -> Result<PlanNode> {
if drop.name.0.is_empty() {
return Result::Err(ErrorCode::SyntaxException("Drop database name is empty"));
}
let name = drop.name.0[0].value.clone();
Ok(PlanNode::DropDatabase(DropDatabasePlan {
if_exists: drop.if_exists,
db: name,
}))
}
#[tracing::instrument(level = "info", skip(self, use_db), fields(ctx.id = self.ctx.get_id().as_str()))]
pub fn sql_use_database_to_plan(&self, use_db: &DfUseDatabase) -> Result<PlanNode> {
let db = use_db.name.0[0].value.clone();
Ok(PlanNode::UseDatabase(UseDatabasePlan { db }))
}
#[tracing::instrument(level = "info", skip(self, create), fields(ctx.id = self.ctx.get_id().as_str()))]
pub fn sql_create_table_to_plan(&self, create: &DfCreateTable) -> Result<PlanNode> {
let mut db = self.ctx.get_current_database();
if create.name.0.is_empty() {
return Result::Err(ErrorCode::SyntaxException("Create table name is empty"));
}
let mut table = create.name.0[0].value.clone();
if create.name.0.len() > 1 {
db = table;
table = create.name.0[1].value.clone();
}
let fields = create
.columns
.iter()
.map(|column| {
SQLCommon::make_data_type(&column.data_type)
.map(|data_type| DataField::new(&column.name.value, data_type, false))
})
.collect::<Result<Vec<DataField>>>()?;
let mut options = HashMap::new();
for p in create.options.iter() {
options.insert(
p.name.value.to_lowercase(),
p.value
.to_string()
.trim_matches(|s| s == '\'' || s == '"')
.to_string(),
);
}
let schema = DataSchemaRefExt::create(fields);
Ok(PlanNode::CreateTable(CreateTablePlan {
if_not_exists: create.if_not_exists,
db,
table,
schema,
engine: create.engine,
options,
}))
}
#[tracing::instrument(level = "info", skip(self, show_create), fields(ctx.id = self.ctx.get_id().as_str()))]
pub fn sql_show_create_table_to_plan(
&self,
show_create: &DfShowCreateTable,
) -> Result<PlanNode> {
let mut db = self.ctx.get_current_database();
if show_create.name.0.is_empty() {
return Result::Err(ErrorCode::SyntaxException(
"Show create table name is empty",
));
}
let mut table = show_create.name.0[0].value.clone();
if show_create.name.0.len() > 1 {
db = table;
table = show_create.name.0[1].value.clone();
}
let fields = vec![
DataField::new("Table", DataType::Utf8, false),
DataField::new("Create Table", DataType::Utf8, false),
];
let schema = DataSchemaRefExt::create(fields);
Ok(PlanNode::ShowCreateTable(ShowCreateTablePlan {
db,
table,
schema,
}))
}
/// DfDescribeTable to plan.
#[tracing::instrument(level = "info", skip(self, describe), fields(ctx.id = self.ctx.get_id().as_str()))]
pub fn sql_describe_table_to_plan(&self, describe: &DfDescribeTable) -> Result<PlanNode> {
let mut db = self.ctx.get_current_database();
if describe.name.0.is_empty() {
return Result::Err(ErrorCode::SyntaxException("Describe table name is empty"));
}
let mut table = describe.name.0[0].value.clone();
if describe.name.0.len() > 1 {
db = table;
table = describe.name.0[1].value.clone();
}
let schema = DataSchemaRefExt::create(vec![
DataField::new("Field", DataType::Utf8, false),
DataField::new("Type", DataType::Utf8, false),
DataField::new("Null", DataType::Utf8, false),
]);
Ok(PlanNode::DescribeTable(DescribeTablePlan {
db,
table,
schema,
}))
}
/// DfDropTable to plan.
#[tracing::instrument(level = "info", skip(self, drop), fields(ctx.id = self.ctx.get_id().as_str()))]
pub fn sql_drop_table_to_plan(&self, drop: &DfDropTable) -> Result<PlanNode> {
let mut db = self.ctx.get_current_database();
if drop.name.0.is_empty() {
return Result::Err(ErrorCode::SyntaxException("Drop table name is empty"));
}
let mut table = drop.name.0[0].value.clone();
if drop.name.0.len() > 1 {
db = table;
table = drop.name.0[1].value.clone();
}
Ok(PlanNode::DropTable(DropTablePlan {
if_exists: drop.if_exists,
db,
table,
}))
}
// DfTruncateTable to plan.
#[tracing::instrument(level = "info", skip(self, truncate), fields(ctx.id = self.ctx.get_id().as_str()))]
pub fn sql_truncate_table_to_plan(&self, truncate: &DfTruncateTable) -> Result<PlanNode> {
let mut db = self.ctx.get_current_database();
if truncate.name.0.is_empty() {
return Result::Err(ErrorCode::SyntaxException(
"TruncateTable table name is empty",
));
}
let mut table = truncate.name.0[0].value.clone();
if truncate.name.0.len() > 1 {
db = table;
table = truncate.name.0[1].value.clone();
}
Ok(PlanNode::TruncateTable(TruncateTablePlan { db, table }))
}
#[tracing::instrument(level = "info", skip(self, table_name, columns, source), fields(ctx.id = self.ctx.get_id().as_str()))]
fn insert_to_plan(
&self,
table_name: &ObjectName,
columns: &[Ident],
source: &Option<Box<Query>>,
) -> Result<PlanNode> {
let mut db_name = self.ctx.get_current_database();
let mut tbl_name = table_name.0[0].value.clone();
if table_name.0.len() > 1 {
db_name = tbl_name;
tbl_name = table_name.0[1].value.clone();
}
let table = self.ctx.get_datasource().get_table(&db_name, &tbl_name)?;
let mut schema = table.datasource().schema()?;
if !columns.is_empty() {
let fields = columns
.iter()
.map(|ident| schema.field_with_name(&ident.value).map(|v| v.clone()))
.collect::<Result<Vec<_>>>()?;
schema = DataSchemaRefExt::create(fields);
}
let mut input_stream = futures::stream::iter::<Vec<DataBlock>>(vec![]);
if let Some(source) = source {
if let sqlparser::ast::SetExpr::Values(vs) = &source.body {
let values = &vs.0;
if values.is_empty() {
return Err(ErrorCode::EmptyData(
"empty values for insertion is not allowed",
));
}
let all_value = values
.iter()
.all(|row| row.iter().all(|item| matches!(item, Expr::Value(_))));
if !all_value {
return Err(ErrorCode::UnImplement(
"not support value expressions other than literal value yet",
));
}
// Buffers some chunks if possible
let chunks = values.chunks(100);
let blocks: Vec<DataBlock> = chunks
.map(|chunk| {
let transposed: Vec<Vec<String>> = (0..chunk[0].len())
.map(|i| {
chunk
.iter()
.map(|inner| match &inner[i] {
Expr::Value(v) => v.to_string(),
_ => "N/A".to_string(),
})
.collect::<Vec<_>>()
})
.collect();
let cols = transposed
.iter()
.map(|col| {
Series::new(col.iter().map(|s| s as &str).collect::<Vec<&str>>())
})
.collect::<Vec<_>>();
DataBlock::create_by_array(schema.clone(), cols)
})
.collect();
input_stream = futures::stream::iter(blocks);
}
}
let plan_node = InsertIntoPlan {
db_name,
tbl_name,
schema,
// this is crazy, please do not keep it, I am just test driving apis
input_stream: Arc::new(Mutex::new(Some(Box::pin(input_stream)))),
};
Ok(PlanNode::InsertInto(plan_node))
}
/// Generate a logic plan from an SQL query
pub fn query_to_plan(&self, query: &sqlparser::ast::Query) -> Result<PlanNode> {
if query.with.is_some() {
return Result::Err(ErrorCode::UnImplement("CTE is not yet implement"));
}
match &query.body {
sqlparser::ast::SetExpr::Select(s) => {
self.select_to_plan(s.as_ref(), &query.limit, &query.offset, &query.order_by)
}
_ => Result::Err(ErrorCode::UnImplement(format!(
"Query {} is not yet implemented",
query.body
))),
}
}
/// Generate a logic plan from an SQL select
/// For example:
/// "select sum(number+1)+2, number%3 as id from numbers(10) where number>1 group by id having id>1 order by id desc limit 3"
#[tracing::instrument(level = "info", skip(self, select, limit, order_by))]
fn select_to_plan(
&self,
select: &sqlparser::ast::Select,
limit: &Option<sqlparser::ast::Expr>,
offset: &Option<sqlparser::ast::Offset>,
order_by: &[OrderByExpr],
) -> Result<PlanNode> {
// Filter expression
// In example: Filter=(number > 1)
let plan = self
.plan_tables_with_joins(&select.from)
.and_then(|input| self.filter(&input, &select.selection, Some(select)))?;
// Projection expression
// In example: Projection=[(sum((number + 1)) + 2), (number % 3) as id]
let projection_exprs = select
.projection
.iter()
.map(|e| self.sql_select_to_rex(e, &plan.schema(), Some(select)))
.collect::<Result<Vec<Expression>>>()?
.iter()
.flat_map(|expr| expand_wildcard(expr, &plan.schema()))
.collect::<Vec<Expression>>();
// Aliases replacement for group by, having, sorting
// In example: Aliases=[("id", (number % 3))]
let aliases = extract_aliases(&projection_exprs);
// Group By expression after against aliases
// In example: GroupBy=[(number % 3)]
let group_by_exprs = select
.group_by
.iter()
.map(|e| {
self.sql_to_rex(e, &plan.schema(), Some(select))
.and_then(|expr| resolve_aliases_to_exprs(&expr, &aliases))
})
.collect::<Result<Vec<_>>>()?;
// Having Expression after against aliases
// In example: Having=((number % 3) > 1)
let having_expr_opt = select
.having
.as_ref()
.map::<Result<Expression>, _>(|having_expr| {
let having_expr = self.sql_to_rex(having_expr, &plan.schema(), Some(select))?;
let having_expr = resolve_aliases_to_exprs(&having_expr, &aliases)?;
Ok(having_expr)
})
.transpose()?;
// OrderBy expression after against aliases
// In example: Sort=(number % 3)
let order_by_exprs = order_by
.iter()
.map(|e| -> Result<Expression> {
Ok(Expression::Sort {
expr: Box::new(
self.sql_to_rex(&e.expr, &plan.schema(), Some(select))
.and_then(|expr| resolve_aliases_to_exprs(&expr, &aliases))?,
),
asc: e.asc.unwrap_or(true),
nulls_first: e.nulls_first.unwrap_or(true),
})
})
.collect::<Result<Vec<Expression>>>()?;
// The outer expressions we will search through for
// aggregates. Aggregates may be sourced from the SELECT, order by, having ...
let mut expression_exprs = projection_exprs.clone();
// from order by
expression_exprs.extend_from_slice(&order_by_exprs);
let expression_with_sort = expression_exprs.clone();
// ... or from the HAVING.
if let Some(having_expr) = &having_expr_opt {
expression_exprs.push(having_expr.clone());
}
// All of the aggregate expressions (deduplicated).
// In example: aggr=[[sum((number + 1))]]
let aggr_exprs = find_aggregate_exprs(&expression_exprs);
let has_aggr = aggr_exprs.len() + group_by_exprs.len() > 0;
let (plan, having_expr_post_aggr_opt) = if has_aggr {
let aggr_projection_exprs = group_by_exprs
.iter()
.chain(aggr_exprs.iter())
.cloned()
.collect::<Vec<_>>();
let before_aggr_exprs = expand_aggregate_arg_exprs(&aggr_projection_exprs);
// Build aggregate inner expression plan and then aggregate&groupby plan.
// In example:
// inner expression=[(number + 1), (number % 3)]
let plan = self
.expression(&plan, &before_aggr_exprs, "Before GroupBy")
.and_then(|input| self.aggregate(&input, &aggr_exprs, &group_by_exprs))?;
// After aggregation, these are all of the columns that will be
// available to next phases of planning.
let column_exprs_post_aggr = aggr_projection_exprs
.iter()
.map(|expr| expr_as_column_expr(expr))
.collect::<Result<Vec<_>>>()?;
// Rewrite the SELECT expression to use the columns produced by the aggregation.
// In example:[col("number + 1"), col("number % 3")]
let select_exprs_post_aggr = expression_exprs
.iter()
.map(|expr| rebase_expr(expr, &aggr_projection_exprs))
.collect::<Result<Vec<_>>>()?;
if let Ok(Some(expr)) =
find_columns_not_satisfy_exprs(&column_exprs_post_aggr, &select_exprs_post_aggr)
{
return Err(ErrorCode::IllegalAggregateExp(format!(
"Column `{:?}` is not under aggregate function and not in GROUP BY: While processing {:?}",
expr, select_exprs_post_aggr
)));
}
// Rewrite the HAVING expression to use the columns produced by the
// aggregation.
let having_expr_post_aggr_opt = if let Some(having_expr) = &having_expr_opt {
let having_expr_post_aggr = rebase_expr(having_expr, &aggr_projection_exprs)?;
if let Ok(Some(expr)) = find_columns_not_satisfy_exprs(&column_exprs_post_aggr, &[
having_expr_post_aggr.clone(),
]) {
return Err(ErrorCode::IllegalAggregateExp(format!(
"Column `{:?}` is not under aggregate function and not in GROUP BY: While processing {:?}",
expr, having_expr_post_aggr
)));
}
Some(having_expr_post_aggr)
} else {
None
};
(plan, having_expr_post_aggr_opt)
} else {
(plan, having_expr_opt)
};
let stage_phase = if order_by_exprs.is_empty() {
"Before Projection"
} else {
"Before OrderBy"
};
let plan = self.expression(&plan, &expression_with_sort, stage_phase)?;
// Having.
let plan = self.having(&plan, having_expr_post_aggr_opt)?;
// Order by
let plan = self.sort(&plan, &order_by_exprs)?;
// Projection
let plan = self.project(&plan, &projection_exprs)?;
// Limit.
let plan = self.limit(&plan, limit, offset, Some(select))?;
Ok(PlanNode::Select(SelectPlan {
input: Arc::new(plan),
}))
}
/// Generate a relational expression from a select SQL expression
fn sql_select_to_rex(
&self,
sql: &sqlparser::ast::SelectItem,
schema: &DataSchema,
select: Option<&sqlparser::ast::Select>,
) -> Result<Expression> {
match sql {
sqlparser::ast::SelectItem::UnnamedExpr(expr) => self.sql_to_rex(expr, schema, select),
sqlparser::ast::SelectItem::ExprWithAlias { expr, alias } => Ok(Expression::Alias(
alias.value.clone(),
Box::new(self.sql_to_rex(expr, schema, select)?),
)),
sqlparser::ast::SelectItem::Wildcard => Ok(Expression::Wildcard),
_ => Result::Err(ErrorCode::UnImplement(format!(
"SelectItem: {:?} are not supported",
sql
))),
}
}
fn plan_tables_with_joins(&self, from: &[sqlparser::ast::TableWithJoins]) -> Result<PlanNode> {
match from.len() {
0 => self.plan_with_dummy_source(),
1 => self.plan_table_with_joins(&from[0]),
_ => Result::Err(ErrorCode::SyntaxException("Cannot support JOIN clause")),
}
}
fn plan_with_dummy_source(&self) -> Result<PlanNode> {
let db_name = "system";
let table_name = "one";
self.ctx
.get_table(db_name, table_name)
.and_then(|table_meta| {
let table = table_meta.datasource();
let table_id = table_meta.meta_id();
let table_version = table_meta.meta_ver();
table
.schema()
.and_then(|ref schema| {
let tbl_scan_info = TableScanInfo {
table_name,
table_id,
table_version,
table_schema: schema.as_ref(),
table_args: None,
};
PlanBuilder::scan(db_name, tbl_scan_info, None, None)
})
.and_then(|builder| builder.build())
.and_then(|dummy_scan_plan| match dummy_scan_plan {
PlanNode::Scan(ref dummy_scan_plan) => table
.read_plan(
self.ctx.clone(),
dummy_scan_plan,
self.ctx.get_settings().get_max_threads()? as usize,
)
.map(PlanNode::ReadSource),
_unreachable_plan => panic!("Logical error: cannot downcast to scan plan"),
})
})
}
fn plan_table_with_joins(&self, t: &sqlparser::ast::TableWithJoins) -> Result<PlanNode> {
self.create_relation(&t.relation)
}
fn create_relation(&self, relation: &sqlparser::ast::TableFactor) -> Result<PlanNode> {
match relation {
TableFactor::Table { name, args, .. } => {
let mut db_name = self.ctx.get_current_database();
let mut table_name = name.to_string();
if name.0.len() == 2 {
db_name = name.0[0].to_string();
table_name = name.0[1].to_string();
}
let mut table_args = None;
let meta_id;
let meta_version;
let table;
// only table functions has table args
if !args.is_empty() {
if name.0.len() >= 2 {
return Result::Err(ErrorCode::BadArguments(
"Currently table can't have arguments",
));
}
let empty_schema = Arc::new(DataSchema::empty());
match &args[0] {
FunctionArg::Named { arg, .. } => {
table_args = Some(self.sql_to_rex(arg, empty_schema.as_ref(), None)?);
}
FunctionArg::Unnamed(arg) => {
table_args = Some(self.sql_to_rex(arg, empty_schema.as_ref(), None)?);
}
}
let func_meta = self.ctx.get_table_function(&table_name)?;
meta_id = func_meta.meta_id();
meta_version = func_meta.meta_ver();
let table_function = func_meta.datasource().clone();
table_name = table_function.name().to_string();
table = table_function.as_table();
} else {
let table_meta = self.ctx.get_table(&db_name, &table_name)?;
meta_id = table_meta.meta_id();
meta_version = table_meta.meta_ver();
table = table_meta.datasource().clone();
}
let scan = {
table.schema().and_then(|schema| {
let tbl_scan_info = TableScanInfo {
table_name: &table_name,
table_id: meta_id,
table_version: meta_version,
table_schema: schema.as_ref(),
table_args,
};
PlanBuilder::scan(&db_name, tbl_scan_info, None, None)
.and_then(|builder| builder.build())
})
};
// TODO: Move ReadSourcePlan to SelectInterpreter
let partitions = self.ctx.get_settings().get_max_threads()? as usize;
scan.and_then(|scan| match scan {
PlanNode::Scan(ref scan) => table
.read_plan(self.ctx.clone(), scan, partitions)
.map(PlanNode::ReadSource),
_unreachable_plan => panic!("Logical error: Cannot downcast to scan plan"),
})
}
TableFactor::Derived { subquery, .. } => self.query_to_plan(subquery),
TableFactor::NestedJoin(table_with_joins) => {
self.plan_table_with_joins(table_with_joins)
}
TableFactor::TableFunction { .. } => {
Result::Err(ErrorCode::UnImplement("Unsupported table function"))
}
}
}
fn process_compound_ident(
&self,
ids: &[Ident],
select: Option<&sqlparser::ast::Select>,
) -> Result<Expression> {
let mut var_names = vec![];
for id in ids {
var_names.push(id.value.clone());
}
if &var_names[0][0..1] == "@" || var_names.len() != 2 || select == None {
return Err(ErrorCode::UnImplement(format!(
"Unsupported compound identifier '{:?}'",
var_names,
)));
}
let table_name = &var_names[0];
let from = &select.unwrap().from;
let obj_table_name = ObjectName(vec![Ident::new(table_name)]);
match from.len() {
0 => Err(ErrorCode::SyntaxException(
"Missing table in the select clause",
)),
1 => match &from[0].relation {
TableFactor::Table {
name,
alias,
args: _,
with_hints: _,
} => {
if *name == obj_table_name {
return Ok(Expression::Column(var_names.pop().unwrap()));
}
match alias {
Some(a) => {
if a.name == ids[0] {
Ok(Expression::Column(var_names.pop().unwrap()))
} else {
Err(ErrorCode::UnknownTable(format!(
"Unknown Table '{:?}'",
&table_name,
)))
}
}
None => Err(ErrorCode::UnknownTable(format!(
"Unknown Table '{:?}'",
&table_name,
))),
}
}
TableFactor::Derived {
lateral: _,
subquery: _,
alias,
} => match alias {
Some(a) => {
if a.name == ids[0] {
Ok(Expression::Column(var_names.pop().unwrap()))
} else {
Err(ErrorCode::UnknownTable(format!(
"Unknown Table '{:?}'",
&table_name,
)))
}
}
None => Err(ErrorCode::UnknownTable(format!(
"Unknown Table '{:?}'",
&table_name,
))),
},
_ => Err(ErrorCode::SyntaxException("Cannot support Nested Join now")),
},
_ => Err(ErrorCode::SyntaxException("Cannot support JOIN clause")),
}
}
/// Generate a relational expression from a SQL expression
pub fn sql_to_rex(
&self,
expr: &sqlparser::ast::Expr,
schema: &DataSchema,
select: Option<&sqlparser::ast::Select>,
) -> Result<Expression> {
fn value_to_rex(value: &sqlparser::ast::Value) -> Result<Expression> {
match value {
sqlparser::ast::Value::Number(ref n, _) => {
DataValue::try_from_literal(n).map(Expression::create_literal)
}
sqlparser::ast::Value::SingleQuotedString(ref value) => Ok(
Expression::create_literal(DataValue::Utf8(Some(value.clone()))),
),
sqlparser::ast::Value::Interval {
value,
leading_field,
leading_precision,
last_field,
fractional_seconds_precision,
} => SQLCommon::make_sql_interval_to_literal(
value,
leading_field,
leading_precision,
last_field,
fractional_seconds_precision,
),
sqlparser::ast::Value::Boolean(b) => {
Ok(Expression::create_literal(DataValue::Boolean(Some(*b))))
}
other => Result::Err(ErrorCode::SyntaxException(format!(
"Unsupported value expression: {}, type: {:?}",
value, other
))),
}
}
match expr {
sqlparser::ast::Expr::Value(value) => value_to_rex(value),
sqlparser::ast::Expr::Identifier(ref v) => Ok(Expression::Column(v.clone().value)),
sqlparser::ast::Expr::BinaryOp { left, op, right } => {
Ok(Expression::BinaryExpression {
op: format!("{}", op),
left: Box::new(self.sql_to_rex(left, schema, select)?),
right: Box::new(self.sql_to_rex(right, schema, select)?),
})
}
sqlparser::ast::Expr::UnaryOp { op, expr } => Ok(Expression::UnaryExpression {
op: format!("{}", op),
expr: Box::new(self.sql_to_rex(expr, schema, select)?),
}),
sqlparser::ast::Expr::Exists(q) => Ok(Expression::ScalarFunction {
op: "EXISTS".to_lowercase(),
args: vec![self.subquery_to_rex(q)?],
}),
sqlparser::ast::Expr::Subquery(q) => Ok(self.scalar_subquery_to_rex(q)?),
sqlparser::ast::Expr::Nested(e) => self.sql_to_rex(e, schema, select),
sqlparser::ast::Expr::CompoundIdentifier(ids) => {
self.process_compound_ident(ids.as_slice(), select)
}
sqlparser::ast::Expr::Function(e) => {
let mut args = Vec::with_capacity(e.args.len());
// 1. Get the args from context by function name. such as SELECT database()
// common::ScalarFunctions::udf::database arg is ctx.get_default()
let ctx_args = ContextFunction::build_args_from_ctx(
e.name.to_string().as_str(),
self.ctx.clone(),
)?;
if !ctx_args.is_empty() {
args.extend_from_slice(ctx_args.as_slice());
}
// 2. Get args from the ast::Expr:Function
for arg in &e.args {
match &arg {
FunctionArg::Named { arg, .. } => {
args.push(self.sql_to_rex(arg, schema, select)?);
}
FunctionArg::Unnamed(arg) => {
args.push(self.sql_to_rex(arg, schema, select)?);
}
}
}
let op = e.name.to_string();
if AggregateFunctionFactory::check(&op) {
let args = match op.to_lowercase().as_str() {
"count" => args
.iter()
.map(|c| match c {
Expression::Wildcard => common_planners::lit(0i64),
_ => c.clone(),
})
.collect(),
_ => args,
};
return Ok(Expression::AggregateFunction {
op,
distinct: e.distinct,
args,
});
}
Ok(Expression::ScalarFunction { op, args })
}
sqlparser::ast::Expr::Wildcard => Ok(Expression::Wildcard),
sqlparser::ast::Expr::TypedString { data_type, value } => {
SQLCommon::make_data_type(data_type).map(|data_type| Expression::Cast {
expr: Box::new(Expression::create_literal(DataValue::Utf8(Some(
value.clone(),
)))),
data_type,
})
}
sqlparser::ast::Expr::Cast { expr, data_type } => self
.sql_to_rex(expr, schema, select)
.map(Box::from)
.and_then(|expr| {
SQLCommon::make_data_type(data_type)
.map(|data_type| Expression::Cast { expr, data_type })
}),
sqlparser::ast::Expr::Substring {
expr,
substring_from,
substring_for,
} => {
let mut args = Vec::with_capacity(3);
args.push(self.sql_to_rex(expr, schema, select)?);
if let Some(from) = substring_from {
args.push(self.sql_to_rex(from, schema, select)?);
} else {
args.push(Expression::create_literal(DataValue::Int64(Some(1))));
}
if let Some(len) = substring_for {
args.push(self.sql_to_rex(len, schema, select)?);
}
Ok(Expression::ScalarFunction {
op: "substring".to_string(),
args,
})
}
sqlparser::ast::Expr::Between {
expr,
negated,
low,
high,
} => {
let expression = self.sql_to_rex(expr, schema, select)?;
let low_expression = self.sql_to_rex(low, schema, select)?;
let high_expression = self.sql_to_rex(high, schema, select)?;
match *negated {
false => Ok(expression
.gt_eq(low_expression)
.and(expression.lt_eq(high_expression))),
true => Ok(expression
.lt(low_expression)
.or(expression.gt(high_expression))),
}
}
other => Result::Err(ErrorCode::SyntaxException(format!(
"Unsupported expression: {}, type: {:?}",
expr, other
))),
}
}
pub fn subquery_to_rex(&self, subquery: &Query) -> Result<Expression> {
let subquery = self.query_to_plan(subquery)?;
let subquery_name = self.ctx.get_subquery_name(&subquery);
Ok(Expression::Subquery {
name: subquery_name,
query_plan: Arc::new(subquery),
})
}
pub fn scalar_subquery_to_rex(&self, subquery: &Query) -> Result<Expression> {
let subquery = self.query_to_plan(subquery)?;
let subquery_name = self.ctx.get_subquery_name(&subquery);
Ok(Expression::ScalarSubquery {
name: subquery_name,
query_plan: Arc::new(subquery),
})
}
pub fn set_variable_to_plan(
&self,
variable: &sqlparser::ast::Ident,
values: &[sqlparser::ast::SetVariableValue],
) -> Result<PlanNode> {
let mut vars = vec![];
for value in values {
let variable = variable.value.clone();
let value = match value {
sqlparser::ast::SetVariableValue::Ident(v) => v.value.clone(),
sqlparser::ast::SetVariableValue::Literal(v) => v.to_string(),
};
vars.push(VarValue { variable, value });
}
Ok(PlanNode::SetVariable(SettingPlan { vars }))
}
/// Apply a filter to the plan
fn filter(
&self,
plan: &PlanNode,
predicate: &Option<sqlparser::ast::Expr>,
select: Option<&sqlparser::ast::Select>,
) -> Result<PlanNode> {
match *predicate {
Some(ref predicate_expr) => self
.sql_to_rex(predicate_expr, &plan.schema(), select)
.and_then(|filter_expr| {
PlanBuilder::from(plan)
.filter(filter_expr)
.and_then(|builder| builder.build())
}),
_ => Ok(plan.clone()),
}
}
/// Apply a having to the plan
fn having(&self, plan: &PlanNode, expr: Option<Expression>) -> Result<PlanNode> {
if let Some(expr) = expr {
let expr = rebase_expr_from_input(&expr, &plan.schema())?;
return PlanBuilder::from(plan)
.having(expr)
.and_then(|builder| builder.build());
}
Ok(plan.clone())
}
/// Wrap a plan in a projection
fn project(&self, input: &PlanNode, exprs: &[Expression]) -> Result<PlanNode> {
let exprs = exprs
.iter()
.map(|expr| rebase_expr_from_input(expr, &input.schema()))
.collect::<Result<Vec<_>>>()?;
PlanBuilder::from(input)
.project(&exprs)
.and_then(|builder| builder.build())
}
/// Wrap a plan for an aggregate
fn aggregate(
&self,
input: &PlanNode,
aggr_exprs: &[Expression],
group_by_exprs: &[Expression],
) -> Result<PlanNode> {
let aggr_exprs = aggr_exprs
.iter()
.map(|expr| rebase_expr_from_input(expr, &input.schema()))
.collect::<Result<Vec<_>>>()?;
let group_by_exprs = group_by_exprs
.iter()
.map(|expr| rebase_expr_from_input(expr, &input.schema()))
.collect::<Result<Vec<_>>>()?;
// S0: Apply a partial aggregator plan.
// S1: Apply a fragment plan for distributed planners split.
// S2: Apply a final aggregator plan.
PlanBuilder::from(input)
.aggregate_partial(&aggr_exprs, &group_by_exprs)
.and_then(|builder| {
builder.aggregate_final(input.schema(), &aggr_exprs, &group_by_exprs)
})
.and_then(|builder| builder.build())
}
fn | (&self, input: &PlanNode, order_by_exprs: &[Expression]) -> Result<PlanNode> {
if order_by_exprs.is_empty() {
return Ok(input.clone());
}
let order_by_exprs = order_by_exprs
.iter()
.map(|expr| rebase_expr_from_input(expr, &input.schema()))
.collect::<Result<Vec<_>>>()?;
PlanBuilder::from(input)
.sort(&order_by_exprs)
.and_then(|builder| builder.build())
}
/// Wrap a plan in a limit
fn limit(
&self,
input: &PlanNode,
limit: &Option<sqlparser::ast::Expr>,
offset: &Option<sqlparser::ast::Offset>,
select: Option<&sqlparser::ast::Select>,
) -> Result<PlanNode> {
match (limit, offset) {
(None, None) => Ok(input.clone()),
(limit, offset) => {
let n = limit
.as_ref()
.map(|limit_expr| {
self.sql_to_rex(limit_expr, &input.schema(), select)
.and_then(|limit_expr| match limit_expr {
Expression::Literal { value, .. } => Ok(value.as_u64()? as usize),
_ => Err(ErrorCode::SyntaxException(format!(
"Unexpected expression for LIMIT clause: {:?}",
limit_expr
))),
})
})
.transpose()?;
let offset = offset
.as_ref()
.map(|offset| {
let offset_expr = &offset.value;
self.sql_to_rex(offset_expr, &input.schema(), select)
.and_then(|offset_expr| match offset_expr {
Expression::Literal { value, .. } => Ok(value.as_u64()? as usize),
_ => Err(ErrorCode::SyntaxException(format!(
"Unexpected expression for OFFSET clause: {:?}",
offset_expr,
))),
})
})
.transpose()?
.unwrap_or(0);
PlanBuilder::from(input)
.limit_offset(n, offset)
.and_then(|builder| builder.build())
}
}
}
/// Apply a expression against exprs.
fn expression(&self, input: &PlanNode, exprs: &[Expression], desc: &str) -> Result<PlanNode> {
let mut dedup_exprs = vec![];
for expr in exprs {
let rebased_expr = unwrap_alias_exprs(expr)
.and_then(|e| rebase_expr_from_input(&e, &input.schema()))?;
let rebased_expr = sort_to_inner_expr(&rebased_expr);
if !dedup_exprs.contains(&rebased_expr) {
dedup_exprs.push(rebased_expr);
}
}
// if all expression is column expression expression, we skip this expression
if dedup_exprs.iter().all(|expr| {
if let Expression::Column(_) = expr {
return true;
}
false
}) {
return Ok(input.clone());
}
if dedup_exprs.is_empty() {
return Ok(input.clone());
}
PlanBuilder::from(input)
.expression(&dedup_exprs, desc)
.and_then(|builder| builder.build())
}
}
| sort |
handler_proxy.go | /*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package apiserver
import (
"context"
"net/http"
"net/url"
"strings"
"sync/atomic"
"time"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/httpstream"
utilnet "k8s.io/apimachinery/pkg/util/net"
"k8s.io/apimachinery/pkg/util/proxy"
auditinternal "k8s.io/apiserver/pkg/apis/audit"
"k8s.io/apiserver/pkg/endpoints/handlers/responsewriters"
endpointmetrics "k8s.io/apiserver/pkg/endpoints/metrics"
genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
genericfeatures "k8s.io/apiserver/pkg/features"
"k8s.io/apiserver/pkg/server/egressselector"
utilfeature "k8s.io/apiserver/pkg/util/feature"
"k8s.io/apiserver/pkg/util/x509metrics"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/transport"
"k8s.io/klog/v2"
apiregistrationv1api "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1"
apiregistrationv1apihelper "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1/helper"
)
const (
aggregatorComponent string = "aggregator"
aggregatedDiscoveryTimeout = 5 * time.Second
)
type certKeyFunc func() ([]byte, []byte)
// proxyHandler provides a http.Handler which will proxy traffic to locations
// specified by items implementing Redirector.
type proxyHandler struct {
// localDelegate is used to satisfy local APIServices
localDelegate http.Handler
// proxyCurrentCertKeyContent holds the client cert used to identify this proxy. Backing APIServices use this to confirm the proxy's identity
proxyCurrentCertKeyContent certKeyFunc
proxyTransport *http.Transport
// Endpoints based routing to map from cluster IP to routable IP
serviceResolver ServiceResolver
handlingInfo atomic.Value
// egressSelector selects the proper egress dialer to communicate with the custom apiserver
// overwrites proxyTransport dialer if not nil
egressSelector *egressselector.EgressSelector
}
type proxyHandlingInfo struct {
// local indicates that this APIService is locally satisfied
local bool
// name is the name of the APIService
name string
// restConfig holds the information for building a roundtripper
restConfig *restclient.Config
// transportBuildingError is an error produced while building the transport. If this
// is non-nil, it will be reported to clients.
transportBuildingError error
// proxyRoundTripper is the re-useable portion of the transport. It does not vary with any request.
proxyRoundTripper http.RoundTripper
// serviceName is the name of the service this handler proxies to
serviceName string
// namespace is the namespace the service lives in
serviceNamespace string
// serviceAvailable indicates this APIService is available or not
serviceAvailable bool
// servicePort is the port of the service this handler proxies to
servicePort int32
}
func proxyError(w http.ResponseWriter, req *http.Request, error string, code int) {
http.Error(w, error, code)
ctx := req.Context()
info, ok := genericapirequest.RequestInfoFrom(ctx)
if !ok {
klog.Warning("no RequestInfo found in the context")
return
}
// TODO: record long-running request differently? The long-running check func does not necessarily match the one of the aggregated apiserver
endpointmetrics.RecordRequestTermination(req, info, aggregatorComponent, code)
}
func (r *proxyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
value := r.handlingInfo.Load()
if value == nil {
r.localDelegate.ServeHTTP(w, req)
return
}
handlingInfo := value.(proxyHandlingInfo)
if handlingInfo.local {
if r.localDelegate == nil {
http.Error(w, "", http.StatusNotFound)
return
}
r.localDelegate.ServeHTTP(w, req)
return
}
if !handlingInfo.serviceAvailable {
proxyError(w, req, "service unavailable", http.StatusServiceUnavailable)
return
}
if handlingInfo.transportBuildingError != nil {
proxyError(w, req, handlingInfo.transportBuildingError.Error(), http.StatusInternalServerError)
return
}
user, ok := genericapirequest.UserFrom(req.Context())
if !ok {
proxyError(w, req, "missing user", http.StatusInternalServerError)
return
}
// write a new location based on the existing request pointed at the target service
location := &url.URL{}
location.Scheme = "https"
rloc, err := r.serviceResolver.ResolveEndpoint(handlingInfo.serviceNamespace, handlingInfo.serviceName, handlingInfo.servicePort)
if err != nil {
klog.Errorf("error resolving %s/%s: %v", handlingInfo.serviceNamespace, handlingInfo.serviceName, err)
proxyError(w, req, "service unavailable", http.StatusServiceUnavailable)
return
}
location.Host = rloc.Host
location.Path = req.URL.Path
location.RawQuery = req.URL.Query().Encode()
newReq, cancelFn := newRequestForProxy(location, req)
defer cancelFn()
if handlingInfo.proxyRoundTripper == nil {
proxyError(w, req, "", http.StatusNotFound)
return
}
proxyRoundTripper := handlingInfo.proxyRoundTripper
upgrade := httpstream.IsUpgradeRequest(req)
proxyRoundTripper = transport.NewAuthProxyRoundTripper(user.GetName(), user.GetGroups(), user.GetExtra(), proxyRoundTripper)
// if we are upgrading, then the upgrade path tries to use this request with the TLS config we provide, but it does
// NOT use the roundtripper. Its a direct call that bypasses the round tripper. This means that we have to
// attach the "correct" user headers to the request ahead of time. After the initial upgrade, we'll be back
// at the roundtripper flow, so we only have to muck with this request, but we do have to do it.
if upgrade {
transport.SetAuthProxyHeaders(newReq, user.GetName(), user.GetGroups(), user.GetExtra())
}
handler := proxy.NewUpgradeAwareHandler(location, proxyRoundTripper, true, upgrade, &responder{w: w})
handler.InterceptRedirects = utilfeature.DefaultFeatureGate.Enabled(genericfeatures.StreamingProxyRedirects)
handler.RequireSameHostRedirects = utilfeature.DefaultFeatureGate.Enabled(genericfeatures.ValidateProxyRedirects)
handler.ServeHTTP(w, newReq)
}
// newRequestForProxy returns a shallow copy of the original request with a context that may include a timeout for discovery requests
func | (location *url.URL, req *http.Request) (*http.Request, context.CancelFunc) {
newCtx := req.Context()
cancelFn := func() {}
if requestInfo, ok := genericapirequest.RequestInfoFrom(req.Context()); ok {
// trim leading and trailing slashes. Then "/apis/group/version" requests are for discovery, so if we have exactly three
// segments that we are going to proxy, we have a discovery request.
if !requestInfo.IsResourceRequest && len(strings.Split(strings.Trim(requestInfo.Path, "/"), "/")) == 3 {
// discovery requests are used by kubectl and others to determine which resources a server has. This is a cheap call that
// should be fast for every aggregated apiserver. Latency for aggregation is expected to be low (as for all extensions)
// so forcing a short timeout here helps responsiveness of all clients.
newCtx, cancelFn = context.WithTimeout(newCtx, aggregatedDiscoveryTimeout)
}
}
// WithContext creates a shallow clone of the request with the same context.
newReq := req.WithContext(newCtx)
newReq.Header = utilnet.CloneHeader(req.Header)
newReq.URL = location
newReq.Host = location.Host
// If the original request has an audit ID, let's make sure we propagate this
// to the aggregated server.
if auditID, found := genericapirequest.AuditIDFrom(req.Context()); found {
newReq.Header.Set(auditinternal.HeaderAuditID, string(auditID))
}
return newReq, cancelFn
}
// responder implements rest.Responder for assisting a connector in writing objects or errors.
type responder struct {
w http.ResponseWriter
}
// TODO this should properly handle content type negotiation
// if the caller asked for protobuf and you write JSON bad things happen.
func (r *responder) Object(statusCode int, obj runtime.Object) {
responsewriters.WriteRawJSON(statusCode, obj, r.w)
}
func (r *responder) Error(_ http.ResponseWriter, _ *http.Request, err error) {
http.Error(r.w, err.Error(), http.StatusServiceUnavailable)
}
// these methods provide locked access to fields
func (r *proxyHandler) updateAPIService(apiService *apiregistrationv1api.APIService) {
if apiService.Spec.Service == nil {
r.handlingInfo.Store(proxyHandlingInfo{local: true})
return
}
proxyClientCert, proxyClientKey := r.proxyCurrentCertKeyContent()
clientConfig := &restclient.Config{
TLSClientConfig: restclient.TLSClientConfig{
Insecure: apiService.Spec.InsecureSkipTLSVerify,
ServerName: apiService.Spec.Service.Name + "." + apiService.Spec.Service.Namespace + ".svc",
CertData: proxyClientCert,
KeyData: proxyClientKey,
CAData: apiService.Spec.CABundle,
},
}
clientConfig.Wrap(x509metrics.NewMissingSANRoundTripperWrapperConstructor(x509MissingSANCounter))
newInfo := proxyHandlingInfo{
name: apiService.Name,
restConfig: clientConfig,
serviceName: apiService.Spec.Service.Name,
serviceNamespace: apiService.Spec.Service.Namespace,
servicePort: *apiService.Spec.Service.Port,
serviceAvailable: apiregistrationv1apihelper.IsAPIServiceConditionTrue(apiService, apiregistrationv1api.Available),
}
if r.egressSelector != nil {
networkContext := egressselector.Cluster.AsNetworkContext()
var egressDialer utilnet.DialFunc
egressDialer, err := r.egressSelector.Lookup(networkContext)
if err != nil {
klog.Warning(err.Error())
} else {
newInfo.restConfig.Dial = egressDialer
}
} else if r.proxyTransport != nil && r.proxyTransport.DialContext != nil {
newInfo.restConfig.Dial = r.proxyTransport.DialContext
}
newInfo.proxyRoundTripper, newInfo.transportBuildingError = restclient.TransportFor(newInfo.restConfig)
if newInfo.transportBuildingError != nil {
klog.Warning(newInfo.transportBuildingError.Error())
}
r.handlingInfo.Store(newInfo)
}
| newRequestForProxy |
archive.js | import React, { useRef, useEffect } from 'react';
import { graphql } from 'gatsby';
import PropTypes from 'prop-types';
import { Helmet } from 'react-helmet';
import styled from 'styled-components';
import { srConfig } from '@config';
import sr from '@utils/sr';
import { Layout } from '@components';
import { Icon } from '@components/icons';
const StyledTableContainer = styled.div`
margin: 100px -20px;
@media (max-width: 768px) {
margin: 50px -10px;
}
table {
width: 100%;
border-collapse: collapse;
.hide-on-mobile {
@media (max-width: 768px) {
display: none;
}
}
tbody tr {
&:hover,
&:focus {
background-color: var(--light-navy);
}
}
th,
td {
padding: 10px;
text-align: left;
&:first-child {
padding-left: 20px;
@media (max-width: 768px) {
padding-left: 10px;
}
}
&:last-child {
padding-right: 20px;
@media (max-width: 768px) {
padding-right: 10px;
}
}
svg {
width: 20px;
height: 20px;
}
}
tr {
cursor: default;
td:first-child {
border-top-left-radius: var(--border-radius);
border-bottom-left-radius: var(--border-radius);
}
td:last-child {
border-top-right-radius: var(--border-radius);
border-bottom-right-radius: var(--border-radius);
}
}
td {
&.year {
padding-right: 20px;
@media (max-width: 768px) {
padding-right: 10px;
font-size: var(--fz-sm);
}
}
&.title {
padding-top: 15px;
padding-right: 20px;
color: var(--lightest-slate);
font-size: var(--fz-xl);
font-weight: 600;
line-height: 1.25;
}
&.company {
font-size: var(--fz-lg);
white-space: nowrap;
}
&.tech {
font-size: var(--fz-xxs);
font-family: var(--font-mono);
line-height: 1.5;
.separator {
margin: 0 5px;
}
span {
display: inline-block; | min-width: 100px;
div {
display: flex;
align-items: center;
a {
${({ theme }) => theme.mixins.flexCenter};
flex-shrink: 0;
}
a + a {
margin-left: 10px;
}
}
}
}
}
`;
const ArchivePage = ({ location, data }) => {
const projects = data.allMarkdownRemark.edges;
const revealTitle = useRef(null);
const revealTable = useRef(null);
const revealProjects = useRef([]);
useEffect(() => {
sr.reveal(revealTitle.current, srConfig());
sr.reveal(revealTable.current, srConfig(200, 0));
revealProjects.current.forEach((ref, i) => sr.reveal(ref, srConfig(i * 10)));
}, []);
return (
<Layout location={location}>
<Helmet title="Archive" />
<main>
<header ref={revealTitle}>
<h1 className="big-heading">Archive</h1>
<p className="subtitle">A big list of things I’ve worked on</p>
</header>
<StyledTableContainer ref={revealTable}>
<table>
<thead>
<tr>
<th>Year</th>
<th>Title</th>
<th className="hide-on-mobile">Made at</th>
<th className="hide-on-mobile">Built with</th>
<th>Link</th>
</tr>
</thead>
<tbody>
{projects.length > 0 &&
projects.map(({ node }, i) => {
const { date, github, external, ios, android, title, tech, company } =
node.frontmatter;
return (
<tr key={i} ref={el => (revealProjects.current[i] = el)}>
<td className="overline year">{`${new Date(date).getFullYear()}`}</td>
<td className="title">{title}</td>
<td className="company hide-on-mobile">
{company ? <span>{company}</span> : <span>—</span>}
</td>
<td className="tech hide-on-mobile">
{tech.length > 0 &&
tech.map((item, i) => (
<span key={i}>
{item}
{''}
{i !== tech.length - 1 && <span className="separator">·</span>}
</span>
))}
</td>
<td className="links">
<div>
{external && (
<a href={external} aria-label="External Link">
<Icon name="External" />
</a>
)}
{github && (
<a href={github} aria-label="GitHub Link">
<Icon name="GitHub" />
</a>
)}
{ios && (
<a href={ios} aria-label="Apple App Store Link">
<Icon name="AppStore" />
</a>
)}
{android && (
<a href={android} aria-label="Google Play Store Link">
<Icon name="PlayStore" />
</a>
)}
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</StyledTableContainer>
</main>
</Layout>
);
};
ArchivePage.propTypes = {
location: PropTypes.object.isRequired,
data: PropTypes.object.isRequired,
};
export default ArchivePage;
export const pageQuery = graphql`
{
allMarkdownRemark(
filter: { fileAbsolutePath: { regex: "/projects/" } }
sort: { fields: [frontmatter___date], order: DESC }
) {
edges {
node {
frontmatter {
date
title
tech
github
external
ios
android
company
}
html
}
}
}
}
`; | }
}
&.links { |
role_binding_list.rs | // Generated from definition io.k8s.api.rbac.v1.RoleBindingList
/// RoleBindingList is a collection of RoleBindings
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RoleBindingList {
/// Items is a list of RoleBindings
pub items: Vec<crate::v1_16::api::rbac::v1::RoleBinding>,
/// Standard object's metadata.
pub metadata: Option<crate::v1_16::apimachinery::pkg::apis::meta::v1::ListMeta>,
}
impl crate::Resource for RoleBindingList {
fn api_version() -> &'static str {
"rbac.authorization.k8s.io/v1"
}
fn group() -> &'static str {
"rbac.authorization.k8s.io"
}
fn kind() -> &'static str {
"RoleBindingList"
}
fn | () -> &'static str {
"v1"
}
}
impl crate::Metadata for RoleBindingList {
type Ty = crate::v1_16::apimachinery::pkg::apis::meta::v1::ListMeta;
fn metadata(&self) -> Option<&<Self as crate::Metadata>::Ty> {
self.metadata.as_ref()
}
}
impl<'de> serde::Deserialize<'de> for RoleBindingList {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
#[allow(non_camel_case_types)]
enum Field {
Key_api_version,
Key_kind,
Key_items,
Key_metadata,
Other,
}
impl<'de> serde::Deserialize<'de> for Field {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de> {
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = Field;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "field identifier")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: serde::de::Error {
Ok(match v {
"apiVersion" => Field::Key_api_version,
"kind" => Field::Key_kind,
"items" => Field::Key_items,
"metadata" => Field::Key_metadata,
_ => Field::Other,
})
}
}
deserializer.deserialize_identifier(Visitor)
}
}
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = RoleBindingList;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "struct RoleBindingList")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: serde::de::MapAccess<'de> {
let mut value_items: Option<Vec<crate::v1_16::api::rbac::v1::RoleBinding>> = None;
let mut value_metadata: Option<crate::v1_16::apimachinery::pkg::apis::meta::v1::ListMeta> = None;
while let Some(key) = serde::de::MapAccess::next_key::<Field>(&mut map)? {
match key {
Field::Key_api_version => {
let value_api_version: String = serde::de::MapAccess::next_value(&mut map)?;
if value_api_version != <Self::Value as crate::Resource>::api_version() {
return Err(serde::de::Error::invalid_value(serde::de::Unexpected::Str(&value_api_version), &<Self::Value as crate::Resource>::api_version()));
}
},
Field::Key_kind => {
let value_kind: String = serde::de::MapAccess::next_value(&mut map)?;
if value_kind != <Self::Value as crate::Resource>::kind() {
return Err(serde::de::Error::invalid_value(serde::de::Unexpected::Str(&value_kind), &<Self::Value as crate::Resource>::kind()));
}
},
Field::Key_items => value_items = Some(serde::de::MapAccess::next_value(&mut map)?),
Field::Key_metadata => value_metadata = serde::de::MapAccess::next_value(&mut map)?,
Field::Other => { let _: serde::de::IgnoredAny = serde::de::MapAccess::next_value(&mut map)?; },
}
}
Ok(RoleBindingList {
items: value_items.ok_or_else(|| serde::de::Error::missing_field("items"))?,
metadata: value_metadata,
})
}
}
deserializer.deserialize_struct(
"RoleBindingList",
&[
"apiVersion",
"kind",
"items",
"metadata",
],
Visitor,
)
}
}
impl serde::Serialize for RoleBindingList {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer {
let mut state = serializer.serialize_struct(
"RoleBindingList",
3 +
self.metadata.as_ref().map_or(0, |_| 1),
)?;
serde::ser::SerializeStruct::serialize_field(&mut state, "apiVersion", <Self as crate::Resource>::api_version())?;
serde::ser::SerializeStruct::serialize_field(&mut state, "kind", <Self as crate::Resource>::kind())?;
serde::ser::SerializeStruct::serialize_field(&mut state, "items", &self.items)?;
if let Some(value) = &self.metadata {
serde::ser::SerializeStruct::serialize_field(&mut state, "metadata", value)?;
}
serde::ser::SerializeStruct::end(state)
}
}
| version |
buffered_x.rs | // Copyright (c) Aptos
// SPDX-License-Identifier: Apache-2.0
///! This is a copy of `futures::stream::buffered` from `futures 0.3.6`, except that it uses
///! `FuturesOrderedX` which provides concurrency control. So we can buffer more results without
///! too many futures driven at the same time.
use crate::utils::stream::futures_ordered_x::FuturesOrderedX;
use futures::{
ready,
stream::Fuse,
task::{Context, Poll},
Future, Stream, StreamExt,
};
use pin_project::pin_project;
use std::pin::Pin;
#[pin_project]
#[must_use = "streams do nothing unless polled"]
pub struct BufferedX<St>
where
St: Stream,
St::Item: Future,
{
#[pin]
stream: Fuse<St>,
in_progress_queue: FuturesOrderedX<St::Item>,
max: usize,
}
impl<St> std::fmt::Debug for BufferedX<St>
where
St: Stream + std::fmt::Debug,
St::Item: Future,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result |
}
impl<St> BufferedX<St>
where
St: Stream,
St::Item: Future,
{
pub(super) fn new(stream: St, n: usize, max_in_progress: usize) -> BufferedX<St> {
assert!(n > 0);
BufferedX {
stream: stream.fuse(),
in_progress_queue: FuturesOrderedX::new(max_in_progress),
max: n,
}
}
}
impl<St> Stream for BufferedX<St>
where
St: Stream,
St::Item: Future,
{
type Item = <St::Item as Future>::Output;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut this = self.project();
// First up, try to spawn off as many futures as possible by filling up
// our queue of futures.
while this.in_progress_queue.len() < *this.max {
match this.stream.as_mut().poll_next(cx) {
Poll::Ready(Some(fut)) => this.in_progress_queue.push(fut),
Poll::Ready(None) | Poll::Pending => break,
}
}
// Attempt to pull the next value from the in_progress_queue
let res = this.in_progress_queue.poll_next_unpin(cx);
if let Some(val) = ready!(res) {
return Poll::Ready(Some(val));
}
// If more values are still coming from the stream, we're not done yet
if this.stream.is_done() {
Poll::Ready(None)
} else {
Poll::Pending
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let queue_len = self.in_progress_queue.len();
let (lower, upper) = self.stream.size_hint();
let lower = lower.saturating_add(queue_len);
let upper = match upper {
Some(x) => x.checked_add(queue_len),
None => None,
};
(lower, upper)
}
}
#[cfg(test)]
mod tests {
use super::super::StreamX;
use futures::StreamExt;
use proptest::{collection::vec, prelude::*};
use tokio::{runtime::Runtime, time::Duration};
proptest! {
#[test]
fn test_run(
sleeps_ms in vec(0u64..10, 0..100),
buffer_size in 1usize..100,
max_in_progress in 1usize..100,
) {
let rt = Runtime::new().unwrap();
rt.block_on(async {
let num_sleeps = sleeps_ms.len();
let outputs = futures::stream::iter(
sleeps_ms.into_iter().enumerate().map(|(n, sleep_ms)| async move {
tokio::time::sleep(Duration::from_millis(sleep_ms)).await;
n
})
).buffered_x(buffer_size, max_in_progress)
.collect::<Vec<_>>().await;
assert_eq!(
outputs,
(0..num_sleeps).collect::<Vec<_>>()
);
});
}
}
}
| {
f.debug_struct("BufferedX")
.field("stream", &self.stream)
.field("in_progress_queue", &self.in_progress_queue)
.field("max", &self.max)
.finish()
} |
jumbotron.ts | import {ArchitectElement} from '../architect-element';
import {hasClass} from '../../utils/has-class';
const template = `<div class="jumbotron">
<h1 class="display-4">Hello, world!</h1>
<p class="lead">This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p>
<hr class="my-4">
<p>It uses utility classes for typography and spacing to space content out within the larger container.</p>
<a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a>
</div>`;
const style = `
.jumbotron {
text-align: center;
}
.jumbotron p {
margin: 20px 0 30px;
}
`;
export class | extends ArchitectElement {
name = 'jumbotron';
contentCategories = ['flow'];
html = template;
css = style;
allowedContent = ['flow'];
category = 'components';
icon = 'call-to-action';
specificity = 3;
hiddenClasses = ['jumbotron'];
matcher(node: HTMLElement) {
return hasClass(node, 'jumbotron');
}
}
| JumbotronEl |
verifier.go | package auth
import (
"context"
"github.com/venturemark/apicommon/pkg/metadata"
"github.com/venturemark/apigengo/pkg/pbf/invite"
"github.com/venturemark/permission"
"github.com/venturemark/permission/pkg/label"
"github.com/venturemark/permission/pkg/label/action"
"github.com/venturemark/permission/pkg/label/resource"
"github.com/venturemark/permission/pkg/label/role"
"github.com/venturemark/permission/pkg/label/visibility"
"github.com/xh3b4sd/redigo"
"github.com/xh3b4sd/tracer"
"github.com/venturemark/apiserver/pkg/context/claimid"
)
type VerifierConfig struct {
Permission permission.Gateway
Redigo redigo.Interface
}
type Verifier struct { | }
func NewVerifier(config VerifierConfig) (*Verifier, error) {
if config.Permission == nil {
return nil, tracer.Maskf(invalidConfigError, "%T.Permission must not be empty", config)
}
if config.Redigo == nil {
return nil, tracer.Maskf(invalidConfigError, "%T.Redigo must not be empty", config)
}
v := &Verifier{
permission: config.Permission,
redigo: config.Redigo,
}
return v, nil
}
func (v *Verifier) Verify(ctx context.Context, req *invite.SearchI) (bool, error) {
var err error
var act label.Label
var res label.Label
var rol label.Label
var vis label.Label
{
act, err = v.act(req.Obj[0].Metadata)
if err != nil {
return false, tracer.Mask(err)
}
res, err = v.res(req.Obj[0].Metadata)
if err != nil {
return false, tracer.Mask(err)
}
rol, err = v.rol(req.Obj[0].Metadata)
if err != nil {
return false, tracer.Mask(err)
}
vis, err = v.vis(ctx, req.Obj[0].Metadata)
if err != nil {
return false, tracer.Mask(err)
}
}
{
ok := v.permission.Ingress().Match(act, res, rol, vis)
if !ok {
return false, nil
}
}
return true, nil
}
func (v *Verifier) act(met map[string]string) (label.Label, error) {
{
ini := met[metadata.InviteID]
if ini == "" {
return action.Filter, nil
}
}
return action.Search, nil
}
func (v *Verifier) res(met map[string]string) (label.Label, error) {
return resource.Invite, nil
}
func (v *Verifier) rol(met map[string]string) (label.Label, error) {
var err error
{
ini := met[metadata.InviteID]
if ini == "" {
return role.Subject, nil
}
}
var inv string
{
inv, err = v.permission.Resolver().Invite().Role(met)
if err != nil {
return "", tracer.Mask(err)
}
}
var ven string
{
ven, err = v.permission.Resolver().Venture().Role(met)
if err != nil {
return "", tracer.Mask(err)
}
}
var rol label.Label
{
if inv == role.Member.Label() {
rol = role.Member
}
if inv == role.Owner.Label() {
rol = role.Owner
}
if inv == role.Reader.Label() {
rol = role.Reader
}
if ven == role.Member.Label() {
rol = role.Member
}
if ven == role.Owner.Label() {
rol = role.Owner
}
if ven == role.Reader.Label() {
rol = role.Reader
}
}
return rol, nil
}
func (v *Verifier) vis(ctx context.Context, met map[string]string) (label.Label, error) {
var err error
var isp bool
{
cli, _ := claimid.FromContext(ctx)
if cli == "webclient" {
isp = true
}
}
var ven string
{
ven, err = v.permission.Resolver().Venture().Visibility(met)
if err != nil {
return "", tracer.Mask(err)
}
}
var vis label.Label
{
if ven == "" {
vis = visibility.Private
}
if ven == visibility.Private.Label() {
vis = visibility.Private
}
if ven == visibility.Public.Label() && isp {
vis = visibility.Public
}
}
return vis, nil
} | permission permission.Gateway
redigo redigo.Interface |
exp_wnd_closer.rs | use crate::bot::protocol::{Event, Message, Update};
use crate::bot::scene::Scene;
use crate::bot::tasks::task::Task;
use crate::bot::world::PlayerWorld;
pub struct ExpWndCloser {
closed: Vec<i32>,
exp_wnd_ids: Vec<i32>,
}
impl ExpWndCloser {
pub fn new() -> Self {
Self {
closed: Vec::new(),
exp_wnd_ids: Vec::new(),
}
}
}
impl Task for ExpWndCloser {
fn name(&self) -> &'static str {
"ExpWndCloser"
}
fn get_next_message(&mut self, _: &PlayerWorld, _: &Scene) -> Option<Message> {
if let Some(id) = self.exp_wnd_ids.iter().find(|v| self.closed.iter().find(|w| w == v).is_none()) {
debug!("ExpWndCloser: close {}", id);
self.closed.push(*id);
return Some(Message::WidgetMessage {
sender: *id,
kind: String::from("close"),
arguments: Vec::new(),
});
}
None
}
fn update(&mut self, _: &PlayerWorld, update: &Update) |
fn restore(&mut self, world: &PlayerWorld) {
for widget in world.widgets().values() {
if widget.kind.as_str().starts_with("ui/expwnd:") {
debug!("ExpWndCloser: restored window {}", widget.id);
self.exp_wnd_ids.push(widget.id);
}
}
}
}
| {
match &update.event {
Event::NewWidget { id, kind, parent: _, pargs: _, cargs: _ } => {
if kind.as_str().starts_with("ui/expwnd:") {
debug!("ExpWndCloser: got a new window {}", id);
self.exp_wnd_ids.push(*id);
}
}
Event::WidgetMessage { id, msg, args: _ } => {
if msg.as_str() == "close" {
debug!("ExpWndCloser: window {} is closed", id);
self.exp_wnd_ids.retain(|v| v != id);
self.closed.retain(|v| v != id);
}
}
Event::Destroy { id } => {
debug!("ExpWndCloser: window {} is destroyed", id);
self.exp_wnd_ids.retain(|v| v != id);
self.closed.retain(|v| v != id);
}
_ => (),
}
} |
sessions.go | // Copyright 2012 The Gorilla Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sessions
import (
"encoding/gob"
"fmt"
"time"
"github.com/valyala/fasthttp"
)
// Default flashes key.
const flashesKey = "_flash"
// Options --------------------------------------------------------------------
// Options stores configuration for a session or session store.
//
// Fields are a subset of http.Cookie fields.
type Options struct {
Path string
Domain string
// MaxAge=0 means no 'Max-Age' attribute specified.
// MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'.
// MaxAge>0 means Max-Age attribute present and given in seconds.
MaxAge int
Secure bool
HttpOnly bool
}
// Session --------------------------------------------------------------------
// NewSession is called by session stores to create a new session instance.
func NewSession(store Store, name string) *Session {
return &Session{
Values: make(map[interface{}]interface{}),
store: store,
name: name,
}
}
// Session stores the values and optional configuration for a session.
type Session struct {
// The ID of the session, generated by stores. It should not be used for
// user data.
ID string
// Values contains the user-data for the session.
Values map[interface{}]interface{}
Options *Options
IsNew bool
store Store
name string
}
// Flashes returns a slice of flash messages from the session.
//
// A single variadic argument is accepted, and it is optional: it defines
// the flash key. If not defined "_flash" is used by default.
func (s *Session) Flashes(vars ...string) []interface{} {
var flashes []interface{}
key := flashesKey
if len(vars) > 0 {
key = vars[0]
}
if v, ok := s.Values[key]; ok {
// Drop the flashes and return it.
delete(s.Values, key)
flashes = v.([]interface{})
}
return flashes
}
// AddFlash adds a flash message to the session.
//
// A single variadic argument is accepted, and it is optional: it defines
// the flash key. If not defined "_flash" is used by default.
func (s *Session) AddFlash(value interface{}, vars ...string) {
key := flashesKey
if len(vars) > 0 {
key = vars[0]
}
var flashes []interface{}
if v, ok := s.Values[key]; ok {
flashes = v.([]interface{})
}
s.Values[key] = append(flashes, value)
}
// Save is a convenience method to save this session. It is the same as calling
// store.Save(request, response, session). You should call Save before writing to
// the response or returning from the handler.
func (s *Session) Save(ctx *fasthttp.RequestCtx) error {
return s.store.Save(ctx, s)
}
// Name returns the name used to register the session.
func (s *Session) Name() string {
return s.name
}
// Store returns the session store used to register the session.
func (s *Session) Store() Store {
return s.store
}
// Helpers --------------------------------------------------------------------
func init() {
gob.Register([]interface{}{})
}
// NewCookie returns an http.Cookie with the options set. It also sets
// the Expires field calculated based on the MaxAge value, for Internet
// Explorer compatibility.
func NewCookie(name, value string, options *Options) *fasthttp.Cookie |
// Error ----------------------------------------------------------------------
// MultiError stores multiple errors.
//
// Borrowed from the App Engine SDK.
type MultiError []error
func (m MultiError) Error() string {
s, n := "", 0
for _, e := range m {
if e != nil {
if n == 0 {
s = e.Error()
}
n++
}
}
switch n {
case 0:
return "(0 errors)"
case 1:
return s
case 2:
return s + " (and 1 other error)"
}
return fmt.Sprintf("%s (and %d other errors)", s, n-1)
}
| {
cookie := &fasthttp.Cookie{}
cookie.SetKey(name)
cookie.SetValue(value)
cookie.SetDomain(options.Domain)
cookie.SetPath(options.Path)
cookie.SetHTTPOnly(options.HttpOnly)
cookie.SetSecure(options.Secure)
if options.MaxAge > 0 {
d := time.Duration(options.MaxAge) * time.Second
cookie.SetExpire(time.Now().Add(d))
} else if options.MaxAge < 0 {
// Set it to the past to expire now.
cookie.SetExpire(time.Unix(1, 0))
}
return cookie
} |
mod.rs | pub mod loading; | pub mod simulation; |
|
ccm.rs | //! Clock Configuration Module (CCM)
mod arm_clock;
use arm_clock::set_arm_clock;
use core::time::Duration;
use imxrt_ral as ral;
use ral::modify_reg;
pub struct Handle {
pub(crate) base: ral::ccm::Instance,
pub(crate) analog: ral::ccm_analog::Instance,
}
impl Handle {
pub fn raw(&mut self) -> (&ral::ccm::Instance, &ral::ccm_analog::Instance) {
(&self.base, &self.analog)
}
}
pub struct CCM {
pub handle: Handle,
pub perclk: perclk::Multiplexer,
/// ARM PLL, providing typical functioning frequency
pub pll1: PLL1,
/// The 480 MHz PFD
pub pll2: pll2::PFD,
/// The 528 MHz PFD
pub pll3: pll3::PFD,
}
/// Sets the low power clock mode
///
/// This is typically entered with the wfi() or wfe() instruction.
///
/// Notably SysTick *does not* wake up the chip from sleep, so
/// if SysTick is desired to be waited on using wfi() or such
/// then the ClockMode should be set to Run
///
/// Clock modes enum matches the mcuxpresso sdk's clock_mode_t
#[repr(u32)]
pub enum ClockMode {
Run = 0,
Wait = 1,
Stop = 2,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ArmFrequency(Frequency);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IPGFrequency(pub(crate) Frequency);
pub struct PLL1(());
impl PLL1 {
fn new() -> Self {
PLL1(())
}
#[cfg(any(feature = "imxrt1011", feature = "imxrt1015"))]
pub const ARM_HZ: u32 = 500_000_000;
#[cfg(any(feature = "imxrt1064", feature = "imxrt1062", feature = "imxrt1061"))]
pub const ARM_HZ: u32 = 600_000_000;
/// Set the clock speed for the ARM core. This represents the base processor frequency.
/// Consider using the 600MHz recommended frequency `PLL1::ARM_HZ`.
pub fn set_arm_clock(
&mut self,
hz: u32,
handle: &mut Handle,
dcdc: &mut crate::dcdc::DCDC,
) -> (ArmFrequency, IPGFrequency) {
let (ccm, ccm_analog) = handle.raw();
let dcdc = dcdc.raw();
let (arm_freq, ipg_freq) = set_arm_clock(hz, ccm, ccm_analog, dcdc);
(
ArmFrequency(Frequency(arm_freq)),
IPGFrequency(Frequency(ipg_freq)),
)
}
}
impl CCM {
pub(crate) fn new(base: ral::ccm::Instance, analog: ral::ccm_analog::Instance) -> Self {
CCM {
handle: Handle { base, analog },
perclk: perclk::Multiplexer::new(),
pll1: PLL1::new(),
pll2: pll2::PFD::new(),
pll3: pll3::PFD::new(),
}
}
// Set the system clock mode, by default we set this to Run
// which prevents the chip from going to to sleep on wfi()
// This is because by default wfi() puts the chip to sleep
// and systick interrupts *do not* wake up the chip.
// See https://github.com/zephyrproject-rtos/zephyr/pull/8535
pub fn set_mode(&mut self, mode: ClockMode) {
modify_reg!(ral::ccm, self.handle.base, CLPCR, LPM: (mode as u32));
}
}
pub mod perclk {
use super::{ral, Divider, Frequency, Handle, OSCILLATOR_FREQUENCY};
use ral::{ccm::CSCMR1::PERCLK_CLK_SEL, modify_reg};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u32)]
#[allow(non_camel_case_types)] // Easier mapping if the names are consistent
pub enum PODF {
/// 0b000000: Divide by 1
DIVIDE_1 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_1,
/// 0b000001: Divide by 2
DIVIDE_2 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_2,
/// 0b000010: Divide by 3
DIVIDE_3 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_3,
/// 0b000011: Divide by 4
DIVIDE_4 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_4,
/// 0b000100: Divide by 5
DIVIDE_5 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_5,
/// 0b000101: Divide by 6
DIVIDE_6 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_6,
/// 0b000110: Divide by 7
DIVIDE_7 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_7,
/// 0b000111: Divide by 8
DIVIDE_8 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_8,
/// 0b001000: Divide by 9
DIVIDE_9 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_9,
/// 0b001001: Divide by 10
DIVIDE_10 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_10,
/// 0b001010: Divide by 11
DIVIDE_11 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_11,
/// 0b001011: Divide by 12
DIVIDE_12 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_12,
/// 0b001100: Divide by 13
DIVIDE_13 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_13,
/// 0b001101: Divide by 14
DIVIDE_14 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_14,
/// 0b001110: Divide by 15
DIVIDE_15 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_15,
/// 0b001111: Divide by 16
DIVIDE_16 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_16,
/// 0b010000: Divide by 17
DIVIDE_17 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_17,
/// 0b010001: Divide by 18
DIVIDE_18 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_18,
/// 0b010010: Divide by 19
DIVIDE_19 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_19,
/// 0b010011: Divide by 20
DIVIDE_20 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_20,
/// 0b010100: Divide by 21
DIVIDE_21 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_21,
/// 0b010101: Divide by 22
DIVIDE_22 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_22,
/// 0b010110: Divide by 23
DIVIDE_23 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_23,
/// 0b010111: Divide by 24
DIVIDE_24 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_24,
/// 0b011000: Divide by 25
DIVIDE_25 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_25,
/// 0b011001: Divide by 26
DIVIDE_26 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_26,
/// 0b011010: Divide by 27
DIVIDE_27 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_27,
/// 0b011011: Divide by 28
DIVIDE_28 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_28,
/// 0b011100: Divide by 29
DIVIDE_29 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_29,
/// 0b011101: Divide by 30
DIVIDE_30 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_30,
/// 0b011110: Divide by 31
DIVIDE_31 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_31,
/// 0b011111: Divide by 32
DIVIDE_32 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_32,
/// 0b100000: Divide by 33
DIVIDE_33 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_33,
/// 0b100001: Divide by 34
DIVIDE_34 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_34,
/// 0b100010: Divide by 35
DIVIDE_35 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_35,
/// 0b100011: Divide by 36
DIVIDE_36 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_36,
/// 0b100100: Divide by 37
DIVIDE_37 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_37,
/// 0b100101: Divide by 38
DIVIDE_38 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_38,
/// 0b100110: Divide by 39
DIVIDE_39 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_39,
/// 0b100111: Divide by 40
DIVIDE_40 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_40,
/// 0b101000: Divide by 41
DIVIDE_41 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_41,
/// 0b101001: Divide by 42
DIVIDE_42 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_42,
/// 0b101010: Divide by 43
DIVIDE_43 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_43,
/// 0b101011: Divide by 44
DIVIDE_44 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_44,
/// 0b101100: Divide by 45
DIVIDE_45 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_45,
/// 0b101101: Divide by 46
DIVIDE_46 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_46,
/// 0b101110: Divide by 47
DIVIDE_47 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_47,
/// 0b101111: Divide by 48
DIVIDE_48 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_48,
/// 0b110000: Divide by 49
DIVIDE_49 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_49,
/// 0b110001: Divide by 50
DIVIDE_50 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_50,
/// 0b110010: Divide by 51
DIVIDE_51 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_51,
/// 0b110011: Divide by 52
DIVIDE_52 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_52,
/// 0b110100: Divide by 53
DIVIDE_53 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_53,
/// 0b110101: Divide by 54
DIVIDE_54 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_54,
/// 0b110110: Divide by 55
DIVIDE_55 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_55,
/// 0b110111: Divide by 56
DIVIDE_56 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_56,
/// 0b111000: Divide by 57
DIVIDE_57 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_57,
/// 0b111001: Divide by 58
DIVIDE_58 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_58,
/// 0b111010: Divide by 59
DIVIDE_59 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_59,
/// 0b111011: Divide by 60
DIVIDE_60 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_60,
/// 0b111100: Divide by 61
DIVIDE_61 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_61,
/// 0b111101: Divide by 62
DIVIDE_62 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_62,
/// 0b111110: Divide by 63
DIVIDE_63 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_63,
/// 0b111111: Divide by 64
DIVIDE_64 = ral::ccm::CSCMR1::PERCLK_PODF::RW::DIVIDE_64,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum CLKSEL {
/// 24MHz oscillator
OSC,
/// IPG
IPG(super::IPGFrequency),
}
impl CLKSEL {
fn to_perclk_clk_sel(self) -> u32 {
match self {
CLKSEL::OSC => PERCLK_CLK_SEL::RW::PERCLK_CLK_SEL_1,
CLKSEL::IPG(_) => PERCLK_CLK_SEL::RW::PERCLK_CLK_SEL_0,
}
}
}
pub struct Multiplexer;
pub struct Configured<'a> {
handle: &'a mut Handle,
podf: PODF,
clksel: CLKSEL,
}
impl From<PODF> for Divider {
fn from(podf: PODF) -> Self {
Divider((podf as u32) + 1)
}
}
impl Multiplexer {
pub(super) fn new() -> Self {
Multiplexer
}
pub fn configure(self, handle: &mut Handle, podf: PODF, clksel: CLKSEL) -> Configured {
modify_reg!(
ral::ccm,
handle.base,
CSCMR1,
PERCLK_CLK_SEL: clksel.to_perclk_clk_sel(),
PERCLK_PODF: (podf as u32)
);
Configured {
handle,
podf,
clksel,
}
}
}
impl<'a> Configured<'a> {
pub(crate) fn enable_pit_clock_gates(&mut self) -> (Frequency, Divider) {
modify_reg!(ral::ccm, self.handle.base, CCGR1, CG6: 0x3);
(self.clksel.into(), self.podf.into())
}
pub(crate) fn enable_gpt1_clock_gates(&mut self) -> (Frequency, Divider) {
modify_reg!(ral::ccm, self.handle.base, CCGR1, CG10: 0x3, CG11: 0x3);
(self.clksel.into(), self.podf.into())
}
pub(crate) fn enable_gpt2_clock_gates(&mut self) -> (Frequency, Divider) {
modify_reg!(ral::ccm, self.handle.base, CCGR0, CG12: 0x3, CG13: 0x3);
(self.clksel.into(), self.podf.into())
}
pub(crate) fn clock_selection(&self) -> CLKSEL {
self.clksel
}
}
impl From<CLKSEL> for Frequency {
fn from(clksel: CLKSEL) -> Frequency {
match clksel {
// 24MHz oscillator
CLKSEL::OSC => OSCILLATOR_FREQUENCY,
CLKSEL::IPG(ipg_freq) => ipg_freq.0,
}
}
}
}
macro_rules! pfd {
($setter:ident, $value:ident) => {
use super::Handle;
use imxrt_ral::{self as ral, write_reg};
fn pfd_gate_frac(pfd: &Option<Frequency>) -> (u32, u32) {
match pfd {
Some(Frequency(freq)) => (1, (*freq).into()),
None => (0, 0),
}
}
pub struct PFD;
impl PFD {
pub(super) fn new() -> Self {
PFD
}
pub fn set(&mut self, handle: &mut Handle, pfds: [Option<Frequency>; 4]) {
let (pfd0_clkgate, pfd0_frac) = pfd_gate_frac(&pfds[0]);
let (pfd1_clkgate, pfd1_frac) = pfd_gate_frac(&pfds[1]);
let (pfd2_clkgate, pfd2_frac) = pfd_gate_frac(&pfds[2]);
let (pfd3_clkgate, pfd3_frac) = pfd_gate_frac(&pfds[3]);
write_reg!(
ral::ccm_analog,
handle.analog,
$setter,
PFD0_CLKGATE: pfd0_clkgate,
PFD1_CLKGATE: pfd1_clkgate,
PFD2_CLKGATE: pfd2_clkgate,
PFD3_CLKGATE: pfd3_clkgate
);
// Safety: PDFx_FRAC is 6 bits wide. By the implementations
// of the `Frequency(..)` newtypes, the wrapped values will
// never exceed a 6 bit value.
write_reg!(
ral::ccm_analog,
handle.analog,
$value,
PFD0_FRAC: pfd0_frac,
PFD1_FRAC: pfd1_frac,
PFD2_FRAC: pfd2_frac,
PFD3_FRAC: pfd3_frac
);
}
}
};
}
/// 480 MHz phase fractional divider
pub mod pll3 {
pfd!(PFD_480_SET, PFD_480);
pub struct Frequency(u8);
pub const MHZ_720: Frequency = Frequency(12);
pub const MHZ_664: Frequency = Frequency(13);
pub const MHZ_617: Frequency = Frequency(14);
pub const MHZ_576: Frequency = Frequency(15);
pub const MHZ_540: Frequency = Frequency(16);
pub const MHZ_508: Frequency = Frequency(17);
pub const MHZ_480: Frequency = Frequency(18);
pub const MHZ_454: Frequency = Frequency(19);
pub const MHZ_432: Frequency = Frequency(20);
pub const MHZ_411: Frequency = Frequency(21);
pub const MHZ_392: Frequency = Frequency(22);
pub const MHZ_375: Frequency = Frequency(23);
pub const MHZ_360: Frequency = Frequency(24);
pub const MHZ_345: Frequency = Frequency(25);
pub const MHZ_332: Frequency = Frequency(26);
pub const MHZ_320: Frequency = Frequency(27);
pub const MHZ_308: Frequency = Frequency(28);
pub const MHZ_297: Frequency = Frequency(29);
pub const MHZ_288: Frequency = Frequency(30);
pub const MHZ_278: Frequency = Frequency(31);
pub const MHZ_270: Frequency = Frequency(32);
pub const MHZ_261: Frequency = Frequency(33);
pub const MHZ_254: Frequency = Frequency(34);
pub const MHZ_246: Frequency = Frequency(35);
}
/// 528 MHz phase fractional divider
pub mod pll2 {
pfd!(PFD_528_SET, PFD_528);
pub struct Frequency(u8);
pub const MHZ_792: Frequency = Frequency(12);
pub const MHZ_731: Frequency = Frequency(13);
pub const MHZ_678: Frequency = Frequency(14);
pub const MHZ_633: Frequency = Frequency(15);
pub const MHZ_594: Frequency = Frequency(16);
pub const MHZ_559: Frequency = Frequency(17);
pub const MHZ_528: Frequency = Frequency(18);
pub const MHZ_500: Frequency = Frequency(19);
pub const MHZ_475: Frequency = Frequency(20);
pub const MHZ_452: Frequency = Frequency(21);
pub const MHZ_432: Frequency = Frequency(22);
pub const MHZ_413: Frequency = Frequency(23);
pub const MHZ_396: Frequency = Frequency(24);
pub const MHZ_380: Frequency = Frequency(25);
pub const MHZ_365: Frequency = Frequency(26);
pub const MHZ_352: Frequency = Frequency(27);
pub const MHZ_339: Frequency = Frequency(28);
pub const MHZ_327: Frequency = Frequency(29);
pub const MHZ_316: Frequency = Frequency(30);
pub const MHZ_306: Frequency = Frequency(31);
pub const MHZ_297: Frequency = Frequency(32);
pub const MHZ_288: Frequency = Frequency(33);
pub const MHZ_279: Frequency = Frequency(34);
pub const MHZ_271: Frequency = Frequency(35);
}
use core::convert::TryFrom;
pub trait TicksRepr: TryFrom<u64> {}
impl TicksRepr for u8 {}
impl TicksRepr for u16 {}
impl TicksRepr for u32 {}
impl TicksRepr for u64 {}
/// Possible errors that could result during a computation of `ticks`
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum TicksError {
/// The duration cannot be expressed in a `u64`.
DurationOverflow,
/// The number of ticks cannot be expressed in a `u32`
TicksOverflow,
/// Computation would divide by zero
DivideByZero,
}
/// Computes the number of clock ticks that span the provide duration, given
/// the clock frequency and clock divider. If there is no divider, use `Divider::default()`
/// to specify an unused divider. Returns `Ok(ticks)` when the computation of
/// clock ticks succeeds, or an error.
pub fn ticks<R: TicksRepr>(dur: Duration, freq: u32, div: u32) -> Result<R, TicksError> {
// Ticks computed as
//
// ticks = (duration / clock_period) - 1
//
// where `clock_period` is the effective clock period: `freq / div`
let delay_ns = u64::try_from(dur.as_nanos()).map_err(|_| TicksError::DurationOverflow)?;
let effective_freq = freq.checked_div(div).ok_or(TicksError::DurationOverflow)?;
let clock_period_ns = 1_000_000_000u32
.checked_div(effective_freq)
.map(u64::from)
.ok_or(TicksError::DivideByZero)?;
delay_ns
.checked_div(clock_period_ns)
.and_then(|ticks| ticks.checked_sub(1))
.and_then(|ticks| R::try_from(ticks).ok())
.ok_or(TicksError::TicksOverflow)
}
/// An opaque value representing a clock frequency
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Frequency(pub(crate) u32);
impl From<Frequency> for core::time::Duration {
fn from(hz: Frequency) -> core::time::Duration {
core::time::Duration::from_nanos((1_000_000_000u32 / hz.0).into())
}
}
/// An opaque value representing a clock phase divider
#[derive(Debug, Clone, Copy)]
pub struct Divider(pub(crate) u32);
impl Default for Divider {
fn default() -> Divider {
Divider(1)
}
}
/// High speed oscillator frequency
const OSCILLATOR_FREQUENCY: Frequency = Frequency(24_000_000 /* 24MHz */);
impl core::ops::Div<Divider> for Frequency {
type Output = Frequency;
fn div(self, rhs: Divider) -> Frequency {
Frequency(self.0 / rhs.0)
}
}
impl core::ops::DivAssign<Divider> for Frequency {
fn div_assign(&mut self, rhs: Divider) {
self.0 /= rhs.0;
}
}
/// Timing configurations for PWM
pub mod pwm {
use super::{ral::pwm, Divider, Frequency, IPGFrequency};
/// PWM submodule clock selection
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive] // not all variants are added
pub enum ClockSelect {
/// IPG clock frequency, available via `set_arm_clock`
IPG(IPGFrequency),
}
/// PWM prescalar
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u16)]
#[allow(non_camel_case_types)] // Easier mapping if the names are consistent
pub enum Prescalar {
/// 0b000: PWM clock frequency = fclk
PRSC_0 = pwm::SMCTRL0::PRSC::RW::PRSC_0,
/// 0b001: PWM clock frequency = fclk/2
PRSC_1 = pwm::SMCTRL0::PRSC::RW::PRSC_1,
/// 0b010: PWM clock frequency = fclk/4
PRSC_2 = pwm::SMCTRL0::PRSC::RW::PRSC_2,
/// 0b011: PWM clock frequency = fclk/8
PRSC_3 = pwm::SMCTRL0::PRSC::RW::PRSC_3,
/// 0b100: PWM clock frequency = fclk/16
PRSC_4 = pwm::SMCTRL0::PRSC::RW::PRSC_4,
/// 0b101: PWM clock frequency = fclk/32
PRSC_5 = pwm::SMCTRL0::PRSC::RW::PRSC_5,
/// 0b110: PWM clock frequency = fclk/64
PRSC_6 = pwm::SMCTRL0::PRSC::RW::PRSC_6,
/// 0b111: PWM clock frequency = fclk/128
PRSC_7 = pwm::SMCTRL0::PRSC::RW::PRSC_7,
}
impl From<Prescalar> for Divider {
fn from(pre: Prescalar) -> Divider {
Divider(1u32 << (pre as u16))
}
}
impl From<ClockSelect> for Frequency {
fn from(clksel: ClockSelect) -> Frequency {
match clksel {
ClockSelect::IPG(IPGFrequency(hz)) => hz,
}
}
}
}
/// Timing configurations for I2C peripherals
pub mod i2c {
use super::{Divider, Frequency, OSCILLATOR_FREQUENCY};
use crate::ral;
/// Clock selection for all I2C peripherals
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u32)]
#[non_exhaustive] // Not all variants added
pub enum ClockSelect {
/// Derive clock from oscillator
OSC = ral::ccm::CSCDR2::LPI2C_CLK_SEL::RW::LPI2C_CLK_SEL_1,
}
/// Prescalar selection for all I2C input clocks
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u32)]
#[allow(non_camel_case_types)] // Easier mapping if the names are consistent
pub enum PrescalarSelect {
DIVIDE_1 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_1,
DIVIDE_2 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_2,
DIVIDE_3 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_3,
DIVIDE_4 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_4,
DIVIDE_5 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_5,
DIVIDE_6 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_6,
DIVIDE_7 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_7,
DIVIDE_8 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_8,
DIVIDE_9 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_9,
DIVIDE_10 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_10,
DIVIDE_11 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_11,
DIVIDE_12 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_12,
DIVIDE_13 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_13,
DIVIDE_14 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_14,
DIVIDE_15 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_15,
DIVIDE_16 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_16,
DIVIDE_17 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_17,
DIVIDE_18 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_18,
DIVIDE_19 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_19,
DIVIDE_20 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_20,
DIVIDE_21 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_21,
DIVIDE_22 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_22,
DIVIDE_23 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_23,
DIVIDE_24 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_24,
DIVIDE_25 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_25,
DIVIDE_26 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_26,
DIVIDE_27 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_27,
DIVIDE_28 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_28,
DIVIDE_29 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_29,
DIVIDE_30 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_30,
DIVIDE_31 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_31,
DIVIDE_32 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_32,
DIVIDE_33 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_33,
DIVIDE_34 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_34,
DIVIDE_35 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_35,
DIVIDE_36 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_36,
DIVIDE_37 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_37,
DIVIDE_38 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_38,
DIVIDE_39 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_39,
DIVIDE_40 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_40,
DIVIDE_41 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_41,
DIVIDE_42 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_42,
DIVIDE_43 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_43,
DIVIDE_44 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_44,
DIVIDE_45 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_45,
DIVIDE_46 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_46,
DIVIDE_47 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_47,
DIVIDE_48 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_48,
DIVIDE_49 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_49,
DIVIDE_50 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_50,
DIVIDE_51 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_51,
DIVIDE_52 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_52,
DIVIDE_53 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_53,
DIVIDE_54 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_54,
DIVIDE_55 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_55,
DIVIDE_56 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_56,
DIVIDE_57 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_57,
DIVIDE_58 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_58,
DIVIDE_59 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_59,
DIVIDE_60 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_60,
DIVIDE_61 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_61,
DIVIDE_62 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_62,
DIVIDE_63 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_63,
DIVIDE_64 = ral::ccm::CSCDR2::LPI2C_CLK_PODF::RW::DIVIDE_64,
}
impl From<ClockSelect> for Frequency {
fn from(clock_select: ClockSelect) -> Self {
match clock_select {
ClockSelect::OSC => OSCILLATOR_FREQUENCY,
}
}
}
impl From<PrescalarSelect> for Divider {
fn from(prescalar_select: PrescalarSelect) -> Self {
Divider((prescalar_select as u32) + 1)
}
}
}
pub mod uart {
use super::{Divider, Frequency, OSCILLATOR_FREQUENCY};
use crate::ral;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u32)]
#[non_exhaustive] // Not all variants added
pub enum ClockSelect {
/// Oscillator clock
OSC = ral::ccm::CSCDR1::UART_CLK_SEL::RW::UART_CLK_SEL_1,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[allow(non_camel_case_types)] // Easier mapping if the names are consistent
#[repr(u32)]
pub enum PrescalarSelect {
/// 0b000000: Divide by 1
DIVIDE_1 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_1,
/// 0b000001: Divide by 2
DIVIDE_2 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_2,
/// 0b000010: Divide by 3
DIVIDE_3 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_3,
/// 0b000011: Divide by 4
DIVIDE_4 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_4,
/// 0b000100: Divide by 5
DIVIDE_5 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_5,
/// 0b000101: Divide by 6
DIVIDE_6 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_6,
/// 0b000110: Divide by 7
DIVIDE_7 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_7,
/// 0b000111: Divide by 8
DIVIDE_8 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_8,
/// 0b001000: Divide by 9
DIVIDE_9 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_9,
/// 0b001001: Divide by 10
DIVIDE_10 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_10,
/// 0b001010: Divide by 11
DIVIDE_11 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_11,
/// 0b001011: Divide by 12
DIVIDE_12 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_12,
/// 0b001100: Divide by 13
DIVIDE_13 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_13,
/// 0b001101: Divide by 14
DIVIDE_14 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_14,
/// 0b001110: Divide by 15
DIVIDE_15 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_15,
/// 0b001111: Divide by 16
DIVIDE_16 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_16,
/// 0b010000: Divide by 17
DIVIDE_17 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_17,
/// 0b010001: Divide by 18
DIVIDE_18 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_18,
/// 0b010010: Divide by 19
DIVIDE_19 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_19,
/// 0b010011: Divide by 20
DIVIDE_20 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_20,
/// 0b010100: Divide by 21
DIVIDE_21 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_21,
/// 0b010101: Divide by 22
DIVIDE_22 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_22,
/// 0b010110: Divide by 23
DIVIDE_23 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_23,
/// 0b010111: Divide by 24
DIVIDE_24 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_24,
/// 0b011000: Divide by 25
DIVIDE_25 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_25,
/// 0b011001: Divide by 26
DIVIDE_26 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_26,
/// 0b011010: Divide by 27
DIVIDE_27 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_27,
/// 0b011011: Divide by 28
DIVIDE_28 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_28,
/// 0b011100: Divide by 29
DIVIDE_29 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_29,
/// 0b011101: Divide by 30
DIVIDE_30 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_30,
/// 0b011110: Divide by 31
DIVIDE_31 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_31,
/// 0b011111: Divide by 32
DIVIDE_32 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_32,
/// 0b100000: Divide by 33
DIVIDE_33 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_33,
/// 0b100001: Divide by 34
DIVIDE_34 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_34,
/// 0b100010: Divide by 35
DIVIDE_35 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_35,
/// 0b100011: Divide by 36
DIVIDE_36 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_36,
/// 0b100100: Divide by 37
DIVIDE_37 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_37,
/// 0b100101: Divide by 38
DIVIDE_38 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_38,
/// 0b100110: Divide by 39
DIVIDE_39 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_39,
/// 0b100111: Divide by 40
DIVIDE_40 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_40,
/// 0b101000: Divide by 41
DIVIDE_41 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_41,
/// 0b101001: Divide by 42
DIVIDE_42 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_42,
/// 0b101010: Divide by 43
DIVIDE_43 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_43,
/// 0b101011: Divide by 44
DIVIDE_44 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_44,
/// 0b101100: Divide by 45
DIVIDE_45 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_45,
/// 0b101101: Divide by 46
DIVIDE_46 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_46,
/// 0b101110: Divide by 47
DIVIDE_47 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_47,
/// 0b101111: Divide by 48
DIVIDE_48 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_48,
/// 0b110000: Divide by 49
DIVIDE_49 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_49,
/// 0b110001: Divide by 50
DIVIDE_50 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_50,
/// 0b110010: Divide by 51
DIVIDE_51 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_51,
/// 0b110011: Divide by 52
DIVIDE_52 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_52,
/// 0b110100: Divide by 53
DIVIDE_53 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_53,
/// 0b110101: Divide by 54
DIVIDE_54 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_54,
/// 0b110110: Divide by 55
DIVIDE_55 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_55,
/// 0b110111: Divide by 56
DIVIDE_56 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_56,
/// 0b111000: Divide by 57
DIVIDE_57 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_57,
/// 0b111001: Divide by 58
DIVIDE_58 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_58,
/// 0b111010: Divide by 59
DIVIDE_59 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_59,
/// 0b111011: Divide by 60
DIVIDE_60 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_60,
/// 0b111100: Divide by 61
DIVIDE_61 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_61,
/// 0b111101: Divide by 62
DIVIDE_62 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_62,
/// 0b111110: Divide by 63
DIVIDE_63 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_63,
/// 0b111111: Divide by 64
DIVIDE_64 = ral::ccm::CSCDR1::UART_CLK_PODF::RW::DIVIDE_64,
}
impl From<PrescalarSelect> for Divider {
fn from(prescale: PrescalarSelect) -> Divider {
Divider((prescale as u32) + 1)
}
}
impl From<ClockSelect> for Frequency {
fn from(clock_select: ClockSelect) -> Self {
match clock_select {
ClockSelect::OSC => OSCILLATOR_FREQUENCY,
}
}
}
/// An opaque type that describes timing configurations
pub struct Timings {
/// OSR register value. Accounts for the -1. May be written
/// directly to the register
pub(crate) osr: u8,
/// True if we need to set BOTHEDGE given the OSR value
pub(crate) both_edge: bool,
/// SBR value;
pub(crate) sbr: u16,
}
#[derive(Clone, Copy, Debug)]
pub enum TimingsError {
DivideByZero,
OutOfRange,
}
/// Compute timings for a UART peripheral. Returns the timings,
/// or a string describing an error.
pub(crate) fn timings(effective_clock: Frequency, baud: u32) -> Result<Timings, TimingsError> {
let effective_clock = effective_clock.0;
// effective_clock
// baud = ---------------
// (OSR+1)(SBR)
//
// Solve for SBR:
//
// effective_clock
// SBR = ---------------
// (OSR+1)(baud)
//
// After selecting SBR, calculate effective baud.
// Minimize the error over all OSRs.
let base_clock: u32 = effective_clock
.checked_div(baud)
.ok_or(TimingsError::DivideByZero)?;
let mut error = u32::max_value();
let mut best_osr = 16;
let mut best_sbr = 1;
for osr in 4..=32 {
let sbr = base_clock
.checked_div(osr)
.ok_or(TimingsError::DivideByZero)?;
let sbr = sbr.max(1).min(8191);
let effective_baud = effective_clock
.checked_div(osr * sbr)
.ok_or(TimingsError::DivideByZero)?;
let err = effective_baud.max(baud) - effective_baud.min(baud);
if err < error {
best_osr = osr;
best_sbr = sbr;
error = err
}
}
use core::convert::TryFrom;
Ok(Timings {
osr: u8::try_from(best_osr - 1).map_err(|_| TimingsError::OutOfRange)?,
sbr: u16::try_from(best_sbr).map_err(|_| TimingsError::OutOfRange)?,
both_edge: best_osr < 8,
})
}
}
/// Timing configurations for SPI peripherals
pub mod spi { | use super::{ral::ccm, Divider, Frequency};
#[derive(Clone, Copy)]
#[non_exhaustive] // Not all variants added
pub enum ClockSelect {
Pll2,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[allow(non_camel_case_types)] // Easier mapping if the names are consistent
#[repr(u32)]
pub enum PrescalarSelect {
/// 0b0000: divide by 1
LPSPI_PODF_0 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_0,
/// 0b0001: divide by 2
LPSPI_PODF_1 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_1,
/// 0b0010: divide by 3
LPSPI_PODF_2 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_2,
/// 0b0011: divide by 4
LPSPI_PODF_3 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_3,
/// 0b0100: divide by 5
LPSPI_PODF_4 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_4,
/// 0b0101: divide by 6
LPSPI_PODF_5 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_5,
/// 0b0110: divide by 7
LPSPI_PODF_6 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_6,
/// 0b0111: divide by 8
LPSPI_PODF_7 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_7,
/// 0b1000: divide by 9
#[cfg(features = "imxrt1011")]
LPSPI_PODF_8 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_8,
/// 0b1001: divide by 10
#[cfg(features = "imxrt1011")]
LPSPI_PODF_9 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_9,
/// 0b1010: divide by 11
#[cfg(features = "imxrt1011")]
LPSPI_PODF_10 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_10,
/// 0b1011: divide by 12
#[cfg(features = "imxrt1011")]
LPSPI_PODF_11 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_11,
/// 0b1100: divide by 13
#[cfg(features = "imxrt1011")]
LPSPI_PODF_12 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_12,
/// 0b1101: divide by 14
#[cfg(features = "imxrt1011")]
LPSPI_PODF_13 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_13,
/// 0b1110: divide by 15
#[cfg(features = "imxrt1011")]
LPSPI_PODF_14 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_14,
/// 0b1111: divide by 16
#[cfg(features = "imxrt1011")]
LPSPI_PODF_15 = ccm::CBCMR::LPSPI_PODF::RW::LPSPI_PODF_15,
}
impl From<ClockSelect> for Frequency {
fn from(clock_select: ClockSelect) -> Self {
match clock_select {
ClockSelect::Pll2 => Frequency(528_000_000),
}
}
}
impl From<PrescalarSelect> for Divider {
fn from(prescalar_select: PrescalarSelect) -> Self {
Divider((prescalar_select as u32) + 1)
}
}
} | |
NavigationTabsWidget.tsx | /*
* TESLER-UI
* Copyright (C) 2018-2020 Tesler Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react'
import NavigationTabs from '../../ui/NavigationTabs/NavigationTabs'
import { NavigationWidgetMeta } from '../../../interfaces/widget'
export interface NavigationTabsWidgetProps {
meta: NavigationWidgetMeta
}
function | ({ meta }: NavigationTabsWidgetProps) {
return <NavigationTabs navigationLevel={meta.options?.navigationLevel ?? 1} />
}
export default React.memo(NavigationTabsWidget)
| NavigationTabsWidget |
pod_template.py | # Copyright 2020 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# coding: utf-8
"""
Tekton
Tekton Pipeline # noqa: E501
The version of the OpenAPI document: v0.17.2
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from tekton_pipeline.configuration import Configuration
class PodTemplate(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'affinity': 'V1Affinity',
'automount_service_account_token': 'bool',
'dns_config': 'V1PodDNSConfig',
'dns_policy': 'str',
'enable_service_links': 'bool',
'host_network': 'bool',
'image_pull_secrets': 'list[V1LocalObjectReference]',
'node_selector': 'dict(str, str)',
'priority_class_name': 'str',
'runtime_class_name': 'str',
'scheduler_name': 'str',
'security_context': 'V1PodSecurityContext',
'tolerations': 'list[V1Toleration]',
'volumes': 'list[V1Volume]'
}
attribute_map = {
'affinity': 'affinity',
'automount_service_account_token': 'automountServiceAccountToken',
'dns_config': 'dnsConfig',
'dns_policy': 'dnsPolicy',
'enable_service_links': 'enableServiceLinks',
'host_network': 'hostNetwork',
'image_pull_secrets': 'imagePullSecrets',
'node_selector': 'nodeSelector',
'priority_class_name': 'priorityClassName',
'runtime_class_name': 'runtimeClassName',
'scheduler_name': 'schedulerName',
'security_context': 'securityContext',
'tolerations': 'tolerations',
'volumes': 'volumes'
}
def __init__(self, affinity=None, automount_service_account_token=None, dns_config=None, dns_policy=None, enable_service_links=None, host_network=None, image_pull_secrets=None, node_selector=None, priority_class_name=None, runtime_class_name=None, scheduler_name=None, security_context=None, tolerations=None, volumes=None, local_vars_configuration=None): # noqa: E501
"""PodTemplate - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._affinity = None
self._automount_service_account_token = None
self._dns_config = None
self._dns_policy = None
self._enable_service_links = None
self._host_network = None
self._image_pull_secrets = None
self._node_selector = None
self._priority_class_name = None
self._runtime_class_name = None
self._scheduler_name = None
self._security_context = None
self._tolerations = None
self._volumes = None
self.discriminator = None
if affinity is not None:
self.affinity = affinity
if automount_service_account_token is not None:
self.automount_service_account_token = automount_service_account_token
if dns_config is not None:
self.dns_config = dns_config
if dns_policy is not None:
self.dns_policy = dns_policy
if enable_service_links is not None:
self.enable_service_links = enable_service_links
if host_network is not None:
self.host_network = host_network
if image_pull_secrets is not None:
self.image_pull_secrets = image_pull_secrets
if node_selector is not None:
self.node_selector = node_selector
if priority_class_name is not None:
self.priority_class_name = priority_class_name
if runtime_class_name is not None:
self.runtime_class_name = runtime_class_name
if scheduler_name is not None:
self.scheduler_name = scheduler_name
if security_context is not None:
self.security_context = security_context
if tolerations is not None:
self.tolerations = tolerations
if volumes is not None:
self.volumes = volumes
@property
def affinity(self):
"""Gets the affinity of this PodTemplate. # noqa: E501
:return: The affinity of this PodTemplate. # noqa: E501
:rtype: V1Affinity
"""
return self._affinity
@affinity.setter
def affinity(self, affinity):
"""Sets the affinity of this PodTemplate.
:param affinity: The affinity of this PodTemplate. # noqa: E501
:type: V1Affinity
"""
self._affinity = affinity
@property
def automount_service_account_token(self):
"""Gets the automount_service_account_token of this PodTemplate. # noqa: E501
AutomountServiceAccountToken indicates whether pods running as this service account should have an API token automatically mounted. # noqa: E501
:return: The automount_service_account_token of this PodTemplate. # noqa: E501
:rtype: bool
"""
return self._automount_service_account_token
@automount_service_account_token.setter
def automount_service_account_token(self, automount_service_account_token):
"""Sets the automount_service_account_token of this PodTemplate.
AutomountServiceAccountToken indicates whether pods running as this service account should have an API token automatically mounted. # noqa: E501
:param automount_service_account_token: The automount_service_account_token of this PodTemplate. # noqa: E501
:type: bool
"""
self._automount_service_account_token = automount_service_account_token
@property
def dns_config(self):
"""Gets the dns_config of this PodTemplate. # noqa: E501
:return: The dns_config of this PodTemplate. # noqa: E501
:rtype: V1PodDNSConfig
"""
return self._dns_config
@dns_config.setter
def dns_config(self, dns_config):
"""Sets the dns_config of this PodTemplate.
:param dns_config: The dns_config of this PodTemplate. # noqa: E501
:type: V1PodDNSConfig
"""
self._dns_config = dns_config
@property
def dns_policy(self):
"""Gets the dns_policy of this PodTemplate. # noqa: E501
Set DNS policy for the pod. Defaults to \"ClusterFirst\". Valid values are 'ClusterFirst', 'Default' or 'None'. DNS parameters given in DNSConfig will be merged with the policy selected with DNSPolicy. # noqa: E501
:return: The dns_policy of this PodTemplate. # noqa: E501
:rtype: str
"""
return self._dns_policy
@dns_policy.setter
def dns_policy(self, dns_policy):
"""Sets the dns_policy of this PodTemplate.
Set DNS policy for the pod. Defaults to \"ClusterFirst\". Valid values are 'ClusterFirst', 'Default' or 'None'. DNS parameters given in DNSConfig will be merged with the policy selected with DNSPolicy. # noqa: E501
:param dns_policy: The dns_policy of this PodTemplate. # noqa: E501
:type: str
"""
self._dns_policy = dns_policy
@property
def enable_service_links(self):
"""Gets the enable_service_links of this PodTemplate. # noqa: E501
EnableServiceLinks indicates whether information about services should be injected into pod's environment variables, matching the syntax of Docker links. Optional: Defaults to true. # noqa: E501
:return: The enable_service_links of this PodTemplate. # noqa: E501
:rtype: bool
"""
return self._enable_service_links
@enable_service_links.setter
def enable_service_links(self, enable_service_links):
"""Sets the enable_service_links of this PodTemplate.
EnableServiceLinks indicates whether information about services should be injected into pod's environment variables, matching the syntax of Docker links. Optional: Defaults to true. # noqa: E501
:param enable_service_links: The enable_service_links of this PodTemplate. # noqa: E501
:type: bool
"""
self._enable_service_links = enable_service_links
@property
def host_network(self):
"""Gets the host_network of this PodTemplate. # noqa: E501
HostNetwork specifies whether the pod may use the node network namespace # noqa: E501
:return: The host_network of this PodTemplate. # noqa: E501
:rtype: bool
"""
return self._host_network
@host_network.setter
def host_network(self, host_network):
"""Sets the host_network of this PodTemplate.
HostNetwork specifies whether the pod may use the node network namespace # noqa: E501
:param host_network: The host_network of this PodTemplate. # noqa: E501
:type: bool
"""
self._host_network = host_network
@property
def image_pull_secrets(self):
"""Gets the image_pull_secrets of this PodTemplate. # noqa: E501
ImagePullSecrets gives the name of the secret used by the pod to pull the image if specified # noqa: E501
:return: The image_pull_secrets of this PodTemplate. # noqa: E501
:rtype: list[V1LocalObjectReference]
"""
return self._image_pull_secrets
@image_pull_secrets.setter
def image_pull_secrets(self, image_pull_secrets):
"""Sets the image_pull_secrets of this PodTemplate.
ImagePullSecrets gives the name of the secret used by the pod to pull the image if specified # noqa: E501
:param image_pull_secrets: The image_pull_secrets of this PodTemplate. # noqa: E501
:type: list[V1LocalObjectReference]
"""
self._image_pull_secrets = image_pull_secrets
@property
def node_selector(self):
"""Gets the node_selector of this PodTemplate. # noqa: E501
NodeSelector is a selector which must be true for the pod to fit on a node. Selector which must match a node's labels for the pod to be scheduled on that node. More info: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/ # noqa: E501
:return: The node_selector of this PodTemplate. # noqa: E501
:rtype: dict(str, str)
"""
return self._node_selector
@node_selector.setter
def node_selector(self, node_selector):
"""Sets the node_selector of this PodTemplate.
NodeSelector is a selector which must be true for the pod to fit on a node. Selector which must match a node's labels for the pod to be scheduled on that node. More info: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/ # noqa: E501
:param node_selector: The node_selector of this PodTemplate. # noqa: E501
:type: dict(str, str)
"""
self._node_selector = node_selector
@property
def priority_class_name(self):
"""Gets the priority_class_name of this PodTemplate. # noqa: E501
If specified, indicates the pod's priority. \"system-node-critical\" and \"system-cluster-critical\" are two special keywords which indicate the highest priorities with the former being the highest priority. Any other name must be defined by creating a PriorityClass object with that name. If not specified, the pod priority will be default or zero if there is no default. # noqa: E501
:return: The priority_class_name of this PodTemplate. # noqa: E501
:rtype: str
"""
return self._priority_class_name
@priority_class_name.setter
def priority_class_name(self, priority_class_name):
"""Sets the priority_class_name of this PodTemplate.
If specified, indicates the pod's priority. \"system-node-critical\" and \"system-cluster-critical\" are two special keywords which indicate the highest priorities with the former being the highest priority. Any other name must be defined by creating a PriorityClass object with that name. If not specified, the pod priority will be default or zero if there is no default. # noqa: E501
:param priority_class_name: The priority_class_name of this PodTemplate. # noqa: E501
:type: str
"""
self._priority_class_name = priority_class_name
@property
def runtime_class_name(self):
"""Gets the runtime_class_name of this PodTemplate. # noqa: E501
RuntimeClassName refers to a RuntimeClass object in the node.k8s.io group, which should be used to run this pod. If no RuntimeClass resource matches the named class, the pod will not be run. If unset or empty, the \"legacy\" RuntimeClass will be used, which is an implicit class with an empty definition that uses the default runtime handler. More info: https://git.k8s.io/enhancements/keps/sig-node/runtime-class.md This is a beta feature as of Kubernetes v1.14. # noqa: E501
:return: The runtime_class_name of this PodTemplate. # noqa: E501
:rtype: str
"""
return self._runtime_class_name
@runtime_class_name.setter
def runtime_class_name(self, runtime_class_name):
"""Sets the runtime_class_name of this PodTemplate.
RuntimeClassName refers to a RuntimeClass object in the node.k8s.io group, which should be used to run this pod. If no RuntimeClass resource matches the named class, the pod will not be run. If unset or empty, the \"legacy\" RuntimeClass will be used, which is an implicit class with an empty definition that uses the default runtime handler. More info: https://git.k8s.io/enhancements/keps/sig-node/runtime-class.md This is a beta feature as of Kubernetes v1.14. # noqa: E501
:param runtime_class_name: The runtime_class_name of this PodTemplate. # noqa: E501
:type: str
"""
self._runtime_class_name = runtime_class_name
@property
def scheduler_name(self):
"""Gets the scheduler_name of this PodTemplate. # noqa: E501
SchedulerName specifies the scheduler to be used to dispatch the Pod # noqa: E501
:return: The scheduler_name of this PodTemplate. # noqa: E501
:rtype: str
"""
return self._scheduler_name
@scheduler_name.setter
def scheduler_name(self, scheduler_name):
"""Sets the scheduler_name of this PodTemplate.
SchedulerName specifies the scheduler to be used to dispatch the Pod # noqa: E501
:param scheduler_name: The scheduler_name of this PodTemplate. # noqa: E501
:type: str
"""
self._scheduler_name = scheduler_name
@property
def security_context(self):
"""Gets the security_context of this PodTemplate. # noqa: E501
:return: The security_context of this PodTemplate. # noqa: E501
:rtype: V1PodSecurityContext
"""
return self._security_context
@security_context.setter
def security_context(self, security_context):
"""Sets the security_context of this PodTemplate.
:param security_context: The security_context of this PodTemplate. # noqa: E501
:type: V1PodSecurityContext
"""
self._security_context = security_context
@property
def tolerations(self):
"""Gets the tolerations of this PodTemplate. # noqa: E501
If specified, the pod's tolerations. # noqa: E501
:return: The tolerations of this PodTemplate. # noqa: E501
:rtype: list[V1Toleration]
"""
return self._tolerations
@tolerations.setter
def tolerations(self, tolerations):
"""Sets the tolerations of this PodTemplate.
If specified, the pod's tolerations. # noqa: E501
:param tolerations: The tolerations of this PodTemplate. # noqa: E501
:type: list[V1Toleration]
"""
self._tolerations = tolerations
@property
def volumes(self):
"""Gets the volumes of this PodTemplate. # noqa: E501
List of volumes that can be mounted by containers belonging to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes # noqa: E501
:return: The volumes of this PodTemplate. # noqa: E501
:rtype: list[V1Volume]
"""
return self._volumes
@volumes.setter
def volumes(self, volumes):
"""Sets the volumes of this PodTemplate.
List of volumes that can be mounted by containers belonging to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes # noqa: E501
:param volumes: The volumes of this PodTemplate. # noqa: E501
:type: list[V1Volume]
"""
self._volumes = volumes
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def | (self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, PodTemplate):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, PodTemplate):
return True
return self.to_dict() != other.to_dict()
| __repr__ |
key_log_file.rs | #[cfg(feature = "logging")]
use crate::log::warn;
use crate::KeyLog;
use std::env;
use std::fs::{File, OpenOptions};
use std::io;
use std::io::Write;
use std::path::Path;
use std::sync::Mutex;
// Internal mutable state for KeyLogFile
struct KeyLogFileInner {
file: Option<File>,
buf: Vec<u8>,
}
impl KeyLogFileInner {
fn new(var: Result<String, env::VarError>) -> Self {
let path = match var {
Ok(ref s) => Path::new(s),
Err(env::VarError::NotUnicode(ref s)) => Path::new(s),
Err(env::VarError::NotPresent) => {
return Self {
file: None,
buf: Vec::new(),
};
}
};
#[cfg_attr(not(feature = "logging"), allow(unused_variables))]
let file = match OpenOptions::new()
.append(true)
.create(true)
.open(path)
{
Ok(f) => Some(f),
Err(e) => {
warn!("unable to create key log file {:?}: {}", path, e);
None
}
};
Self {
file,
buf: Vec::new(),
}
}
fn try_write(&mut self, label: &str, client_random: &[u8], secret: &[u8]) -> io::Result<()> {
let mut file = match self.file {
None => {
return Ok(());
}
Some(ref f) => f,
};
self.buf.truncate(0);
write!(self.buf, "{} ", label)?;
for b in client_random.iter() {
write!(self.buf, "{:02x}", b)?;
}
write!(self.buf, " ")?;
for b in secret.iter() {
write!(self.buf, "{:02x}", b)?;
}
writeln!(self.buf)?;
file.write_all(&self.buf)
}
}
/// [`KeyLog`] implementation that opens a file whose name is
/// given by the `SSLKEYLOGFILE` environment variable, and writes
/// keys into it.
///
/// If `SSLKEYLOGFILE` is not set, this does nothing.
///
/// If such a file cannot be opened, or cannot be written then
/// this does nothing but logs errors at warning-level.
pub struct KeyLogFile(Mutex<KeyLogFileInner>);
impl KeyLogFile {
/// Makes a new `KeyLogFile`. The environment variable is
/// inspected and the named file is opened during this call.
pub fn new() -> Self {
let var = env::var("SSLKEYLOGFILE");
Self(Mutex::new(KeyLogFileInner::new(var)))
}
}
impl KeyLog for KeyLogFile {
fn log(&self, label: &str, client_random: &[u8], secret: &[u8]) {
#[cfg_attr(not(feature = "logging"), allow(unused_variables))]
match self
.0
.lock()
.unwrap()
.try_write(label, client_random, secret)
{
Ok(()) => {}
Err(e) => {
warn!("error writing to key log file: {}", e);
}
}
}
}
#[cfg(all(test, target_os = "linux"))]
mod test {
use super::*;
fn init() {
let _ = env_logger::builder()
.is_test(true)
.try_init();
}
#[test]
fn test_env_var_is_not_unicode() {
init();
let mut inner = KeyLogFileInner::new(Err(env::VarError::NotUnicode(
"/tmp/keylogfileinnertest".into(),
)));
assert!(inner
.try_write("label", b"random", b"secret")
.is_ok());
}
#[test]
fn test_env_var_is_not_set() {
init();
let mut inner = KeyLogFileInner::new(Err(env::VarError::NotPresent));
assert!(inner
.try_write("label", b"random", b"secret")
.is_ok());
}
#[test]
fn test_env_var_cannot_be_opened() |
#[test]
fn test_env_var_cannot_be_written() {
init();
let mut inner = KeyLogFileInner::new(Ok("/dev/full".into()));
assert!(inner
.try_write("label", b"random", b"secret")
.is_err());
}
}
| {
init();
let mut inner = KeyLogFileInner::new(Ok("/dev/does-not-exist".into()));
assert!(inner
.try_write("label", b"random", b"secret")
.is_ok());
} |
projection.rs | // Copyright 2020 Andy Grove
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Projection operator.
use std::sync::Arc;
use crate::arrow::datatypes::Schema;
use crate::datafusion::logicalplan::Expr;
use crate::error::Result;
use crate::execution::physical_plan::{
compile_expressions, ColumnarBatch, ColumnarBatchIter, ColumnarBatchStream, ColumnarValue,
ExecutionContext, ExecutionPlan, Expression, Partitioning, PhysicalPlan,
};
use async_trait::async_trait;
/// Projection operator evaluates expressions against an input.
#[derive(Debug, Clone)]
pub struct | {
/// Logical expressions for the projection.
pub(crate) exprs: Vec<Expr>,
/// The input operator to apply the projection to.
pub(crate) child: Arc<PhysicalPlan>,
/// The resulting schema of the projection.
pub(crate) schema: Arc<Schema>,
}
impl ProjectionExec {
pub fn try_new(exprs: &[Expr], child: Arc<PhysicalPlan>) -> Result<Self> {
let input_schema = child.as_execution_plan().schema();
let pexprs = compile_expressions(&exprs, &child.as_execution_plan().schema())?;
let fields: Result<Vec<_>> = pexprs
.iter()
.map(|e| e.to_schema_field(&input_schema))
.collect();
let schema = Arc::new(Schema::new(fields?));
Ok(Self {
exprs: exprs.to_vec(),
child,
schema,
})
}
pub fn with_new_children(&self, new_children: Vec<Arc<PhysicalPlan>>) -> ProjectionExec {
assert!(new_children.len() == 1);
ProjectionExec {
exprs: self.exprs.clone(),
child: new_children[0].clone(),
schema: self.schema.clone(),
}
}
}
#[async_trait]
impl ExecutionPlan for ProjectionExec {
fn schema(&self) -> Arc<Schema> {
self.schema.clone()
}
fn children(&self) -> Vec<Arc<PhysicalPlan>> {
vec![self.child.clone()]
}
fn output_partitioning(&self) -> Partitioning {
self.child.as_execution_plan().output_partitioning()
}
async fn execute(
&self,
ctx: Arc<dyn ExecutionContext>,
partition_index: usize,
) -> Result<ColumnarBatchStream> {
let input = &self.child.as_execution_plan();
let projection = compile_expressions(&self.exprs, &input.schema())?;
Ok(Arc::new(ProjectionIter {
input: input.execute(ctx.clone(), partition_index).await?,
projection,
schema: self.schema.clone(),
}))
}
}
/// Iterator that applies a projection to the batches
struct ProjectionIter {
input: ColumnarBatchStream,
projection: Vec<Arc<dyn Expression>>,
schema: Arc<Schema>,
}
impl ColumnarBatchIter for ProjectionIter {
fn schema(&self) -> Arc<Schema> {
self.schema.clone()
}
fn next(&self) -> Result<Option<ColumnarBatch>> {
match self.input.next()? {
Some(batch) => {
let projected_values: Vec<ColumnarValue> = self
.projection
.iter()
.map(|e| e.evaluate(&batch))
.collect::<Result<Vec<_>>>()?;
Ok(Some(ColumnarBatch::from_values_and_schema(
&projected_values,
self.schema.clone(),
)))
}
None => Ok(None),
}
}
}
| ProjectionExec |
ui_layout_table.go | package game
type UILayoutTable struct {
gi *GlobalInfo
id int
transform *Transform
UISpec UISpec
//
ElementWidth float32 // 相邻元素的间隔宽度
ElementHeight float32 // 相邻元素的间隔高度
Rows int // 一行不得超过
Cols int // 一列不得超过
//
Elements []UICanBeLayout //
}
func NewUILayoutTable(gi *GlobalInfo) *UILayoutTable {
uilt := new(UILayoutTable)
uilt.gi = gi
uilt.transform | (_id) == 0 {
return uilt.id
}
if len(_id) > 1 {
panic("len(_id)")
}
uilt.id = _id[0]
return uilt.id
}
func (uilt *UILayoutTable) Start() {
}
func (uilt *UILayoutTable) Update() {
{
// 根据 UISpec 得到真正要渲染的参数
widthDeform := uilt.gi.GetWindowWidth() / uilt.gi.UICanvas.DesignWidth
heightDeform := uilt.gi.GetWindowHeight() / uilt.gi.UICanvas.DesignHeight
// 1. pos
{
posx, posy := uilt.UISpec.LocalPos.GetValue2()
posrx, posry := uilt.UISpec.PosRelativity.GetValue2()
// 根据真实分辨率,计算新的位置
posxNew := posx * widthDeform
posyNew := posy * heightDeform
posxNew = (1-posrx)*posx + posrx*posxNew
posyNew = (1-posry)*posy + posry*posyNew
uilt.transform.Postion.SetIndexValue(0, posxNew)
uilt.transform.Postion.SetIndexValue(1, posyNew)
}
// 2. scale
{
scalex := 1 + uilt.UISpec.SizeRelativity.GetIndexValue(0)*(widthDeform-1)
scaley := 1 + uilt.UISpec.SizeRelativity.GetIndexValue(1)*(heightDeform-1)
uilt.transform.Scale.SetValue2(
scalex,
scaley,
)
}
// 3. rotate
{
// uibutton.transform.Rotation.SetZ(
// float32(uibutton.gi.CurFrame) / 2,
// )
}
}
}
func (uilt *UILayoutTable) SetEles(eles []UICanBeLayout) {
for _, onebutton := range eles {
onebutton.GetTransform().SetParent(uilt.transform)
}
uilt.Elements = eles
}
// 排列一次,根据所有的参数,算出最终的各个元素的参数
// 主要是改变元素的 UISpec.LocalPos
func (uilt *UILayoutTable) Arrange() {
if uilt.Rows+uilt.Cols == 0 {
return
}
if uilt.Rows > 0 {
uilt.arrangeByRow()
return
}
if uilt.Cols > 0 {
uilt.arrangeByCol()
return
}
}
// 每行不得超过 uilt.Rows
func (uilt *UILayoutTable) arrangeByRow() {
// offx, offy := uilt.UISpec.LocalPos.GetValue2()
offx, offy := float32(0), float32(0)
tx, ty := float32(0), float32(0)
for idx, oneele := range uilt.Elements {
ty = offy - float32(idx/uilt.Rows)*uilt.ElementHeight
tx = offx + float32(idx%uilt.Rows)*uilt.ElementWidth
oneele.GetUISpec().LocalPos.SetValue2(tx, ty)
}
}
// 每列不得超过 uilt.Cols
func (uilt *UILayoutTable) arrangeByCol() {
// offx, offy := uilt.UISpec.LocalPos.GetValue2()
offx, offy := float32(0), float32(0)
tx, ty := float32(0), float32(0)
for idx, oneele := range uilt.Elements {
tx = offx + float32(idx/uilt.Cols)*uilt.ElementWidth
ty = offy - float32(idx%uilt.Cols)*uilt.ElementHeight
oneele.GetUISpec().LocalPos.SetValue2(tx, ty)
}
}
| = NewTransform(nil)
return uilt
}
func (uilt *UILayoutTable) ID_sg(_id ...int) int {
if len |
mod.rs | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
impl super::DIVH {
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R |
}
#[doc = r" Value of the field"]
pub struct DIVHR {
bits: u8,
}
impl DIVHR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:3 - RTC prescaler divider register high"]
#[inline]
pub fn divh(&self) -> DIVHR {
let bits = {
const MASK: u8 = 15;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u8
};
DIVHR { bits }
}
}
| {
R {
bits: self.register.get(),
}
} |
extension.ts | import * as vscode from 'vscode'
import { componentMap, ComponentDescriptor } from './componentMap'
import { bigCamelize, kebabCase } from './utils'
const DOC = 'https://varlet-varletjs.vercel.app/#/zh-CN'
const DOC_VUE2 = 'https://varlet-vue2.vercel.app/#/zh-CN'
const EN_DOC = 'https://varlet-varletjs.vercel.app/#/en-US'
const EN_DOC_VUE2 = 'https://varlet-vue2.vercel.app/#/en-US'
const LINK_RE = /(?<=<var-)([\w-]+)/g
const BIG_CAMELIZE_RE = /(?<=<Var)([\w-]+)/g
const files = ['vue', 'typescript', 'javascript', 'javascriptreact', 'typescriptreact']
function provideCompletionItems() {
const completionItems: vscode.CompletionItem[] = []
Object.keys(componentMap).forEach((key) => {
completionItems.push(
new vscode.CompletionItem(`var-${key}`, vscode.CompletionItemKind.Field),
new vscode.CompletionItem(bigCamelize(`var-${key}`), vscode.CompletionItemKind.Field)
)
})
return completionItems
}
function resolveCompletionItem(item: vscode.CompletionItem) {
const name = kebabCase(item.label as string).slice(4)
const descriptor: ComponentDescriptor = componentMap[name]
const attrText = descriptor.attrs ? ' ' + descriptor.attrs.join(' ') : ''
const tagSuffix = descriptor.closeSelf ? '' : `</${item.label}>`
const characterDelta = -tagSuffix.length + (descriptor.characterDelta ?? 0)
item.insertText = `<${item.label}${attrText}`
item.insertText += descriptor.closeSelf ? '/>' : `>${tagSuffix}`
item.command = {
title: 'move-cursor',
command: 'move-cursor',
arguments: [characterDelta],
}
return item
}
function | (document: vscode.TextDocument, position: vscode.Position) {
const line = document.lineAt(position)
const linkComponents = line.text.match(LINK_RE) ?? []
const bigCamelizeComponents = line.text.match(BIG_CAMELIZE_RE) ?? []
const components = [...new Set([...linkComponents, ...bigCamelizeComponents.map(kebabCase)])]
if (components.length) {
const contents = components
.filter((component) => componentMap[component])
.map((component) => {
const { site } = componentMap[component]
const isCN = vscode.env.language === 'zh-cn'
const text = isCN
? `查看${bigCamelize(component)}组件官方文档`
: `Watch ${bigCamelize(component)} component documentation`
return `\
[Varlet -> ${text}](${isCN ? DOC : EN_DOC}${site})\n
[Varlet-vue2 -> ${text}](${isCN ? DOC_VUE2 : EN_DOC_VUE2}${site})`
})
return new vscode.Hover(contents)
}
}
function moveCursor(characterDelta: number) {
const active = vscode.window.activeTextEditor!.selection.active!
const position = active.translate({ characterDelta })
vscode.window.activeTextEditor!.selection = new vscode.Selection(position, position)
}
export function activate(context: vscode.ExtensionContext) {
vscode.commands.registerCommand('move-cursor', moveCursor)
context.subscriptions.push(
vscode.languages.registerHoverProvider(files, {
provideHover,
}),
vscode.languages.registerCompletionItemProvider(files, {
provideCompletionItems,
resolveCompletionItem,
})
)
}
export function deactivate() {}
| provideHover |
00_db.py | # -*- coding: utf-8 -*-
"""
Import Modules
Configure the Database
Instantiate Classes
"""
if settings.get_L10n_languages_readonly():
# Make the Language files read-only for improved performance
T.is_writable = False
get_vars = request.get_vars
# Are we running in debug mode?
settings.check_debug()
import datetime
try:
import json # try stdlib (Python 2.6)
except ImportError:
try:
import simplejson as json # try external module
except:
import gluon.contrib.simplejson as json # fallback to pure-Python module
########################
# Database Configuration
########################
migrate = settings.get_base_migrate()
fake_migrate = settings.get_base_fake_migrate()
if migrate:
check_reserved = ["mysql", "postgres"]
else:
check_reserved = None
(db_string, pool_size) = settings.get_database_string()
if db_string.find("sqlite") != -1:
db = DAL(db_string,
check_reserved=check_reserved,
migrate_enabled = migrate,
fake_migrate_all = fake_migrate,
lazy_tables = not migrate)
# on SQLite 3.6.19+ this enables foreign key support (included in Python 2.7+)
# db.executesql("PRAGMA foreign_keys=ON")
else:
try:
if db_string.find("mysql") != -1:
# Use MySQLdb where available (pymysql has given broken pipes)
# - done automatically now, no need to add this manually
#try:
# import MySQLdb
# from gluon.dal import MySQLAdapter
# MySQLAdapter.driver = MySQLdb
#except ImportError:
# # Fallback to pymysql
# pass
if check_reserved:
check_reserved = ["postgres"]
db = DAL(db_string,
check_reserved = check_reserved,
pool_size = pool_size,
migrate_enabled = migrate,
lazy_tables = not migrate)
else:
# PostgreSQL
if check_reserved:
check_reserved = ["mysql"]
db = DAL(db_string,
check_reserved = check_reserved,
pool_size = pool_size,
migrate_enabled = migrate,
lazy_tables = not migrate)
except:
db_type = db_string.split(":", 1)[0]
db_location = db_string.split("@", 1)[1]
raise(HTTP(503, "Cannot connect to %s Database: %s" % (db_type, db_location)))
current.db = db
db.set_folder("upload")
# Sessions Storage
if settings.get_base_session_memcache():
# Store sessions in Memcache
from gluon.contrib.memcache import MemcacheClient
cache.memcache = MemcacheClient(request,
[settings.get_base_session_memcache()])
from gluon.contrib.memdb import MEMDB
session.connect(request, response, db=MEMDB(cache.memcache))
####################################################################
# Instantiate Classes from Modules #
# - store instances in current to be accessible from other modules #
####################################################################
from gluon.tools import Mail
mail = Mail()
current.mail = mail
from gluon.storage import Messages
messages = Messages(T)
current.messages = messages
ERROR = Messages(T)
current.ERROR = ERROR
# Import the S3 Framework
if update_check_needed:
# Reload the Field definitions
reload(s3base.s3fields)
else:
import s3 as s3base
# Set up logger (before any module attempts to use it!)
import s3log
s3log.S3Log.setup()
# AAA
current.auth = auth = s3base.AuthS3()
# Use session for persistent per-user variables
# - beware of a user having multiple tabs open!
# - don't save callables or class instances as these can't be pickled
if not session.s3:
session.s3 = Storage()
# Use username instead of email address for logins
# - would probably require further customisation
# to get this fully-working within Eden as it's not a Tested configuration
#auth.settings.login_userfield = "username"
auth.settings.hmac_key = settings.get_auth_hmac_key()
auth.define_tables(migrate=migrate, fake_migrate=fake_migrate)
current.audit = audit = s3base.S3Audit(migrate=migrate, fake_migrate=fake_migrate)
# Shortcuts for models/controllers/views
s3_has_role = auth.s3_has_role
s3_has_permission = auth.s3_has_permission
s3_logged_in_person = auth.s3_logged_in_person
# CRUD
s3.crud = Storage()
# S3 Custom Validators and Widgets, imported here into the global
# namespace in order to access them without the s3base namespace prefix
s3_action_buttons = s3base.S3CRUD.action_buttons
s3_fullname = s3base.s3_fullname
S3ResourceHeader = s3base.S3ResourceHeader
from s3.s3navigation import s3_rheader_tabs
from s3.s3validators import *
from s3.s3widgets import *
from s3.s3data import *
# GIS Module
gis = s3base.GIS()
current.gis = gis
# s3_request
s3_request = s3base.s3_request
# Field Selectors
FS = s3base.FS
# S3XML
s3xml = s3base.S3XML()
current.xml = s3xml
# Messaging
msg = s3base.S3Msg()
current.msg = msg
# Sync
sync = s3base.S3Sync()
current.sync = sync
# -----------------------------------------------------------------------------
def s3_clear_session():
# CRUD last opened records (rcvars)
s3base.s3_remove_last_record_id()
# Session-owned records
if "owned_records" in session:
del session["owned_records"]
if "s3" in session:
s3 = session.s3
opts = ["hrm", "report_options", "utc_offset", "deduplicate"]
for o in opts:
if o in s3:
del s3[o]
# -----------------------------------------------------------------------------
def s3_auth_on_login(form): | """
Actions to be performed upon successful login
Do not redirect from here!
"""
s3_clear_session()
# -----------------------------------------------------------------------------
def s3_auth_on_logout(user):
"""
Actions to be performed after logout
Do not redirect from here!
"""
s3_clear_session()
# END ========================================================================= | |
dcim_console_ports_partial_update_responses.go | // Code generated by go-swagger; DO NOT EDIT.
// Copyright 2020 The go-netbox Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package dcim
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
"github.com/fbreckle/go-netbox/netbox/models"
)
// DcimConsolePortsPartialUpdateReader is a Reader for the DcimConsolePortsPartialUpdate structure.
type DcimConsolePortsPartialUpdateReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *DcimConsolePortsPartialUpdateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewDcimConsolePortsPartialUpdateOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
default:
result := NewDcimConsolePortsPartialUpdateDefault(response.Code())
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
if response.Code()/100 == 2 {
return result, nil
}
return nil, result
}
}
// NewDcimConsolePortsPartialUpdateOK creates a DcimConsolePortsPartialUpdateOK with default headers values
func | () *DcimConsolePortsPartialUpdateOK {
return &DcimConsolePortsPartialUpdateOK{}
}
/* DcimConsolePortsPartialUpdateOK describes a response with status code 200, with default header values.
DcimConsolePortsPartialUpdateOK dcim console ports partial update o k
*/
type DcimConsolePortsPartialUpdateOK struct {
Payload *models.ConsolePort
}
func (o *DcimConsolePortsPartialUpdateOK) Error() string {
return fmt.Sprintf("[PATCH /dcim/console-ports/{id}/][%d] dcimConsolePortsPartialUpdateOK %+v", 200, o.Payload)
}
func (o *DcimConsolePortsPartialUpdateOK) GetPayload() *models.ConsolePort {
return o.Payload
}
func (o *DcimConsolePortsPartialUpdateOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(models.ConsolePort)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
// NewDcimConsolePortsPartialUpdateDefault creates a DcimConsolePortsPartialUpdateDefault with default headers values
func NewDcimConsolePortsPartialUpdateDefault(code int) *DcimConsolePortsPartialUpdateDefault {
return &DcimConsolePortsPartialUpdateDefault{
_statusCode: code,
}
}
/* DcimConsolePortsPartialUpdateDefault describes a response with status code -1, with default header values.
DcimConsolePortsPartialUpdateDefault dcim console ports partial update default
*/
type DcimConsolePortsPartialUpdateDefault struct {
_statusCode int
Payload interface{}
}
// Code gets the status code for the dcim console ports partial update default response
func (o *DcimConsolePortsPartialUpdateDefault) Code() int {
return o._statusCode
}
func (o *DcimConsolePortsPartialUpdateDefault) Error() string {
return fmt.Sprintf("[PATCH /dcim/console-ports/{id}/][%d] dcim_console-ports_partial_update default %+v", o._statusCode, o.Payload)
}
func (o *DcimConsolePortsPartialUpdateDefault) GetPayload() interface{} {
return o.Payload
}
func (o *DcimConsolePortsPartialUpdateDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
// response payload
if err := consumer.Consume(response.Body(), &o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
| NewDcimConsolePortsPartialUpdateOK |
backward.go | package manager
import (
"net"
)
const (
B_NEWBACKWARD = iota
B_GETSEQCHAN
B_ADDCONN
B_GETDATACHAN
B_GETDATACHAN_WITHOUTUUID
B_CLOSETCP
B_CLOSESINGLE
B_CLOSESINGLEALL
B_FORCESHUTDOWN
)
type backwardManager struct {
backwardSeqMap map[uint64]string
backwardMap map[string]*backward
BackwardMessChan chan interface{}
TaskChan chan *BackwardTask
ResultChan chan *backwardResult
SeqReady chan bool
}
type BackwardTask struct {
Mode int
Seq uint64
Listener net.Listener
RPort string
BackwardSocket net.Conn
}
type backwardResult struct {
OK bool
SeqChan chan uint64
DataChan chan []byte
}
type backward struct {
listener net.Listener
seqChan chan uint64
backwardStatusMap map[uint64]*backwardStatus
}
type backwardStatus struct {
dataChan chan []byte
conn net.Conn
}
func | () *backwardManager {
manager := new(backwardManager)
manager.backwardSeqMap = make(map[uint64]string)
manager.backwardMap = make(map[string]*backward)
manager.BackwardMessChan = make(chan interface{}, 5)
manager.ResultChan = make(chan *backwardResult)
manager.TaskChan = make(chan *BackwardTask)
manager.SeqReady = make(chan bool)
return manager
}
func (manager *backwardManager) run() {
for {
task := <-manager.TaskChan
switch task.Mode {
case B_NEWBACKWARD:
manager.newBackward(task)
case B_GETSEQCHAN:
manager.getSeqChan(task)
case B_ADDCONN:
manager.addConn(task)
case B_GETDATACHAN:
manager.getDataChan(task)
case B_GETDATACHAN_WITHOUTUUID:
manager.getDatachanWithoutUUID(task)
case B_CLOSETCP:
manager.closeTCP(task)
case B_CLOSESINGLE:
manager.closeSingle(task)
case B_CLOSESINGLEALL:
manager.closeSingleAll()
case B_FORCESHUTDOWN:
manager.forceShutdown()
}
}
}
func (manager *backwardManager) newBackward(task *BackwardTask) {
manager.backwardMap[task.RPort] = new(backward)
manager.backwardMap[task.RPort].listener = task.Listener
manager.backwardMap[task.RPort].backwardStatusMap = make(map[uint64]*backwardStatus)
manager.backwardMap[task.RPort].seqChan = make(chan uint64)
manager.ResultChan <- &backwardResult{OK: true}
}
func (manager *backwardManager) getSeqChan(task *BackwardTask) {
if _, ok := manager.backwardMap[task.RPort]; ok {
manager.ResultChan <- &backwardResult{
OK: true,
SeqChan: manager.backwardMap[task.RPort].seqChan,
}
} else {
manager.ResultChan <- &backwardResult{OK: false}
}
}
func (manager *backwardManager) addConn(task *BackwardTask) {
if _, ok := manager.backwardMap[task.RPort]; ok {
manager.backwardSeqMap[task.Seq] = task.RPort
manager.backwardMap[task.RPort].backwardStatusMap[task.Seq] = new(backwardStatus)
manager.backwardMap[task.RPort].backwardStatusMap[task.Seq].conn = task.BackwardSocket
manager.backwardMap[task.RPort].backwardStatusMap[task.Seq].dataChan = make(chan []byte, 5)
manager.ResultChan <- &backwardResult{OK: true}
} else {
manager.ResultChan <- &backwardResult{OK: false}
}
}
func (manager *backwardManager) getDataChan(task *BackwardTask) {
if _, ok := manager.backwardMap[task.RPort]; ok {
if _, ok := manager.backwardMap[task.RPort].backwardStatusMap[task.Seq]; ok {
manager.ResultChan <- &backwardResult{
OK: true,
DataChan: manager.backwardMap[task.RPort].backwardStatusMap[task.Seq].dataChan,
}
} else {
manager.ResultChan <- &backwardResult{OK: false}
}
} else {
manager.ResultChan <- &backwardResult{OK: false}
}
}
func (manager *backwardManager) getDatachanWithoutUUID(task *BackwardTask) {
if _, ok := manager.backwardSeqMap[task.Seq]; !ok {
manager.ResultChan <- &backwardResult{OK: false}
return
}
rPort := manager.backwardSeqMap[task.Seq]
if _, ok := manager.backwardMap[rPort]; ok {
manager.ResultChan <- &backwardResult{
OK: true,
DataChan: manager.backwardMap[rPort].backwardStatusMap[task.Seq].dataChan,
}
} else {
manager.ResultChan <- &backwardResult{OK: false}
}
}
func (manager *backwardManager) closeTCP(task *BackwardTask) {
if _, ok := manager.backwardSeqMap[task.Seq]; !ok {
return
}
rPort := manager.backwardSeqMap[task.Seq]
manager.backwardMap[rPort].backwardStatusMap[task.Seq].conn.Close()
close(manager.backwardMap[rPort].backwardStatusMap[task.Seq].dataChan)
delete(manager.backwardMap[rPort].backwardStatusMap, task.Seq)
}
func (manager *backwardManager) closeSingle(task *BackwardTask) {
manager.backwardMap[task.RPort].listener.Close()
close(manager.backwardMap[task.RPort].seqChan)
for seq, status := range manager.backwardMap[task.RPort].backwardStatusMap {
status.conn.Close()
close(status.dataChan)
delete(manager.backwardMap[task.RPort].backwardStatusMap, seq)
}
delete(manager.backwardMap, task.RPort)
for seq, rPort := range manager.backwardSeqMap {
if rPort == task.RPort {
delete(manager.backwardSeqMap, seq)
}
}
manager.ResultChan <- &backwardResult{OK: true}
}
func (manager *backwardManager) closeSingleAll() {
for rPort, bw := range manager.backwardMap {
bw.listener.Close()
close(bw.seqChan)
for seq, status := range bw.backwardStatusMap {
status.conn.Close()
close(status.dataChan)
delete(manager.backwardMap[rPort].backwardStatusMap, seq)
}
delete(manager.backwardMap, rPort)
}
for seq := range manager.backwardSeqMap {
delete(manager.backwardSeqMap, seq)
}
manager.ResultChan <- &backwardResult{OK: true}
}
func (manager *backwardManager) forceShutdown() {
manager.closeSingleAll()
}
| newBackwardManager |
data-types.test.ts | import { DuckDB, Connection } from "@addon";
import { RowResultFormat } from "@addon-types";
/**
* There are types in the source code that there is no documentation for and I'm not sure if they are used as return types:
* - VARBINARY
* - POINTER
* - HASH
* - STRUCT
* - LIST
* These are not supported (yet) by the bindings, not sure if they need to be
*/
describe("Data type mapping", () => {
let db: DuckDB;
let connection: Connection;
beforeEach(() => {
db = new DuckDB();
connection = new Connection(db);
});
afterEach(() => {
connection.close();
db.close();
});
it("supports TINYINT", async () => {
const result = await connection.executeIterator<number[]>(`SELECT CAST(1 AS TINYINT)`, {
rowResultFormat: RowResultFormat.Array,
});
expect(result.fetchRow()).toMatchObject([1]);
});
it("supports SMALLINT", async () => {
const result = await connection.executeIterator<number[]>(`SELECT CAST(1 AS SMALLINT)`, {
rowResultFormat: RowResultFormat.Array,
});
expect(result.fetchRow()).toMatchObject([1]);
});
it("supports INTEGER", async () => {
const result = await connection.executeIterator<number[]>(`SELECT CAST(1 AS INTEGER)`, {
rowResultFormat: RowResultFormat.Array,
});
expect(result.fetchRow()).toMatchObject([1]);
});
it("supports BIGINT", async () => {
const bigInt = 9223372036854775807n;
const result = await connection.executeIterator<Array<bigint>>(`SELECT CAST (${bigInt} AS BIGINT)`, {
rowResultFormat: RowResultFormat.Array,
});
const resultValue = result.fetchRow()[0];
expect(resultValue).toEqual(bigInt);
});
it("supports HUGEINT - positive max", async () => {
const hugeInt = 170141183460469231731687303715884105727n;
const result = await connection.executeIterator<Array<bigint>>(`SELECT CAST (${hugeInt} AS HUGEINT)`, {
rowResultFormat: RowResultFormat.Array,
});
const resultValue = result.fetchRow()[0];
expect(resultValue).toEqual(hugeInt);
});
it("supports HUGEINT - large negative", async () => {
const hugeInt = -4565365654654345325455654365n;
const result = await connection.executeIterator<Array<bigint>>(`SELECT CAST (${hugeInt} AS HUGEINT)`, {
rowResultFormat: RowResultFormat.Array,
});
const resultValue = result.fetchRow()[0];
expect(resultValue).toEqual(hugeInt);
});
it("supports HUGEINT - small positive number", async () => {
const hugeInt = 132142n;
const result = await connection.executeIterator<Array<bigint>>(`SELECT CAST (${hugeInt} AS HUGEINT)`, {
rowResultFormat: RowResultFormat.Array,
});
const resultValue = result.fetchRow()[0];
expect(resultValue).toEqual(hugeInt);
});
| const hugeInt = -1n;
const result = await connection.executeIterator<Array<bigint>>(`SELECT CAST (${hugeInt} AS HUGEINT)`, {
rowResultFormat: RowResultFormat.Array,
});
const resultValue = result.fetchRow()[0];
expect(resultValue).toEqual(hugeInt);
});
it("supports HUGEINT - large negative number", async () => {
const hugeInt = -354235423543264236543654n;
const result = await connection.executeIterator<Array<bigint>>(`SELECT CAST (${hugeInt} AS HUGEINT)`, {
rowResultFormat: RowResultFormat.Array,
});
const resultValue = result.fetchRow()[0];
expect(resultValue).toEqual(hugeInt);
});
it("supports HUGEINT - negative max", async () => {
const hugeInt = -170141183460469231731687303715884105727n;
const result = await connection.executeIterator<Array<bigint>>(`SELECT CAST (${hugeInt} AS HUGEINT)`, {
rowResultFormat: RowResultFormat.Array,
});
const resultValue = result.fetchRow()[0];
expect(resultValue).toEqual(hugeInt);
});
it("supports common types", async () => {
const result = await connection.executeIterator<any[]>(
`SELECT
null,
true,
0,
CAST(1 AS TINYINT),
CAST(8 AS SMALLINT),
10000,
1.1,
CAST(1.1 AS DOUBLE),
'stringy',
TIMESTAMP '1971-02-02 01:01:01.001',
DATE '1971-02-02'
`,
{ rowResultFormat: RowResultFormat.Array },
);
expect(result.fetchRow()).toMatchObject([
null,
true,
0,
1,
8,
10000,
1.1,
1.1,
"stringy",
Date.UTC(71, 1, 2, 1, 1, 1, 1),
Date.UTC(71, 1, 2),
]);
});
// Note: even though there is a CHAR type in the source code, it is simply an alias to VARCHAR
it("supports CHAR", async () => {
const result = await connection.executeIterator<string[]>(`SELECT CAST('a' AS CHAR)`, {
rowResultFormat: RowResultFormat.Array,
});
expect(result.fetchRow()).toMatchObject(["a"]);
});
it("supports TIME", async () => {
const result = await connection.executeIterator<number[]>(`SELECT TIME '01:01:01.001'`, {
rowResultFormat: RowResultFormat.Array,
});
expect(result.fetchRow()).toMatchObject([1 + 1000 + 60000 + 60000 * 60]);
});
it("supports BLOB", async () => {
const result = await connection.executeIterator<Buffer[]>(`SELECT 'AB'::BLOB;`, {
rowResultFormat: RowResultFormat.Array,
});
const resultBuffer = result.fetchRow()[0];
const view = new Int8Array(resultBuffer);
// ASCII "a"
expect(view[0]).toBe(65);
// ASCII "b"
expect(view[1]).toBe(66);
});
// TODO: either create a JS/TS object representing an interval or possibly convert to number
it("supports INTERVAL", async () => {
const result = await connection.executeIterator<string[]>(`SELECT INTERVAL '1' MONTH;`, {
rowResultFormat: RowResultFormat.Array,
});
expect(result.fetchRow()).toMatchObject(["1 month"]);
});
}); | it("supports HUGEINT - negative 1", async () => { |
main.rs | mod internal;
use internal::*;
use std::io::prelude::*;
use std::fs::File;
use std::env::{args};
fn main() -> std::io::Result<()> |
fn input_buffer(filename: String) -> std::io::Result<String> {
let mut f = File::open(filename)?;
let mut input_buf = String::new();
f.read_to_string(&mut input_buf)?;
Ok(input_buf)
}
| {
let filename_pt01 : String = args().skip(1).take(1).collect();
let pt_01_input_buffer = input_buffer(filename_pt01)?;
let filename_pt02 : String = args().skip(2).take(1).collect();
let pt_02_input_buffer = input_buffer(filename_pt02)?;
println!("answer (pt. 01): {}", day_01_pt_01(&pt_01_input_buffer));
println!("answer (pt. 01): {:?}", day_01_pt_02(&pt_02_input_buffer));
Ok(())
} |
templates.py | """
Classes and functions for templates.
"""
from __future__ import absolute_import, division, print_function
import sys
from glob import glob
import os
import traceback
import numpy as np
from astropy.io import fits
from .utils import native_endian, elapsed, transmission_Lyman
from .rebin import rebin_template, trapz_rebin
class Template(object):
"""A spectral Template PCA object.
The template data is read from a redrock-format template file.
Alternatively, the data can be specified in the constructor.
Args:
filename (str): the path to the template file, either absolute or
relative to the RR_TEMPLATE_DIR environment variable.
"""
def __init__(self, filename=None, spectype=None, redshifts=None,
wave=None, flux=None, subtype=None):
if filename is not None:
fx = None
if os.path.exists(filename):
fx = fits.open(filename, memmap=False)
else:
xfilename = os.path.join(os.getenv('RR_TEMPLATE_DIR'), filename)
if os.path.exists(xfilename):
fx = fits.open(xfilename, memmap=False)
else:
raise IOError('unable to find '+filename)
hdr = fx['BASIS_VECTORS'].header
if 'VERSION' in hdr:
self._version = hdr['VERSION']
else:
self._version = 'unknown'
self.wave = np.asarray(hdr['CRVAL1'] + \
hdr['CDELT1']*np.arange(hdr['NAXIS1']), dtype=np.float64)
if 'LOGLAM' in hdr and hdr['LOGLAM'] != 0:
self.wave = 10**self.wave
self.flux = np.asarray(native_endian(fx['BASIS_VECTORS'].data),
dtype=np.float64)
self._redshifts = None
## find out if redshift info is present in the file
old_style_templates = True
try:
self._redshifts = native_endian(fx['REDSHIFTS'].data)
old_style_templates = False
except KeyError:
pass
fx.close()
self._rrtype = hdr['RRTYPE'].strip().upper()
if old_style_templates:
if self._rrtype == 'GALAXY':
# redshifts = 10**np.arange(np.log10(1+0.005),
# np.log10(1+2.0), 1.5e-4) - 1
self._redshifts = 10**np.arange(np.log10(1-0.005),
np.log10(1+1.7), 3e-4) - 1
elif self._rrtype == 'STAR':
self._redshifts = np.arange(-0.002, 0.00201, 4e-5)
elif self._rrtype == 'QSO':
self._redshifts = 10**np.arange(np.log10(1+0.05),
np.log10(1+6.0), 5e-4) - 1
else:
raise ValueError("Unknown redshift range to use for "
"template type {}".format(self._rrtype))
zmin = self._redshifts[0]
zmax = self._redshifts[-1]
print("DEBUG: Using default redshift range {:.4f}-{:.4f} for "
"{}".format(zmin, zmax, os.path.basename(filename)))
else:
zmin = self._redshifts[0]
zmax = self._redshifts[-1]
print("DEBUG: Using redshift range {:.4f}-{:.4f} for "
"{}".format(zmin, zmax, os.path.basename(filename)))
self._subtype = None
if 'RRSUBTYP' in hdr:
self._subtype = hdr['RRSUBTYP'].strip().upper()
else:
self._subtype = ''
else:
self._rrtype = spectype
self._redshifts = redshifts
self.wave = wave
self.flux = flux
self._subtype = subtype
self._nbasis = self.flux.shape[0]
self._nwave = self.flux.shape[1]
@property
def nbasis(self):
return self._nbasis
@property
def nwave(self):
return self._nwave
@property
def template_type(self):
|
@property
def sub_type(self):
return self._subtype
@property
def full_type(self):
"""Return formatted type:subtype string.
"""
if self._subtype != '':
return '{}:::{}'.format(self._rrtype, self._subtype)
else:
return self._rrtype
@property
def redshifts(self):
return self._redshifts
def eval(self, coeff, wave, z):
"""Return template for given coefficients, wavelengths, and redshift
Args:
coeff : array of coefficients length self.nbasis
wave : wavelengths at which to evaluate template flux
z : redshift at which to evaluate template flux
Returns:
template flux array
Notes:
A single factor of (1+z)^-1 is applied to the resampled flux
to conserve integrated flux after redshifting.
"""
assert len(coeff) == self.nbasis
flux = self.flux.T.dot(coeff).T / (1+z)
return trapz_rebin(self.wave*(1+z), flux, wave)
def find_templates(template_dir=None):
"""Return list of redrock-\*.fits template files
Search directories in this order, returning results from first one found:
- template_dir
- $RR_TEMPLATE_DIR
- <redrock_code>/templates/
Args:
template_dir (str): optional directory containing the templates.
Returns:
list: a list of template files.
"""
if template_dir is None:
if 'RR_TEMPLATE_DIR' in os.environ:
template_dir = os.environ['RR_TEMPLATE_DIR']
else:
thisdir = os.path.dirname(__file__)
tempdir = os.path.join(os.path.abspath(thisdir), 'templates')
if os.path.exists(tempdir):
template_dir = tempdir
if template_dir is None:
raise IOError("ERROR: can't find template_dir, $RR_TEMPLATE_DIR, or {rrcode}/templates/")
else:
print('DEBUG: Read templates from {}'.format(template_dir) )
return sorted(glob(os.path.join(template_dir, 'rrtemplate-*.fits')))
class DistTemplatePiece(object):
"""One piece of the distributed template data.
This is a simple container for storing interpolated templates for a set of
redshift values. It is used for communicating the interpolated templates
between processes.
In the MPI case, each process will store at most two of these
simultaneously. This is the data that is computed on a single process and
passed between processes.
Args:
index (int): the chunk index of this piece- this corresponds to
the process rank that originally computed this piece.
redshifts (array): the redshift range contained in this piece.
data (list): a list of dictionaries, one for each redshift, and
each containing the 2D interpolated template values for all
"wavehash" keys.
"""
def __init__(self, index, redshifts, data):
self.index = index
self.redshifts = redshifts
self.data = data
def _mp_rebin_template(template, dwave, zlist, qout):
"""Function for multiprocessing version of rebinning.
"""
try:
results = dict()
for z in zlist:
binned = rebin_template(template, z, dwave)
results[z] = binned
qout.put(results)
except:
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
lines = [ "MP rebin: {}".format(x) for x in lines ]
print("".join(lines))
sys.stdout.flush()
return
class DistTemplate(object):
"""Distributed template data interpolated to all redshifts.
For a given template, the redshifts are distributed among the
processes in the communicator. Then each process will rebin the
template to those redshifts for the wavelength grids specified by
dwave.
Args:
template (Template): the template to distribute
dwave (dict): the keys are the "wavehash" and the values
are a 1D array containing the wavelength grid.
mp_procs (int): if not using MPI, restrict the number of
multiprocesses to this.
comm (mpi4py.MPI.Comm): (optional) the MPI communicator.
"""
def __init__(self, template, dwave, mp_procs=1, comm=None):
self._comm = comm
self._template = template
self._dwave = dwave
self._comm_rank = 0
self._comm_size = 1
if self._comm is not None:
self._comm_rank = self._comm.rank
self._comm_size = self._comm.size
self._distredshifts = np.array_split(self._template.redshifts,
self._comm_size)
myz = self._distredshifts[self._comm_rank]
nz = len(myz)
data = list()
# In the case of not using MPI (comm == None), one process is rebinning
# all the templates. In that scenario, use multiprocessing
# workers to do the rebinning.
if self._comm is not None:
# MPI case- compute our local redshifts
for z in myz:
binned = rebin_template(self._template, z, self._dwave)
data.append(binned)
else:
# We don't have MPI, so use multiprocessing
import multiprocessing as mp
qout = mp.Queue()
work = np.array_split(myz, mp_procs)
procs = list()
for i in range(mp_procs):
p = mp.Process(target=_mp_rebin_template,
args=(self._template, self._dwave, work[i], qout))
procs.append(p)
p.start()
# Extract the output into a single list
results = dict()
for i in range(mp_procs):
res = qout.get()
results.update(res)
for z in myz:
data.append(results[z])
# Correct spectra for Lyman-series
for i, z in enumerate(myz):
for k in list(self._dwave.keys()):
T = transmission_Lyman(z,self._dwave[k])
for vect in range(data[i][k].shape[1]):
data[i][k][:,vect] *= T
self._piece = DistTemplatePiece(self._comm_rank, myz, data)
@property
def comm(self):
return self._comm
@property
def template(self):
return self._template
@property
def local(self):
return self._piece
def cycle(self):
"""Pass our piece of data to the next process.
If we have returned to our original data, then return True, otherwise
return False.
Args:
Nothing
Returns (bool):
Whether we have finished (True) else False.
"""
# If we are not using MPI, this function is a no-op, so just return.
if self._comm is None:
return True
rank = self._comm_rank
nproc = self._comm_size
to_proc = rank + 1
if to_proc >= nproc:
to_proc = 0
from_proc = rank - 1
if from_proc < 0:
from_proc = nproc - 1
# Send our data and get a request handle for later checking.
req = self._comm.isend(self._piece, to_proc)
# Receive our data
incoming = self._comm.recv(source=from_proc)
# Wait for send to finishself._comm_rank = self._comm.rank
req.wait()
# Now replace our local piece with the new one
self._piece = incoming
# Are we done?
done = False
if self._piece.index == rank:
done = True
return done
def load_dist_templates(dwave, templates=None, comm=None, mp_procs=1):
"""Read and distribute templates from disk.
This reads one or more template files from disk and distributes them among
an MPI communicator. Each process will locally store interpolated data
for a redshift slice of each template. For a single redshift, the template
is interpolated to the wavelength grids specified by "dwave".
As an example, imagine 3 templates with independent redshift ranges. Also
imagine that the communicator has 2 processes. This function would return
a list of 3 DistTemplate objects. Within each of those objects, the 2
processes store the interpolated data for a subset of the redshift range:
DistTemplate #1: zmin1 <---- p0 ----> | <---- p1 ----> zmax1
DistTemplate #2: zmin2 <-- p0 --> | <-- p1 --> zmax2
DistTemplate #3: zmin3 <--- p0 ---> | <--- p1 ---> zmax3
Args:
dwave (dict): the dictionary of wavelength grids. Keys are the
"wavehash" and values are an array of wavelengths.
templates (str or None): if None, find all templates from the
redrock template directory. If a path to a file is specified,
load that single template. If a path to a directory is given,
load all templates in that directory.
comm (mpi4py.MPI.Comm): (optional) the MPI communicator.
mp_procs (int): if not using MPI, restrict the number of
multiprocesses to this.
Returns:
list: a list of DistTemplate objects.
"""
timer = elapsed(None, "", comm=comm)
template_files = None
if (comm is None) or (comm.rank == 0):
# Only one process needs to do this
if templates is not None:
if os.path.isfile(templates):
# we are using just a single file
template_files = [ templates ]
elif os.path.isdir(templates):
# this is a template dir
template_files = find_templates(template_dir=templates)
else:
print("{} is neither a file nor a directory"\
.format(templates))
sys.stdout.flush()
if comm is not None:
comm.Abort()
else:
template_files = find_templates()
if comm is not None:
template_files = comm.bcast(template_files, root=0)
template_data = list()
if (comm is None) or (comm.rank == 0):
for t in template_files:
template_data.append(Template(filename=t))
if comm is not None:
template_data = comm.bcast(template_data, root=0)
timer = elapsed(timer, "Read and broadcast of {} templates"\
.format(len(template_files)), comm=comm)
# Compute the interpolated templates in a distributed way with every
# process generating a slice of the redshift range.
dtemplates = list()
for t in template_data:
dtemplates.append(DistTemplate(t, dwave, mp_procs=mp_procs, comm=comm))
timer = elapsed(timer, "Rebinning templates", comm=comm)
return dtemplates
| return self._rrtype |
gregor.go | package service
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"net"
"net/url"
"sync"
"time"
"golang.org/x/net/context"
"github.com/keybase/backoff"
"github.com/keybase/client/go/badges"
"github.com/keybase/client/go/chat"
"github.com/keybase/client/go/chat/globals"
chatstorage "github.com/keybase/client/go/chat/storage"
"github.com/keybase/client/go/chat/utils"
"github.com/keybase/client/go/engine"
"github.com/keybase/client/go/gregor"
grclient "github.com/keybase/client/go/gregor/client"
"github.com/keybase/client/go/gregor/storage"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/logger"
"github.com/keybase/client/go/protocol/chat1"
"github.com/keybase/client/go/protocol/gregor1"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/clockwork"
"github.com/keybase/go-framed-msgpack-rpc/rpc"
jsonw "github.com/keybase/go-jsonw"
)
const GregorRequestTimeout time.Duration = 30 * time.Second
const GregorConnectionRetryInterval time.Duration = 2 * time.Second
const GregorGetClientTimeout time.Duration = 4 * time.Second
type IdentifyUIHandler struct {
libkb.Contextified
connID libkb.ConnectionID
alwaysAlive bool
}
var _ libkb.GregorInBandMessageHandler = (*IdentifyUIHandler)(nil)
func NewIdentifyUIHandler(g *libkb.GlobalContext, connID libkb.ConnectionID) IdentifyUIHandler {
return IdentifyUIHandler{
Contextified: libkb.NewContextified(g),
connID: connID,
alwaysAlive: false,
}
}
func (h IdentifyUIHandler) IsAlive() bool {
return (h.alwaysAlive || h.G().ConnectionManager.LookupConnection(h.connID) != nil)
}
func (h IdentifyUIHandler) Name() string {
return "IdentifyUIHandler"
}
func (h *IdentifyUIHandler) toggleAlwaysAlive(alive bool) {
h.alwaysAlive = alive
}
type gregorFirehoseHandler struct {
libkb.Contextified
connID libkb.ConnectionID
cli keybase1.GregorUIClient
}
func newGregorFirehoseHandler(g *libkb.GlobalContext, connID libkb.ConnectionID, xp rpc.Transporter) *gregorFirehoseHandler {
return &gregorFirehoseHandler{
Contextified: libkb.NewContextified(g),
connID: connID,
cli: keybase1.GregorUIClient{Cli: rpc.NewClient(xp, libkb.NewContextifiedErrorUnwrapper(g), nil)},
}
}
func (h *gregorFirehoseHandler) IsAlive() bool {
return h.G().ConnectionManager.LookupConnection(h.connID) != nil
}
func (h *gregorFirehoseHandler) PushState(s gregor1.State, r keybase1.PushReason) {
err := h.cli.PushState(context.Background(), keybase1.PushStateArg{State: s, Reason: r})
if err != nil {
h.G().Log.Error(fmt.Sprintf("Error in firehose push state: %s", err))
}
}
func (h *gregorFirehoseHandler) PushOutOfBandMessages(m []gregor1.OutOfBandMessage) {
err := h.cli.PushOutOfBandMessages(context.Background(), m)
if err != nil {
h.G().Log.Error(fmt.Sprintf("Error in firehose push out-of-band messages: %s", err))
}
}
type testingEvents struct {
broadcastSentCh chan error
}
func newTestingEvents() *testingEvents {
return &testingEvents{
broadcastSentCh: make(chan error),
}
}
type connectionAuthError struct {
msg string
shouldRetry bool
}
func newConnectionAuthError(msg string, shouldRetry bool) connectionAuthError {
return connectionAuthError{
msg: msg,
shouldRetry: shouldRetry,
}
}
func (c connectionAuthError) ShouldRetry() bool {
return c.shouldRetry
}
func (c connectionAuthError) Error() string {
return fmt.Sprintf("connection auth error: msg: %s shouldRetry: %v", c.msg, c.shouldRetry)
}
type gregorHandler struct {
globals.Contextified
// This lock is to protect ibmHandlers and gregorCli and firehoseHandlers. Only public methods
// should grab it.
sync.Mutex
ibmHandlers []libkb.GregorInBandMessageHandler
gregorCli *grclient.Client
firehoseHandlers []libkb.GregorFirehoseHandler
badger *badges.Badger
reachability *reachability
chatLog utils.DebugLabeler
// This mutex protects the con object
connMutex sync.Mutex
conn *rpc.Connection
uri *rpc.FMPURI
// connectHappened will be closed after gregor connection established
connectHappened chan struct{}
cli rpc.GenericClient
pingCli rpc.GenericClient
sessionID gregor1.SessionID
firstConnect bool
forceSessionCheck bool
// Function for determining if a new BroadcastMessage should trigger
// a pushState call to firehose handlers
pushStateFilter func(m gregor.Message) bool
shutdownCh chan struct{}
broadcastCh chan gregor1.Message
// Testing
testingEvents *testingEvents
transportForTesting *connTransport
}
var _ libkb.GregorDismisser = (*gregorHandler)(nil)
var _ libkb.GregorListener = (*gregorHandler)(nil)
type gregorLocalDb struct {
libkb.Contextified
}
func newLocalDB(g *libkb.GlobalContext) *gregorLocalDb {
return &gregorLocalDb{
Contextified: libkb.NewContextified(g),
}
}
func dbKey(u gregor.UID) libkb.DbKey {
return libkb.DbKey{Typ: libkb.DBGregor, Key: hex.EncodeToString(u.Bytes())}
}
func (db *gregorLocalDb) Store(u gregor.UID, b []byte) error {
return db.G().LocalDb.PutRaw(dbKey(u), b)
}
func (db *gregorLocalDb) Load(u gregor.UID) (res []byte, e error) {
res, _, err := db.G().LocalDb.GetRaw(dbKey(u))
return res, err
}
func newGregorHandler(g *globals.Context) *gregorHandler {
gh := &gregorHandler{
Contextified: globals.NewContextified(g),
chatLog: utils.NewDebugLabeler(g.GetLog(), "PushHandler", false),
firstConnect: true,
pushStateFilter: func(m gregor.Message) bool { return true },
badger: nil,
broadcastCh: make(chan gregor1.Message, 10000),
forceSessionCheck: false,
connectHappened: make(chan struct{}),
}
return gh
}
// Init starts all the background services for managing connection to Gregor
func (g *gregorHandler) Init() {
// Attempt to create a gregor client initially, if we are not logged in
// or don't have user/device info in G, then this won't work
if err := g.resetGregorClient(); err != nil {
g.Warning(context.Background(), "unable to create push service client: %s", err.Error())
}
// Start broadcast handler goroutine
go g.broadcastMessageHandler()
// Start the app state monitor thread
go g.monitorAppState()
}
func (g *gregorHandler) monitorAppState() {
// Wait for state updates and react accordingly
for {
state := <-g.G().AppState.NextUpdate()
switch state {
case keybase1.AppState_BACKGROUNDACTIVE:
fallthrough
case keybase1.AppState_FOREGROUND:
// Make sure the URI is set before attempting this (possible it isnt in a race)
if g.uri != nil {
g.chatLog.Debug(context.Background(), "foregrounded, reconnecting")
if err := g.Connect(g.uri); err != nil {
g.chatLog.Debug(context.Background(), "error reconnecting")
}
}
case keybase1.AppState_INACTIVE, keybase1.AppState_BACKGROUND:
g.chatLog.Debug(context.Background(), "backgrounded, shutting down connection")
g.Shutdown()
}
}
}
func (g *gregorHandler) GetURI() *rpc.FMPURI {
return g.uri
}
func (g *gregorHandler) GetIncomingClient() gregor1.IncomingInterface {
if g.IsShutdown() || g.cli == nil {
return gregor1.IncomingClient{Cli: chat.OfflineClient{}}
}
return gregor1.IncomingClient{Cli: g.cli}
}
func (g *gregorHandler) GetClient() chat1.RemoteInterface {
if g.IsShutdown() || g.cli == nil {
select {
case <-g.connectHappened:
if g.IsShutdown() || g.cli == nil {
g.chatLog.Debug(context.Background(), "GetClient: connectHappened, but still shutdown, using OfflineClient for chat1.RemoteClient")
return chat1.RemoteClient{Cli: chat.OfflineClient{}}
}
g.chatLog.Debug(context.Background(), "GetClient: successfully waited for connection")
return chat1.RemoteClient{Cli: chat.NewRemoteClient(g.G(), g.cli)}
case <-time.After(GregorGetClientTimeout):
g.chatLog.Debug(context.Background(), "GetClient: shutdown, using OfflineClient for chat1.RemoteClient (waited %s for connectHappened)", GregorGetClientTimeout)
return chat1.RemoteClient{Cli: chat.OfflineClient{}}
}
}
g.chatLog.Debug(context.Background(), "GetClient: not shutdown, making new remote client")
return chat1.RemoteClient{Cli: chat.NewRemoteClient(g.G(), g.cli)}
}
func (g *gregorHandler) resetGregorClient() (err error) {
defer g.G().Trace("gregorHandler#newGregorClient", func() error { return err })()
of := gregor1.ObjFactory{}
sm := storage.NewMemEngine(of, clockwork.NewRealClock())
ctx := context.Background()
var guid gregor.UID
var gdid gregor.DeviceID
var b []byte
uid := g.G().Env.GetUID()
if !uid.Exists() {
err = errors.New("no UID; probably not logged in")
return err
}
if b = uid.ToBytes(); b == nil {
err = errors.New("Can't convert UID to byte array")
return err
}
if guid, err = of.MakeUID(b); err != nil {
return err
}
did := g.G().Env.GetDeviceID()
if !did.Exists() {
err = errors.New("no device ID; probably not logged in")
return err
}
if b, err = hex.DecodeString(did.String()); err != nil {
return err
}
if gdid, err = of.MakeDeviceID(b); err != nil {
return err
}
// Create client object
gcli := grclient.NewClient(guid, gdid, sm, newLocalDB(g.G().ExternalG()),
g.G().Env.GetGregorSaveInterval(), g.G().Log)
// Bring up local state
g.Debug(ctx, "restoring state from leveldb")
if err = gcli.Restore(); err != nil {
// If this fails, we'll keep trying since the server can bail us out
g.Debug(ctx, "restore local state failed: %s", err)
}
g.gregorCli = gcli
return nil
}
func (g *gregorHandler) getGregorCli() (*grclient.Client, error) {
if g.gregorCli == nil {
return nil, errors.New("client unset")
}
return g.gregorCli, nil
}
func (g *gregorHandler) getRPCCli() rpc.GenericClient {
return g.cli
}
func (g *gregorHandler) Debug(ctx context.Context, s string, args ...interface{}) {
g.G().Log.CloneWithAddedDepth(1).CDebugf(ctx, "PushHandler: "+s, args...)
}
func (g *gregorHandler) Warning(ctx context.Context, s string, args ...interface{}) {
g.G().Log.CloneWithAddedDepth(1).CWarningf(ctx, "PushHandler: "+s, args...)
}
func (g *gregorHandler) Errorf(ctx context.Context, s string, args ...interface{}) {
g.G().Log.CloneWithAddedDepth(1).CErrorf(ctx, "PushHandler: "+s, args...)
}
func (g *gregorHandler) SetPushStateFilter(f func(m gregor.Message) bool) {
g.pushStateFilter = f
}
func (g *gregorHandler) setReachability(r *reachability) {
g.reachability = r
}
func (g *gregorHandler) Connect(uri *rpc.FMPURI) (err error) {
defer g.G().Trace("gregorHandler#Connect", func() error { return err })()
g.connMutex.Lock()
defer g.connMutex.Unlock()
defer func() {
close(g.connectHappened)
g.connectHappened = make(chan struct{})
}()
// Create client interface to gregord; the user needs to be logged in for this
// to work
if err = g.resetGregorClient(); err != nil {
return err
}
// In case we need to interrupt auth'ing or the ping loop,
// set up this channel.
g.shutdownCh = make(chan struct{})
g.uri = uri
if uri.UseTLS() {
err = g.connectTLS()
} else {
err = g.connectNoTLS()
}
return err
}
func (g *gregorHandler) HandlerName() string {
return "keybase service"
}
// PushHandler adds a new ibm handler to our list. This is usually triggered
// when an external entity (like Electron) connects to the service, and we can
// safely send Gregor information to it
func (g *gregorHandler) PushHandler(handler libkb.GregorInBandMessageHandler) {
g.Lock()
defer g.Unlock()
g.G().Log.Debug("pushing inband handler %s to position %d", handler.Name(), len(g.ibmHandlers))
g.ibmHandlers = append(g.ibmHandlers, handler)
// Only try replaying if we are logged in, it's possible that a handler can
// attach before that is true (like if we start the service logged out and
// Electron connects)
if g.IsConnected() {
if _, err := g.replayInBandMessages(context.TODO(), gregor1.IncomingClient{Cli: g.cli},
time.Time{}, handler); err != nil {
g.Errorf(context.Background(), "replayInBandMessages on PushHandler failed: %s", err)
}
if g.badger != nil {
s, err := g.getState(context.Background())
if err != nil {
g.Warning(context.Background(), "Cannot get state in PushHandler: %s", err)
return
}
g.badger.PushState(s)
}
}
}
// PushFirehoseHandler pushes a new firehose handler onto the list of currently
// active firehose handles. We can have several of these active at once. All
// get the "firehose" of gregor events. They're removed lazily as their underlying
// connections die.
func (g *gregorHandler) PushFirehoseHandler(handler libkb.GregorFirehoseHandler) {
g.Lock()
defer g.Unlock()
g.firehoseHandlers = append(g.firehoseHandlers, handler)
s, err := g.getState(context.Background())
if err != nil {
g.Warning(context.Background(), "Cannot push state in firehose handler: %s", err)
return
}
handler.PushState(s, keybase1.PushReason_RECONNECTED)
}
// iterateOverFirehoseHandlers applies the function f to all live fireshose handlers
// and then resets the list to only include the live ones.
func (g *gregorHandler) iterateOverFirehoseHandlers(f func(h libkb.GregorFirehoseHandler)) {
var freshHandlers []libkb.GregorFirehoseHandler
for _, h := range g.firehoseHandlers {
if h.IsAlive() {
f(h)
freshHandlers = append(freshHandlers, h)
}
}
g.firehoseHandlers = freshHandlers
return
}
func (g *gregorHandler) pushState(r keybase1.PushReason) {
s, err := g.getState(context.Background())
if err != nil {
g.Warning(context.Background(), "Cannot push state in firehose handler: %s", err)
return
}
g.iterateOverFirehoseHandlers(func(h libkb.GregorFirehoseHandler) { h.PushState(s, r) })
// Only send this state update on reception of new data, not a reconnect since we will
// be sending that on a different code path altogether (see OnConnect).
if g.badger != nil && r != keybase1.PushReason_RECONNECTED {
g.badger.PushState(s)
}
}
func (g *gregorHandler) pushOutOfBandMessages(m []gregor1.OutOfBandMessage) {
g.iterateOverFirehoseHandlers(func(h libkb.GregorFirehoseHandler) { h.PushOutOfBandMessages(m) })
}
// replayInBandMessages will replay all the messages in the current state from
// the given time. If a handler is specified, it will only replay using it,
// otherwise it will try all of them. gregorHandler needs to be locked when calling
// this function.
func (g *gregorHandler) replayInBandMessages(ctx context.Context, cli gregor1.IncomingInterface,
t time.Time, handler libkb.GregorInBandMessageHandler) ([]gregor.InBandMessage, error) {
var msgs []gregor.InBandMessage
var err error
gcli, err := g.getGregorCli()
if err != nil {
return nil, err
}
if t.IsZero() {
g.Debug(ctx, "replayInBandMessages: fresh replay: using state items")
state, err := gcli.StateMachineState(ctx, nil)
if err != nil {
g.Debug(ctx, "unable to fetch state for replay: %s", err)
return nil, err
}
if msgs, err = gcli.InBandMessagesFromState(state); err != nil {
g.Debug(ctx, "unable to fetch messages from state for replay: %s", err)
return nil, err
}
} else {
g.Debug(ctx, "replayInBandMessages: incremental replay: using ibms since")
if msgs, err = gcli.StateMachineInBandMessagesSince(ctx, t); err != nil {
g.Debug(ctx, "unable to fetch messages for replay: %s", err)
return nil, err
}
}
g.Debug(ctx, "replaying %d messages", len(msgs))
for _, msg := range msgs {
// If we have a handler, just run it on that, otherwise run it against
// all of the handlers we know about
if handler == nil {
err = g.handleInBandMessage(ctx, cli, msg)
} else {
_, err = g.handleInBandMessageWithHandler(ctx, cli, msg, handler)
}
// If an error happens when replaying, don't kill everything else that
// follows, just make a warning.
if err != nil {
g.Debug(ctx, "Failure in message replay: %s", err.Error())
err = nil
}
}
return msgs, nil
}
func (g *gregorHandler) IsShutdown() bool {
g.connMutex.Lock()
defer g.connMutex.Unlock()
return g.conn == nil
}
func (g *gregorHandler) IsConnected() bool {
g.connMutex.Lock()
defer g.connMutex.Unlock()
return g.conn != nil && g.conn.IsConnected()
}
// serverSync is called from
// gregord. This can happen either on initial startup, or after a reconnect. Needs
// to be called with gregorHandler locked.
func (g *gregorHandler) serverSync(ctx context.Context,
cli gregor1.IncomingInterface, gcli *grclient.Client, syncRes *chat1.SyncAllNotificationRes) ([]gregor.InBandMessage, []gregor.InBandMessage, error) {
// Get time of the last message we synced (unless this is our first time syncing)
var t time.Time
if !g.firstConnect {
pt := gcli.StateMachineLatestCTime(ctx)
if pt != nil {
t = *pt
}
g.Debug(ctx, "serverSync: starting replay from: %s", t)
} else {
g.Debug(ctx, "serverSync: performing a fresh replay")
}
// Sync down everything from the server
consumedMsgs, err := gcli.Sync(ctx, cli, syncRes)
if err != nil {
g.Debug(ctx, "serverSync: error syncing from the server, reason: %s", err)
return nil, nil, err
}
// Replay in-band messages
replayedMsgs, err := g.replayInBandMessages(ctx, cli, t, nil)
if err != nil {
g.Errorf(ctx, "serverSync: replay messages failed: %s", err)
return nil, nil, err
}
g.pushState(keybase1.PushReason_RECONNECTED)
return replayedMsgs, consumedMsgs, nil
}
func (g *gregorHandler) makeReconnectOobm() gregor1.Message {
return gregor1.Message{
Oobm_: &gregor1.OutOfBandMessage{
System_: "internal.reconnect",
},
}
}
func (g *gregorHandler) authParams(ctx context.Context) (uid gregor1.UID, token gregor1.SessionToken, err error) {
var res loggedInRes
var stoken string
var kuid keybase1.UID
if kuid, stoken, res = g.loggedIn(ctx); res != loggedInYes {
return uid, token,
newConnectionAuthError("failed to check logged in status", res == loggedInMaybe)
}
return kuid.ToBytes(), gregor1.SessionToken(stoken), nil
}
func (g *gregorHandler) inboxParams(ctx context.Context, uid gregor1.UID) chat1.InboxVers {
// Grab current on disk version
ibox := chatstorage.NewInbox(g.G(), uid)
vers, err := ibox.Version(ctx)
if err != nil {
g.chatLog.Debug(ctx, "inboxParams: failed to get current inbox version (using 0): %s",
err.Error())
vers = chat1.InboxVers(0)
}
return vers
}
func (g *gregorHandler) notificationParams(ctx context.Context, gcli *grclient.Client) (t gregor1.Time) {
pt := gcli.StateMachineLatestCTime(ctx)
if pt != nil {
t = gregor1.ToTime(*pt)
}
g.chatLog.Debug(ctx, "notificationParams: latest ctime: %s", t)
return t
}
// OnConnect is called by the rpc library to indicate we have connected to
// gregord
func (g *gregorHandler) OnConnect(ctx context.Context, conn *rpc.Connection,
cli rpc.GenericClient, srv *rpc.Server) error {
g.Lock()
defer g.Unlock()
// If we get a random OnConnect on some other connection that is not g.conn, then
// just reject it.
if conn != g.conn {
return chat.ErrDuplicateConnection
}
timeoutCli := WrapGenericClientWithTimeout(cli, GregorRequestTimeout, chat.ErrChatServerTimeout)
chatCli := chat1.RemoteClient{Cli: chat.NewRemoteClient(g.G(), cli)}
g.chatLog.Debug(ctx, "connected")
if err := srv.Register(gregor1.OutgoingProtocol(g)); err != nil {
return fmt.Errorf("error registering protocol: %s", err.Error())
}
// Grab authentication and sync params
gcli, err := g.getGregorCli()
if err != nil {
return fmt.Errorf("failed to get gregor client: %s", err.Error())
}
uid, token, err := g.authParams(ctx)
if err != nil {
return err
}
iboxVers := g.inboxParams(ctx, uid)
latestCtime := g.notificationParams(ctx, gcli)
// Run SyncAll to both authenticate, and grab all the data we will need to run the
// various resync procedures for chat and notifications
var identBreaks []keybase1.TLFIdentifyFailure
ctx = chat.Context(ctx, g.G(), keybase1.TLFIdentifyBehavior_CHAT_GUI, &identBreaks,
chat.NewIdentifyNotifier(g.G()))
syncAllRes, err := chatCli.SyncAll(ctx, chat1.SyncAllArg{
Uid: uid,
DeviceID: gcli.Device.(gregor1.DeviceID),
Session: token,
InboxVers: iboxVers,
Ctime: latestCtime,
Fresh: g.firstConnect,
ProtVers: chat1.SyncAllProtVers_V1,
HostName: g.GetURI().Host,
})
if err != nil {
// This will cause us to try and refresh session on the next attempt
if _, ok := err.(libkb.BadSessionError); ok {
g.chatLog.Debug(ctx, "bad session from SyncAll(): forcing session check on next attempt")
g.forceSessionCheck = true
}
return fmt.Errorf("error running SyncAll: %s", err.Error())
}
// Use the client parameter instead of conn.GetClient(), since we can get stuck
// in a recursive loop if we keep retrying on reconnect.
if err := g.auth(ctx, timeoutCli, &syncAllRes.Auth); err != nil {
return fmt.Errorf("error authenticating: %s", err.Error())
}
// Sync chat data using a Syncer object
if err := g.G().Syncer.Connected(ctx, chatCli, uid, &syncAllRes.Chat); err != nil {
return fmt.Errorf("error running chat sync: %s", err.Error())
}
// Sync down events since we have been dead
replayedMsgs, consumedMsgs, err := g.serverSync(ctx, gregor1.IncomingClient{Cli: timeoutCli}, gcli,
&syncAllRes.Notification)
if err != nil {
g.chatLog.Debug(ctx, "sync failure: %s", err.Error())
} else {
g.chatLog.Debug(ctx, "sync success: replayed: %d consumed: %d", len(replayedMsgs),
len(consumedMsgs))
}
// Sync badge state in the background
if g.badger != nil {
if err := g.badger.Resync(ctx, g.GetClient, gcli, &syncAllRes.Badge); err != nil {
g.chatLog.Debug(ctx, "badger failure: %s", err.Error())
}
}
// Call out to reachability module if we have one
if g.reachability != nil {
g.reachability.setReachability(keybase1.Reachability{
Reachable: keybase1.Reachable_YES,
})
}
// Broadcast reconnect oobm. Spawn this off into a goroutine so that we don't delay
// reconnection any longer than we have to.
go func(m gregor1.Message) {
g.BroadcastMessage(context.Background(), m)
}(g.makeReconnectOobm())
// No longer first connect if we are now connected
g.firstConnect = false
// On successful login we can reset this guy to not force a check
g.forceSessionCheck = false
return nil
}
func (g *gregorHandler) OnConnectError(err error, reconnectThrottleDuration time.Duration) {
g.chatLog.Debug(context.Background(), "connect error %s, reconnect throttle duration: %s", err, reconnectThrottleDuration)
// Check reachability here to see the nature of our offline status
go func() {
if g.reachability != nil && !g.isReachable() {
g.reachability.setReachability(keybase1.Reachability{
Reachable: keybase1.Reachable_NO,
})
}
}()
}
func (g *gregorHandler) OnDisconnected(ctx context.Context, status rpc.DisconnectStatus) {
g.chatLog.Debug(context.Background(), "disconnected: %v", status)
// Alert chat syncer that we are now disconnected
g.G().Syncer.Disconnected(ctx)
// Call out to reachability module if we have one (and we are currently connected)
go func() {
if g.reachability != nil && status != rpc.StartingFirstConnection && !g.isReachable() {
g.reachability.setReachability(keybase1.Reachability{
Reachable: keybase1.Reachable_NO,
})
}
}()
}
func (g *gregorHandler) OnDoCommandError(err error, nextTime time.Duration) {
g.chatLog.Debug(context.Background(), "do command error: %s, nextTime: %s", err, nextTime)
}
func (g *gregorHandler) ShouldRetry(name string, err error) bool {
g.chatLog.Debug(context.Background(), "should retry: name %s, err %v (returning false)", name, err)
return false
}
func (g *gregorHandler) ShouldRetryOnConnect(err error) bool {
if err == nil {
return false
}
ctx := context.Background()
g.chatLog.Debug(ctx, "should retry on connect, err %v", err)
if err == chat.ErrDuplicateConnection {
g.chatLog.Debug(ctx, "duplicate connection error, not retrying")
return false
}
if _, ok := err.(libkb.BadSessionError); ok {
g.chatLog.Debug(ctx, "bad session error, not retrying")
return false
}
if cerr, ok := err.(connectionAuthError); ok && !cerr.ShouldRetry() {
g.chatLog.Debug(ctx, "should retry on connect, non-retry error, ending: %s", err.Error())
return false
}
return true
}
func (g *gregorHandler) broadcastMessageOnce(ctx context.Context, m gregor1.Message) error {
g.Lock()
defer g.Unlock()
// Handle the message
var obm gregor.OutOfBandMessage
ibm := m.ToInBandMessage()
if ibm != nil {
gcli, err := g.getGregorCli()
if err != nil {
g.Debug(ctx, "BroadcastMessage: failed to get Gregor client: %s", err.Error())
return err
}
// Check to see if this is already in our state
msgID := ibm.Metadata().MsgID()
state, err := gcli.StateMachineState(ctx, nil)
if err != nil {
g.Debug(ctx, "BroadcastMessage: no state machine available: %s", err.Error())
return err
}
if _, ok := state.GetItem(msgID); ok {
g.Debug(ctx, "BroadcastMessage: msgID: %s already in state, ignoring", msgID)
return errors.New("ignored repeat message")
}
g.Debug(ctx, "broadcast: in-band message: msgID: %s Ctime: %s", msgID, ibm.Metadata().CTime())
err = g.handleInBandMessage(ctx, g.GetIncomingClient(), ibm)
// Send message to local state machine
gcli.StateMachineConsumeMessage(ctx, m)
// Forward to electron or whichever UI is listening for the new gregor state
if g.pushStateFilter(m) {
g.pushState(keybase1.PushReason_NEW_DATA)
}
return err
}
obm = m.ToOutOfBandMessage()
if obm != nil {
g.Debug(ctx, "broadcast: out-of-band message: uid: %s",
m.ToOutOfBandMessage().UID())
if err := g.handleOutOfBandMessage(ctx, obm); err != nil {
g.Debug(ctx, "BroadcastMessage: error handling oobm: %s", err.Error())
return err
}
return nil
}
g.Debug(ctx, "BroadcastMessage: both in-band and out-of-band message nil")
return errors.New("invalid message, no ibm or oobm")
}
func (g *gregorHandler) broadcastMessageHandler() {
ctx := context.Background()
for {
m := <-g.broadcastCh
err := g.broadcastMessageOnce(ctx, m)
if err != nil {
g.Debug(context.Background(), "broadcast error: %v", err)
}
// Testing alerts
if g.testingEvents != nil {
g.testingEvents.broadcastSentCh <- err
}
}
}
// BroadcastMessage is called when we receive a new messages from gregord. Grabs
// the lock protect the state machine and handleInBandMessage
func (g *gregorHandler) BroadcastMessage(ctx context.Context, m gregor1.Message) error {
// Send the message on a channel so we can return to Gregor as fast as possible. Note
// that this can block, but broadcastCh has a large buffer to try and mitigate
g.broadcastCh <- m
return nil
}
// handleInBandMessage runs a message on all the alive handlers. gregorHandler
// must be locked when calling this function.
func (g *gregorHandler) handleInBandMessage(ctx context.Context, cli gregor1.IncomingInterface,
ibm gregor.InBandMessage) (err error) {
defer g.G().Trace(fmt.Sprintf("gregorHandler#handleInBandMessage with %d handlers", len(g.ibmHandlers)), func() error { return err })()
ctx = libkb.WithLogTag(ctx, "GRGIBM")
var freshHandlers []libkb.GregorInBandMessageHandler
// Loop over all handlers and run the messages against any that are alive
// If the handler is not alive, we prune it from our list
for i, handler := range g.ibmHandlers {
g.Debug(ctx, "trying handler %s at position %d", handler.Name(), i)
if handler.IsAlive() {
if handled, err := g.handleInBandMessageWithHandler(ctx, cli, ibm, handler); err != nil {
if handled {
// Don't stop handling errors on a first failure.
g.Errorf(ctx, "failed to run %s handler: %s", handler.Name(), err)
} else {
g.Debug(ctx, "handleInBandMessage() failed to run %s handler: %s", handler.Name(), err)
}
}
freshHandlers = append(freshHandlers, handler)
} else {
g.Debug(ctx, "skipping handler as it's marked dead: %s", handler.Name())
}
}
if len(g.ibmHandlers) != len(freshHandlers) {
g.Debug(ctx, "Change # of live handlers from %d to %d", len(g.ibmHandlers), len(freshHandlers))
g.ibmHandlers = freshHandlers
}
return nil
}
// handleInBandMessageWithHandler runs a message against the specified handler
func (g *gregorHandler) handleInBandMessageWithHandler(ctx context.Context, cli gregor1.IncomingInterface,
ibm gregor.InBandMessage, handler libkb.GregorInBandMessageHandler) (bool, error) {
g.Debug(ctx, "handleInBand: %+v", ibm)
gcli, err := g.getGregorCli()
if err != nil {
return false, err
}
state, err := gcli.StateMachineState(ctx, nil)
if err != nil {
return false, err
}
sync := ibm.ToStateSyncMessage()
if sync != nil {
g.Debug(ctx, "state sync message")
return false, nil
}
update := ibm.ToStateUpdateMessage()
if update != nil {
g.Debug(ctx, "state update message")
item := update.Creation()
if item != nil {
id := item.Metadata().MsgID().String()
g.Debug(ctx, "msg ID %s created ctime: %s", id,
item.Metadata().CTime())
category := ""
if item.Category() != nil {
category = item.Category().String()
g.Debug(ctx, "item %s has category %s", id, category)
}
if handled, err := handler.Create(ctx, cli, category, item); err != nil {
return handled, err
}
}
dismissal := update.Dismissal()
if dismissal != nil {
g.Debug(ctx, "received dismissal")
for _, id := range dismissal.MsgIDsToDismiss() {
item, present := state.GetItem(id)
if !present {
g.Debug(ctx, "tried to dismiss item %s, not present", id.String())
continue
}
g.Debug(ctx, "dismissing item %s", id.String())
category := ""
if item.Category() != nil {
category = item.Category().String()
g.Debug(ctx, "dismissal %s has category %s", id, category)
}
if handled, err := handler.Dismiss(ctx, cli, category, item); handled && err != nil {
return handled, err
}
}
if len(dismissal.RangesToDismiss()) > 0 {
g.Debug(ctx, "message range dismissing not implemented")
}
}
return true, nil
}
return false, nil
}
func (h IdentifyUIHandler) Create(ctx context.Context, cli gregor1.IncomingInterface, category string,
item gregor.Item) (bool, error) {
switch category {
case "show_tracker_popup":
return true, h.handleShowTrackerPopupCreate(ctx, cli, item)
}
return false, nil
}
func (h IdentifyUIHandler) Dismiss(ctx context.Context, cli gregor1.IncomingInterface, category string,
item gregor.Item) (bool, error) {
switch category {
case "show_tracker_popup":
return true, h.handleShowTrackerPopupDismiss(ctx, cli, item)
}
return false, nil
}
func (h IdentifyUIHandler) handleShowTrackerPopupCreate(ctx context.Context, cli gregor1.IncomingInterface,
item gregor.Item) error {
h.G().Log.Debug("handleShowTrackerPopupCreate: %+v", item)
if item.Body() == nil {
return errors.New("gregor handler for show_tracker_popup: nil message body")
}
body, err := jsonw.Unmarshal(item.Body().Bytes())
if err != nil {
h.G().Log.Debug("body failed to unmarshal", err)
return err
}
uidString, err := body.AtPath("uid").GetString()
if err != nil {
h.G().Log.Debug("failed to extract uid", err)
return err
}
uid, err := keybase1.UIDFromString(uidString)
if err != nil {
h.G().Log.Debug("failed to convert UID from string", err)
return err
}
identifyUI, err := h.G().UIRouter.GetIdentifyUI()
if err != nil {
h.G().Log.Debug("failed to get IdentifyUI", err)
return err
}
if identifyUI == nil {
h.G().Log.Debug("got nil IdentifyUI")
return errors.New("got nil IdentifyUI")
}
secretUI, err := h.G().UIRouter.GetSecretUI(0)
if err != nil {
h.G().Log.Debug("failed to get SecretUI", err)
return err
}
if secretUI == nil {
h.G().Log.Debug("got nil SecretUI")
return errors.New("got nil SecretUI")
}
engineContext := engine.Context{
IdentifyUI: identifyUI,
SecretUI: secretUI,
}
identifyReason := keybase1.IdentifyReason{
Type: keybase1.IdentifyReasonType_TRACK,
// TODO: text here?
}
identifyArg := keybase1.Identify2Arg{Uid: uid, Reason: identifyReason}
identifyEng := engine.NewIdentify2WithUID(h.G(), &identifyArg)
identifyEng.SetResponsibleGregorItem(item)
return identifyEng.Run(&engineContext)
}
func (h IdentifyUIHandler) handleShowTrackerPopupDismiss(ctx context.Context, cli gregor1.IncomingInterface,
item gregor.Item) error {
h.G().Log.Debug("handleShowTrackerPopupDismiss: %+v", item)
if item.Body() == nil {
return errors.New("gregor dismissal for show_tracker_popup: nil message body")
}
body, err := jsonw.Unmarshal(item.Body().Bytes())
if err != nil {
h.G().Log.Debug("body failed to unmarshal", err)
return err
}
uidString, err := body.AtPath("uid").GetString()
if err != nil {
h.G().Log.Debug("failed to extract uid", err)
return err
}
uid, err := keybase1.UIDFromString(uidString)
if err != nil {
h.G().Log.Debug("failed to convert UID from string", err)
return err
}
user, err := libkb.LoadUser(libkb.NewLoadUserByUIDArg(ctx, h.G(), uid))
if err != nil {
h.G().Log.Debug("failed to load user from UID", err)
return err
}
identifyUI, err := h.G().UIRouter.GetIdentifyUI()
if err != nil {
h.G().Log.Debug("failed to get IdentifyUI", err)
return err
}
if identifyUI == nil {
h.G().Log.Debug("got nil IdentifyUI")
return errors.New("got nil IdentifyUI")
}
reason := keybase1.DismissReason{
Type: keybase1.DismissReasonType_HANDLED_ELSEWHERE,
}
identifyUI.Dismiss(user.GetName(), reason)
return nil
}
func (g *gregorHandler) handleOutOfBandMessage(ctx context.Context, obm gregor.OutOfBandMessage) error {
if obm.System() == nil {
return errors.New("nil system in out of band message")
}
if tmp, ok := obm.(gregor1.OutOfBandMessage); ok {
g.pushOutOfBandMessages([]gregor1.OutOfBandMessage{tmp})
} else {
g.G().Log.Warning("Got non-exportable out-of-band message")
}
// Send the oobm to that chat system so that it can potentially handle it
if g.G().PushHandler != nil {
handled, err := g.G().PushHandler.HandleOobm(ctx, obm)
if err != nil {
return err
}
if handled {
return nil
}
}
switch obm.System().String() {
case "kbfs.favorites":
return g.kbfsFavorites(ctx, obm)
case "internal.reconnect":
g.G().Log.Debug("reconnected to push server")
return nil
default:
return fmt.Errorf("unhandled system: %s", obm.System())
}
}
func (g *gregorHandler) Shutdown() {
g.Debug(context.Background(), "shutdown")
g.connMutex.Lock()
defer g.connMutex.Unlock()
if g.conn == nil {
return
}
// Alert chat syncer that we are now disconnected
g.G().Syncer.Disconnected(context.Background())
close(g.shutdownCh)
g.conn.Shutdown()
g.conn = nil
g.cli = nil
}
func (g *gregorHandler) Reset() error {
g.Shutdown()
return g.resetGregorClient()
}
func (g *gregorHandler) kbfsFavorites(ctx context.Context, m gregor.OutOfBandMessage) error {
if m.Body() == nil {
return errors.New("gregor handler for kbfs.favorites: nil message body")
}
body, err := jsonw.Unmarshal(m.Body().Bytes())
if err != nil {
return err
}
action, err := body.AtPath("action").GetString()
if err != nil {
return err
}
switch action {
case "create", "delete":
return g.notifyFavoritesChanged(ctx, m.UID())
default:
return fmt.Errorf("unhandled kbfs.favorites action %q", action)
}
}
func (g *gregorHandler) notifyFavoritesChanged(ctx context.Context, uid gregor.UID) error {
kbUID, err := keybase1.UIDFromString(hex.EncodeToString(uid.Bytes()))
if err != nil {
return err
}
g.G().NotifyRouter.HandleFavoritesChanged(kbUID)
return nil
}
type loggedInRes int
const (
loggedInYes loggedInRes = iota
loggedInNo
loggedInMaybe
)
func (g *gregorHandler) loggedIn(ctx context.Context) (uid keybase1.UID, token string, res loggedInRes) {
// Check to see if we have been shutdown,
select {
case <-g.shutdownCh:
return uid, token, loggedInMaybe
default:
// if we were going to block, then that means we are still alive
}
// Continue on and authenticate
g.G().Log.Debug("gregorHandler forceSessionCheck: %v", g.forceSessionCheck)
status, err := g.G().LoginState().APIServerSession(g.forceSessionCheck)
if err != nil {
switch err.(type) {
case libkb.LoginRequiredError:
return uid, token, loggedInNo
case libkb.NoSessionError:
return uid, token, loggedInNo
default:
g.G().Log.Debug("gregorHandler APIServerSessionStatus error (%T): %s", err, err)
}
g.G().Log.Debug("gregorHandler APIServerSessionStatus error: %s (returning loggedInMaybe)", err)
return uid, token, loggedInMaybe
}
if status == nil {
return uid, token, loggedInNo
}
return status.UID, status.SessionToken, loggedInYes
}
func (g *gregorHandler) auth(ctx context.Context, cli rpc.GenericClient, auth *gregor1.AuthResult) (err error) {
var token string
var res loggedInRes
var uid keybase1.UID
if uid, token, res = g.loggedIn(ctx); res != loggedInYes {
return newConnectionAuthError("not logged in for auth", res == loggedInMaybe)
}
if auth == nil {
g.chatLog.Debug(ctx, "logged in: authenticating")
ac := gregor1.AuthClient{Cli: cli}
auth = new(gregor1.AuthResult)
*auth, err = ac.AuthenticateSessionToken(ctx, gregor1.SessionToken(token))
if err != nil {
g.chatLog.Debug(ctx, "auth error: %s", err)
g.forceSessionCheck = true
return err
}
} else {
g.Debug(ctx, "using previously obtained auth result")
}
g.chatLog.Debug(ctx, "auth result: %+v", *auth)
if !bytes.Equal(auth.Uid, uid.ToBytes()) {
msg := fmt.Sprintf("auth result uid %x doesn't match session uid %q", auth.Uid, uid)
return newConnectionAuthError(msg, false)
}
g.sessionID = auth.Sid
return nil
}
func (g *gregorHandler) isReachable() bool {
ctx := context.Background()
timeout := g.G().Env.GetGregorPingTimeout()
url, err := url.Parse(g.G().Env.GetGregorURI())
if err != nil {
g.chatLog.Debug(ctx, "isReachable: failed to parse server uri, exiting: %s", err.Error())
return false
}
// If we currently think we are online, then make sure
conn, err := net.DialTimeout("tcp", url.Host, timeout)
if conn != nil {
conn.Close()
return true
}
if err != nil {
g.chatLog.Debug(ctx, "isReachable: error: terminating connection: %s", err.Error())
if _, err := g.Reconnect(ctx); err != nil {
g.chatLog.Debug(ctx, "isReachable: error reconnecting: %s", err.Error())
}
return false
}
return true
}
func (g *gregorHandler) Reconnect(ctx context.Context) (didShutdown bool, err error) {
if g.IsConnected() {
didShutdown = true
g.chatLog.Debug(ctx, "Reconnect: reconnecting to server")
g.Shutdown()
return didShutdown, g.Connect(g.uri)
}
didShutdown = false
g.chatLog.Debug(ctx, "Reconnect: skipping reconnect, already disconnected")
return didShutdown, nil
}
func (g *gregorHandler) pingLoop() {
ctx := context.Background()
id, _ := libkb.RandBytes(4)
duration := g.G().Env.GetGregorPingInterval()
timeout := g.G().Env.GetGregorPingTimeout()
url, err := url.Parse(g.G().Env.GetGregorURI())
if err != nil {
g.chatLog.Debug(ctx, "ping loop: failed to parse server uri, exiting: %s", err.Error())
return
}
g.chatLog.Debug(ctx, "ping loop: starting up: id: %x duration: %v timeout: %v url: %s",
id, duration, timeout, url.Host)
defer g.chatLog.Debug(ctx, "ping loop: id: %x terminating", id)
for {
ctx, shutdownCancel := context.WithCancel(context.Background())
select {
case <-g.G().Clock().After(duration):
var err error
doneCh := make(chan error)
go func(ctx context.Context) {
if g.IsConnected() {
// If we are connected, subject the ping call to a fairly
// aggressive timeout so our chat stuff can be responsive
// to changes in connectivity
var timeoutCancel context.CancelFunc
var timeoutCtx context.Context
timeoutCtx, timeoutCancel = context.WithTimeout(ctx, timeout)
_, err = gregor1.IncomingClient{Cli: g.pingCli}.Ping(timeoutCtx)
timeoutCancel()
} else {
// If we are not connected, we don't want to timeout anything
// Just hook into the normal reconnect chan stuff in the RPC
// library
g.chatLog.Debug(ctx, "ping loop: id: %x normal ping, not connected", id)
_, err = gregor1.IncomingClient{Cli: g.pingCli}.Ping(ctx)
}
select {
case <-ctx.Done():
g.chatLog.Debug(ctx, "ping loop: id: %x context cancelled, so not sending err", id)
default:
doneCh <- err
}
}(ctx)
select {
case err = <-doneCh:
case <-g.shutdownCh:
g.chatLog.Debug(ctx, "ping loop: id: %x shutdown received", id)
shutdownCancel()
return
}
if err != nil {
g.Debug(ctx, "ping loop: id: %x error: %s", id, err.Error())
if err == context.DeadlineExceeded {
g.chatLog.Debug(ctx, "ping loop: timeout: terminating connection")
var didShutdown bool
var err error
if didShutdown, err = g.Reconnect(ctx); err != nil {
g.chatLog.Debug(ctx, "ping loop: id: %x error reconnecting: %s", id,
err.Error())
}
// It is possible that we have already reconnected by the time we call Reconnect
// above. If that is the case, we don't want to terminate the ping loop. Only
// if Reconnect has actually reset the connection do we stop this ping loop.
if didShutdown {
shutdownCancel()
return
}
}
}
case <-g.shutdownCh:
g.chatLog.Debug(ctx, "ping loop: id: %x shutdown received", id)
shutdownCancel()
return
}
shutdownCancel()
}
}
// connMutex must be locked before calling this
func (g *gregorHandler) connectTLS() error {
ctx := context.Background()
if g.conn != nil {
g.chatLog.Debug(ctx, "skipping connect, conn is not nil")
return nil
}
uri := g.uri
g.chatLog.Debug(ctx, "connecting to gregord via TLS at %s", uri)
rawCA := g.G().Env.GetBundledCA(uri.Host)
if len(rawCA) == 0 {
return fmt.Errorf("No bundled CA for %s", uri.Host)
}
g.chatLog.Debug(ctx, "Using CA for gregor: %s", libkb.ShortCA(rawCA))
// Let people know we are trying to sync
g.G().NotifyRouter.HandleChatInboxSyncStarted(ctx, g.G().Env.GetUID())
constBackoff := backoff.NewConstantBackOff(GregorConnectionRetryInterval)
opts := rpc.ConnectionOpts{
TagsFunc: logger.LogTagsFromContextRPC,
WrapErrorFunc: libkb.MakeWrapError(g.G().ExternalG()), | []byte(rawCA), libkb.NewContextifiedErrorUnwrapper(g.G().ExternalG()), g, libkb.NewRPCLogFactory(g.G().ExternalG()), g.G().Log, opts)
// The client we get here will reconnect to gregord on disconnect if necessary.
// We should grab it here instead of in OnConnect, since the connection is not
// fully established in OnConnect. Anything that wants to make calls outside
// of OnConnect should use g.cli, everything else should the client that is
// a paramater to OnConnect
g.cli = WrapGenericClientWithTimeout(g.conn.GetClient(), GregorRequestTimeout,
chat.ErrChatServerTimeout)
g.pingCli = g.conn.GetClient() // Don't want this to have a timeout from here
// Start up ping loop to keep the connection to gregord alive, and to kick
// off the reconnect logic in the RPC library
go g.pingLoop()
return nil
}
// connMutex must be locked before calling this
func (g *gregorHandler) connectNoTLS() error {
ctx := context.Background()
if g.conn != nil {
g.chatLog.Debug(ctx, "skipping connect, conn is not nil")
return nil
}
uri := g.uri
g.chatLog.Debug(ctx, "connecting to gregord without TLS at %s", uri)
t := newConnTransport(g.G().ExternalG(), uri.HostPort)
g.transportForTesting = t
constBackoff := backoff.NewConstantBackOff(GregorConnectionRetryInterval)
opts := rpc.ConnectionOpts{
TagsFunc: logger.LogTagsFromContextRPC,
WrapErrorFunc: libkb.MakeWrapError(g.G().ExternalG()),
ReconnectBackoff: func() backoff.BackOff { return constBackoff },
}
g.conn = rpc.NewConnectionWithTransport(g, t, libkb.NewContextifiedErrorUnwrapper(g.G().ExternalG()), g.G().Log, opts)
g.cli = WrapGenericClientWithTimeout(g.conn.GetClient(), GregorRequestTimeout,
chat.ErrChatServerTimeout)
g.pingCli = g.conn.GetClient()
// Start up ping loop to keep the connection to gregord alive, and to kick
// off the reconnect logic in the RPC library
go g.pingLoop()
return nil
}
func NewGregorMsgID() (gregor1.MsgID, error) {
r, err := libkb.RandBytes(16) // TODO: Create a shared function for this.
if err != nil {
return nil, err
}
return gregor1.MsgID(r), nil
}
func (g *gregorHandler) templateMessage() (*gregor1.Message, error) {
uid := g.G().Env.GetUID()
if uid.IsNil() {
return nil, fmt.Errorf("Can't create new gregor items without a current UID.")
}
gregorUID := gregor1.UID(uid.ToBytes())
newMsgID, err := NewGregorMsgID()
if err != nil {
return nil, err
}
return &gregor1.Message{
Ibm_: &gregor1.InBandMessage{
StateUpdate_: &gregor1.StateUpdateMessage{
Md_: gregor1.Metadata{
Uid_: gregorUID,
MsgID_: newMsgID,
},
},
},
}, nil
}
// `cli` is the interface used to talk to gregor.
// If nil then the global cli will be used.
// Be sure to pass a cli when called from within OnConnect, as the global cli would deadlock.
func (g *gregorHandler) DismissItem(ctx context.Context, cli gregor1.IncomingInterface, id gregor.MsgID) error {
if id == nil {
return nil
}
var err error
defer g.G().Trace(fmt.Sprintf("gregorHandler.dismissItem(%s)", id.String()),
func() error { return err },
)()
dismissal, err := g.templateMessage()
if err != nil {
return err
}
dismissal.Ibm_.StateUpdate_.Dismissal_ = &gregor1.Dismissal{
MsgIDs_: []gregor1.MsgID{gregor1.MsgID(id.Bytes())},
}
if cli == nil {
cli = gregor1.IncomingClient{Cli: g.cli}
}
err = cli.ConsumeMessage(ctx, *dismissal)
return err
}
func (g *gregorHandler) DismissCategory(ctx context.Context, category gregor1.Category) error {
var err error
defer g.G().Trace(fmt.Sprintf("gregorHandler.DismissCategory(%s)", category.String()),
func() error { return err },
)()
dismissal, err := g.templateMessage()
if err != nil {
return err
}
dismissal.Ibm_.StateUpdate_.Dismissal_ = &gregor1.Dismissal{
Ranges_: []gregor1.MsgRange{
gregor1.MsgRange{
Category_: category,
// A small non-zero offset that effectively means "now",
// because an actually-zero offset would be interpreted as "not
// an offset at all" by the SQL query builder.
EndTime_: gregor1.TimeOrOffset{
Offset_: gregor1.DurationMsec(1),
},
}},
}
incomingClient := gregor1.IncomingClient{Cli: g.cli}
err = incomingClient.ConsumeMessage(ctx, *dismissal)
return err
}
func (g *gregorHandler) InjectItem(ctx context.Context, cat string, body []byte, dtime gregor1.TimeOrOffset) (gregor1.MsgID, error) {
var err error
defer g.G().CTrace(ctx, fmt.Sprintf("gregorHandler.InjectItem(%s)", cat),
func() error { return err },
)()
creation, err := g.templateMessage()
if err != nil {
return nil, err
}
creation.Ibm_.StateUpdate_.Creation_ = &gregor1.Item{
Category_: gregor1.Category(cat),
Body_: gregor1.Body(body),
Dtime_: dtime,
}
incomingClient := gregor1.IncomingClient{Cli: g.cli}
err = incomingClient.ConsumeMessage(ctx, *creation)
return creation.Ibm_.StateUpdate_.Md_.MsgID_, err
}
func (g *gregorHandler) InjectOutOfBandMessage(system string, body []byte) error {
var err error
defer g.G().Trace(fmt.Sprintf("gregorHandler.InjectOutOfBandMessage(%s)", system),
func() error { return err },
)()
uid := g.G().Env.GetUID()
if uid.IsNil() {
err = fmt.Errorf("Can't create new gregor items without a current UID.")
return err
}
gregorUID := gregor1.UID(uid.ToBytes())
msg := gregor1.Message{
Oobm_: &gregor1.OutOfBandMessage{
Uid_: gregorUID,
System_: gregor1.System(system),
Body_: gregor1.Body(body),
},
}
incomingClient := gregor1.IncomingClient{Cli: g.cli}
// TODO: Should the interface take a context from the caller?
err = incomingClient.ConsumeMessage(context.TODO(), msg)
return err
}
func (g *gregorHandler) simulateCrashForTesting() {
g.transportForTesting.Reset()
gregor1.IncomingClient{Cli: g.cli}.Ping(context.Background())
}
type gregorRPCHandler struct {
libkb.Contextified
xp rpc.Transporter
gh *gregorHandler
}
func newGregorRPCHandler(xp rpc.Transporter, g *libkb.GlobalContext, gh *gregorHandler) *gregorRPCHandler {
return &gregorRPCHandler{
Contextified: libkb.NewContextified(g),
xp: xp,
gh: gh,
}
}
func (g *gregorHandler) getState(ctx context.Context) (res gregor1.State, err error) {
var s gregor.State
if g == nil || g.gregorCli == nil {
return res, errors.New("gregor service not available (are you in standalone?)")
}
s, err = g.gregorCli.StateMachineState(ctx, nil)
if err != nil {
return res, err
}
ps, err := s.Export()
if err != nil {
return res, err
}
var ok bool
if res, ok = ps.(gregor1.State); !ok {
return res, errors.New("failed to convert state to exportable format")
}
return res, nil
}
func (g *gregorRPCHandler) GetState(ctx context.Context) (res gregor1.State, err error) {
return g.gh.getState(ctx)
}
func (g *gregorRPCHandler) InjectItem(ctx context.Context, arg keybase1.InjectItemArg) (gregor1.MsgID, error) {
return g.gh.InjectItem(ctx, arg.Cat, []byte(arg.Body), arg.Dtime)
}
func (g *gregorRPCHandler) DismissCategory(ctx context.Context, category gregor1.Category) error {
return g.gh.DismissCategory(ctx, category)
}
func (g *gregorRPCHandler) DismissItem(ctx context.Context, id gregor1.MsgID) error {
return g.gh.DismissItem(ctx, nil, id)
}
func WrapGenericClientWithTimeout(client rpc.GenericClient, timeout time.Duration, timeoutErr error) rpc.GenericClient {
return &timeoutClient{client, timeout, timeoutErr}
}
type timeoutClient struct {
inner rpc.GenericClient
timeout time.Duration
timeoutErr error
}
var _ rpc.GenericClient = (*timeoutClient)(nil)
func (t *timeoutClient) Call(ctx context.Context, method string, arg interface{}, res interface{}) error {
var timeoutCancel context.CancelFunc
ctx, timeoutCancel = context.WithTimeout(ctx, t.timeout)
defer timeoutCancel()
err := t.inner.Call(ctx, method, arg, res)
if err == context.DeadlineExceeded {
return t.timeoutErr
}
return err
}
func (t *timeoutClient) Notify(ctx context.Context, method string, arg interface{}) error {
var timeoutCancel context.CancelFunc
ctx, timeoutCancel = context.WithTimeout(ctx, t.timeout)
defer timeoutCancel()
err := t.inner.Notify(ctx, method, arg)
if err == context.DeadlineExceeded {
return t.timeoutErr
}
return err
} | ReconnectBackoff: func() backoff.BackOff { return constBackoff },
}
g.conn = rpc.NewTLSConnection(rpc.NewFixedRemote(uri.HostPort), |
debugger.py | # -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
Contains the text debugger manager.
"""
import os.path as osp
from qtpy.QtWidgets import QInputDialog, QLineEdit
from spyder.config.main import CONF
from spyder.config.base import _
from spyder.py3compat import to_text_string
from spyder.api.manager import Manager
from spyder.plugins.editor.utils.editor import BlockUserData
def _load_all_breakpoints():
bp_dict = CONF.get('run', 'breakpoints', {})
for filename in list(bp_dict.keys()):
if not osp.isfile(filename):
bp_dict.pop(filename)
return bp_dict
def load_breakpoints(filename):
breakpoints = _load_all_breakpoints().get(filename, [])
if breakpoints and isinstance(breakpoints[0], int):
# Old breakpoints format
breakpoints = [(lineno, None) for lineno in breakpoints]
return breakpoints
def save_breakpoints(filename, breakpoints):
if not osp.isfile(filename):
return
bp_dict = _load_all_breakpoints()
bp_dict[filename] = breakpoints
CONF.set('run', 'breakpoints', bp_dict)
def clear_all_breakpoints():
CONF.set('run', 'breakpoints', {})
def clear_breakpoint(filename, lineno):
breakpoints = load_breakpoints(filename)
if breakpoints:
for breakpoint in breakpoints[:]:
if breakpoint[0] == lineno:
breakpoints.remove(breakpoint)
save_breakpoints(filename, breakpoints)
class DebuggerManager(Manager):
"""
Manages adding/removing breakpoint from the editor.
"""
def __init__(self, editor):
s |
def set_filename(self, filename):
if filename is None:
return
if self.filename != filename:
old_filename = self.filename
self.filename = filename
if self.breakpoints:
save_breakpoints(old_filename, []) # clear old breakpoints
self.save_breakpoints()
def toogle_breakpoint(self, line_number=None, condition=None,
edit_condition=False):
"""Add/remove breakpoint."""
if not self.editor.is_python_like():
return
if line_number is None:
block = self.editor.textCursor().block()
else:
block = self.editor.document().findBlockByNumber(line_number-1)
data = block.userData()
if not data:
data = BlockUserData(self.editor)
data.breakpoint = True
elif not edit_condition:
data.breakpoint = not data.breakpoint
data.breakpoint_condition = None
if condition is not None:
data.breakpoint_condition = condition
if edit_condition:
condition = data.breakpoint_condition
condition, valid = QInputDialog.getText(self.editor,
_('Breakpoint'),
_("Condition:"),
QLineEdit.Normal,
condition)
if not valid:
return
data.breakpoint = True
data.breakpoint_condition = str(condition) if condition else None
if data.breakpoint:
text = to_text_string(block.text()).strip()
if len(text) == 0 or text.startswith(('#', '"', "'")):
data.breakpoint = False
block.setUserData(data)
self.editor.sig_flags_changed.emit()
self.editor.sig_breakpoints_changed.emit()
def get_breakpoints(self):
"""Get breakpoints"""
breakpoints = []
block = self.editor.document().firstBlock()
for line_number in range(1, self.editor.document().blockCount()+1):
data = block.userData()
if data and data.breakpoint:
breakpoints.append((line_number, data.breakpoint_condition))
block = block.next()
return breakpoints
def clear_breakpoints(self):
"""Clear breakpoints"""
self.breakpoints = []
for data in self.editor.blockuserdata_list():
data.breakpoint = False
# data.breakpoint_condition = None # not necessary, but logical
def set_breakpoints(self, breakpoints):
"""Set breakpoints"""
self.clear_breakpoints()
for line_number, condition in breakpoints:
self.toogle_breakpoint(line_number, condition)
self.breakpoints = self.get_breakpoints()
def update_breakpoints(self):
"""Update breakpoints"""
self.editor.sig_breakpoints_changed.emit()
def breakpoints_changed(self):
"""Breakpoint list has changed"""
breakpoints = self.get_breakpoints()
if self.breakpoints != breakpoints:
self.breakpoints = breakpoints
self.save_breakpoints()
def save_breakpoints(self):
breakpoints = repr(self.breakpoints)
filename = to_text_string(self.filename)
breakpoints = to_text_string(breakpoints)
filename = osp.normpath(osp.abspath(filename))
if breakpoints:
breakpoints = eval(breakpoints)
else:
breakpoints = []
save_breakpoints(filename, breakpoints)
self.editor.sig_breakpoints_saved.emit()
def load_breakpoints(self):
self.set_breakpoints(load_breakpoints(self.filename))
| uper(DebuggerManager, self).__init__(editor)
self.filename = None
self.breakpoints = self.get_breakpoints()
self.editor.sig_breakpoints_changed.connect(self.breakpoints_changed)
self.editor.sig_filename_changed.connect(self.set_filename)
|
color_windows_test.go | // Copyright 2014 beego Author. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build windows
package logs
import (
"bytes"
"fmt"
"syscall"
"testing"
)
var GetConsoleScreenBufferInfo = getConsoleScreenBufferInfo
func ChangeColor(color uint16) {
setConsoleTextAttribute(uintptr(syscall.Stdout), color)
}
func ResetColor() {
ChangeColor(uint16(0x0007))
}
func TestWritePlanText(t *testing.T) {
inner := bytes.NewBufferString("")
w := NewAnsiColorWriter(inner)
expected := "plain text"
fmt.Fprintf(w, expected)
actual := inner.String()
if actual != expected {
t.Errorf("Get %q, want %q", actual, expected)
}
}
func TestWriteParseText(t *testing.T) {
inner := bytes.NewBufferString("")
w := NewAnsiColorWriter(inner)
inputTail := "\x1b[0mtail text"
expectedTail := "tail text"
fmt.Fprintf(w, inputTail)
actualTail := inner.String()
inner.Reset()
if actualTail != expectedTail {
t.Errorf("Get %q, want %q", actualTail, expectedTail)
}
inputHead := "head text\x1b[0m"
expectedHead := "head text"
fmt.Fprintf(w, inputHead)
actualHead := inner.String()
inner.Reset()
if actualHead != expectedHead {
t.Errorf("Get %q, want %q", actualHead, expectedHead)
}
inputBothEnds := "both ends \x1b[0m text"
expectedBothEnds := "both ends text"
fmt.Fprintf(w, inputBothEnds)
actualBothEnds := inner.String()
inner.Reset()
if actualBothEnds != expectedBothEnds {
t.Errorf("Get %q, want %q", actualBothEnds, expectedBothEnds)
}
inputManyEsc := "\x1b\x1b\x1b\x1b[0m many esc"
expectedManyEsc := "\x1b\x1b\x1b many esc"
fmt.Fprintf(w, inputManyEsc)
actualManyEsc := inner.String()
inner.Reset()
if actualManyEsc != expectedManyEsc {
t.Errorf("Get %q, want %q", actualManyEsc, expectedManyEsc)
}
expectedSplit := "split text"
for _, ch := range "split \x1b[0m text" {
fmt.Fprintf(w, string(ch))
}
actualSplit := inner.String()
inner.Reset()
if actualSplit != expectedSplit {
t.Errorf("Get %q, want %q", actualSplit, expectedSplit)
}
}
type screenNotFoundError struct {
error
}
func writeAnsiColor(expectedText, colorCode string) (actualText string, actualAttributes uint16, err error) {
inner := bytes.NewBufferString("")
w := NewAnsiColorWriter(inner)
fmt.Fprintf(w, "\x1b[%sm%s", colorCode, expectedText)
actualText = inner.String()
screenInfo := GetConsoleScreenBufferInfo(uintptr(syscall.Stdout))
if screenInfo != nil {
actualAttributes = screenInfo.WAttributes
} else {
err = &screenNotFoundError{}
}
return
}
type testParam struct {
text string
attributes uint16
ansiColor string
}
func TestWriteAnsiColorText(t *testing.T) {
screenInfo := GetConsoleScreenBufferInfo(uintptr(syscall.Stdout))
if screenInfo == nil {
t.Fatal("Could not get ConsoleScreenBufferInfo")
}
defer ChangeColor(screenInfo.WAttributes)
defaultFgColor := screenInfo.WAttributes & uint16(0x0007)
defaultBgColor := screenInfo.WAttributes & uint16(0x0070)
defaultFgIntensity := screenInfo.WAttributes & uint16(0x0008)
defaultBgIntensity := screenInfo.WAttributes & uint16(0x0080)
fgParam := []testParam{
{"foreground black ", uint16(0x0000 | 0x0000), "30"},
{"foreground red ", uint16(0x0004 | 0x0000), "31"},
{"foreground green ", uint16(0x0002 | 0x0000), "32"},
{"foreground yellow ", uint16(0x0006 | 0x0000), "33"},
{"foreground blue ", uint16(0x0001 | 0x0000), "34"},
{"foreground magenta", uint16(0x0005 | 0x0000), "35"},
{"foreground cyan ", uint16(0x0003 | 0x0000), "36"},
{"foreground white ", uint16(0x0007 | 0x0000), "37"},
{"foreground default", defaultFgColor | 0x0000, "39"},
{"foreground light gray ", uint16(0x0000 | 0x0008 | 0x0000), "90"},
{"foreground light red ", uint16(0x0004 | 0x0008 | 0x0000), "91"},
{"foreground light green ", uint16(0x0002 | 0x0008 | 0x0000), "92"},
{"foreground light yellow ", uint16(0x0006 | 0x0008 | 0x0000), "93"},
{"foreground light blue ", uint16(0x0001 | 0x0008 | 0x0000), "94"},
{"foreground light magenta", uint16(0x0005 | 0x0008 | 0x0000), "95"},
{"foreground light cyan ", uint16(0x0003 | 0x0008 | 0x0000), "96"},
{"foreground light white ", uint16(0x0007 | 0x0008 | 0x0000), "97"},
}
bgParam := []testParam{
{"background black ", uint16(0x0007 | 0x0000), "40"},
{"background red ", uint16(0x0007 | 0x0040), "41"},
{"background green ", uint16(0x0007 | 0x0020), "42"},
{"background yellow ", uint16(0x0007 | 0x0060), "43"},
{"background blue ", uint16(0x0007 | 0x0010), "44"},
{"background magenta", uint16(0x0007 | 0x0050), "45"},
{"background cyan ", uint16(0x0007 | 0x0030), "46"},
{"background white ", uint16(0x0007 | 0x0070), "47"},
{"background default", uint16(0x0007) | defaultBgColor, "49"},
{"background light gray ", uint16(0x0007 | 0x0000 | 0x0080), "100"},
{"background light red ", uint16(0x0007 | 0x0040 | 0x0080), "101"},
{"background light green ", uint16(0x0007 | 0x0020 | 0x0080), "102"},
{"background light yellow ", uint16(0x0007 | 0x0060 | 0x0080), "103"},
{"background light blue ", uint16(0x0007 | 0x0010 | 0x0080), "104"},
{"background light magenta", uint16(0x0007 | 0x0050 | 0x0080), "105"},
{"background light cyan ", uint16(0x0007 | 0x0030 | 0x0080), "106"},
{"background light white ", uint16(0x0007 | 0x0070 | 0x0080), "107"},
}
resetParam := []testParam{
{"all reset", defaultFgColor | defaultBgColor | defaultFgIntensity | defaultBgIntensity, "0"},
{"all reset", defaultFgColor | defaultBgColor | defaultFgIntensity | defaultBgIntensity, ""},
}
boldParam := []testParam{
{"bold on", uint16(0x0007 | 0x0008), "1"},
{"bold off", uint16(0x0007), "21"},
}
underscoreParam := []testParam{
{"underscore on", uint16(0x0007 | 0x8000), "4"},
{"underscore off", uint16(0x0007), "24"},
}
blinkParam := []testParam{
{"blink on", uint16(0x0007 | 0x0080), "5"},
{"blink off", uint16(0x0007), "25"},
}
mixedParam := []testParam{
{"both black, bold, underline, blink", uint16(0x0000 | 0x0000 | 0x0008 | 0x8000 | 0x0080), "30;40;1;4;5"},
{"both red, bold, underline, blink", uint16(0x0004 | 0x0040 | 0x0008 | 0x8000 | 0x0080), "31;41;1;4;5"},
{"both green, bold, underline, blink", uint16(0x0002 | 0x0020 | 0x0008 | 0x8000 | 0x0080), "32;42;1;4;5"},
{"both yellow, bold, underline, blink", uint16(0x0006 | 0x0060 | 0x0008 | 0x8000 | 0x0080), "33;43;1;4;5"},
{"both blue, bold, underline, blink", uint16(0x0001 | 0x0010 | 0x0008 | 0x8000 | 0x0080), "34;44;1;4;5"},
{"both magenta, bold, underline, blink", uint16(0x0005 | 0x0050 | 0x0008 | 0x8000 | 0x0080), "35;45;1;4;5"},
{"both cyan, bold, underline, blink", uint16(0x0003 | 0x0030 | 0x0008 | 0x8000 | 0x0080), "36;46;1;4;5"},
{"both white, bold, underline, blink", uint16(0x0007 | 0x0070 | 0x0008 | 0x8000 | 0x0080), "37;47;1;4;5"},
{"both default, bold, underline, blink", uint16(defaultFgColor | defaultBgColor | 0x0008 | 0x8000 | 0x0080), "39;49;1;4;5"},
}
assertTextAttribute := func(expectedText string, expectedAttributes uint16, ansiColor string) {
actualText, actualAttributes, err := writeAnsiColor(expectedText, ansiColor)
if actualText != expectedText {
t.Errorf("Get %q, want %q", actualText, expectedText)
}
if err != nil {
t.Fatal("Could not get ConsoleScreenBufferInfo")
}
if actualAttributes != expectedAttributes {
t.Errorf("Text: %q, Get 0x%04x, want 0x%04x", expectedText, actualAttributes, expectedAttributes)
}
}
for _, v := range fgParam {
ResetColor()
assertTextAttribute(v.text, v.attributes, v.ansiColor)
}
for _, v := range bgParam {
ChangeColor(uint16(0x0070 | 0x0007))
assertTextAttribute(v.text, v.attributes, v.ansiColor)
}
for _, v := range resetParam {
ChangeColor(uint16(0x0000 | 0x0070 | 0x0008))
assertTextAttribute(v.text, v.attributes, v.ansiColor)
}
ResetColor()
for _, v := range boldParam {
assertTextAttribute(v.text, v.attributes, v.ansiColor)
}
ResetColor()
for _, v := range underscoreParam {
assertTextAttribute(v.text, v.attributes, v.ansiColor)
}
ResetColor()
for _, v := range blinkParam {
assertTextAttribute(v.text, v.attributes, v.ansiColor)
}
for _, v := range mixedParam {
ResetColor()
assertTextAttribute(v.text, v.attributes, v.ansiColor)
}
}
func TestIgnoreUnknownSequences(t *testing.T) {
inner := bytes.NewBufferString("")
w := NewModeAnsiColorWriter(inner, OutputNonColorEscSeq)
inputText := "\x1b[=decpath mode"
expectedTail := inputText
fmt.Fprintf(w, inputText)
actualTail := inner.String()
inner.Reset()
if actualTail != expectedTail {
t.Errorf("Get %q, want %q", actualTail, expectedTail)
}
inputText = "\x1b[=tailing esc and bracket\x1b["
expectedTail = inputText
fmt.Fprintf(w, inputText)
actualTail = inner.String()
inner.Reset()
if actualTail != expectedTail {
t.Errorf("Get %q, want %q", actualTail, expectedTail)
}
inputText = "\x1b[?tailing esc\x1b"
expectedTail = inputText
fmt.Fprintf(w, inputText)
actualTail = inner.String()
inner.Reset()
if actualTail != expectedTail {
t.Errorf("Get %q, want %q", actualTail, expectedTail)
}
inputText = "\x1b[1h;3punended color code invalid\x1b3"
expectedTail = inputText
fmt.Fprintf(w, inputText)
actualTail = inner.String()
inner.Reset()
if actualTail != expectedTail {
t.Errorf("Get %q, want %q", actualTail, expectedTail)
| }
} | |
wait_for_db.py | import time
from django.db import connections
from django.db.utils import OperationalError
from django.core.management.base import BaseCommand
class | (BaseCommand):
"""Django command to pause execution until the database is avaialable"""
def handle(self, *args, **options):
"""Handle the command"""
self.stdout.write('Waiting for database...')
db_conn = None
while not db_conn:
try:
db_conn = connections['default']
except OperationalError:
self.stdout.write('Database unavailable, waiting 1 second...')
time.sleep(1)
self.stdout.write(self.style.SUCCESS('Database Available!'))
| Command |
postgres.rs | use crate::{
ast::*,
visitor::{self, Visitor},
};
use std::fmt::{self, Write};
/// A visitor to generate queries for the PostgreSQL database.
///
/// The returned parameter values implement the `ToSql` trait from postgres and
/// can be used directly with the database.
#[cfg_attr(feature = "docs", doc(cfg(feature = "postgresql")))]
pub struct Postgres<'a> {
query: String,
parameters: Vec<Value<'a>>,
}
impl<'a> Visitor<'a> for Postgres<'a> {
const C_BACKTICK_OPEN: &'static str = "\"";
const C_BACKTICK_CLOSE: &'static str = "\"";
const C_WILDCARD: &'static str = "%";
#[tracing::instrument(name = "render_sql", skip(query))]
fn build<Q>(query: Q) -> crate::Result<(String, Vec<Value<'a>>)>
where
Q: Into<Query<'a>>,
{
let mut postgres = Postgres {
query: String::with_capacity(4096),
parameters: Vec::with_capacity(128),
};
Postgres::visit_query(&mut postgres, query.into())?;
Ok((postgres.query, postgres.parameters))
}
fn write<D: fmt::Display>(&mut self, s: D) -> visitor::Result {
write!(&mut self.query, "{}", s)?;
Ok(())
}
fn add_parameter(&mut self, value: Value<'a>) {
self.parameters.push(value);
}
fn parameter_substitution(&mut self) -> visitor::Result {
self.write("$")?;
self.write(self.parameters.len())
}
fn visit_limit_and_offset(&mut self, limit: Option<Value<'a>>, offset: Option<Value<'a>>) -> visitor::Result {
match (limit, offset) {
(Some(limit), Some(offset)) => {
self.write(" LIMIT ")?;
self.visit_parameterized(limit)?;
self.write(" OFFSET ")?;
self.visit_parameterized(offset)
}
(None, Some(offset)) => {
self.write(" OFFSET ")?;
self.visit_parameterized(offset)
}
(Some(limit), None) => {
self.write(" LIMIT ")?;
self.visit_parameterized(limit)
}
(None, None) => Ok(()),
}
}
fn visit_raw_value(&mut self, value: Value<'a>) -> visitor::Result {
let res = match value {
Value::Integer(i) => i.map(|i| self.write(i)),
Value::Text(t) => t.map(|t| self.write(format!("'{}'", t))),
Value::Enum(e) => e.map(|e| self.write(e)),
Value::Bytes(b) => b.map(|b| self.write(format!("E'{}'", hex::encode(b)))),
Value::Boolean(b) => b.map(|b| self.write(b)),
Value::Xml(cow) => cow.map(|cow| self.write(format!("'{}'", cow))),
Value::Char(c) => c.map(|c| self.write(format!("'{}'", c))),
Value::Float(d) => d.map(|f| match f {
f if f.is_nan() => self.write("'NaN'"),
f if f == f32::INFINITY => self.write("'Infinity'"),
f if f == f32::NEG_INFINITY => self.write("'-Infinity"),
v => self.write(format!("{:?}", v)),
}),
Value::Double(d) => d.map(|f| match f {
f if f.is_nan() => self.write("'NaN'"),
f if f == f64::INFINITY => self.write("'Infinity'"),
f if f == f64::NEG_INFINITY => self.write("'-Infinity"),
v => self.write(format!("{:?}", v)),
}),
Value::Array(ary) => ary.map(|ary| {
self.surround_with("'{", "}'", |ref mut s| {
let len = ary.len();
for (i, item) in ary.into_iter().enumerate() {
s.write(item)?;
if i < len - 1 {
s.write(",")?;
}
}
Ok(())
})
}),
#[cfg(feature = "json")]
Value::Json(j) => j.map(|j| self.write(format!("'{}'", serde_json::to_string(&j).unwrap()))),
#[cfg(feature = "bigdecimal")]
Value::Numeric(r) => r.map(|r| self.write(r)),
#[cfg(feature = "uuid")]
Value::Uuid(uuid) => uuid.map(|uuid| self.write(format!("'{}'", uuid.to_hyphenated().to_string()))),
#[cfg(feature = "chrono")]
Value::DateTime(dt) => dt.map(|dt| self.write(format!("'{}'", dt.to_rfc3339(),))),
#[cfg(feature = "chrono")]
Value::Date(date) => date.map(|date| self.write(format!("'{}'", date))),
#[cfg(feature = "chrono")]
Value::Time(time) => time.map(|time| self.write(format!("'{}'", time))),
};
match res {
Some(res) => res,
None => self.write("null"),
}
}
fn visit_insert(&mut self, insert: Insert<'a>) -> visitor::Result {
self.write("INSERT ")?;
if let Some(table) = insert.table {
self.write("INTO ")?;
self.visit_table(table, true)?;
}
match insert.values {
Expression {
kind: ExpressionKind::Row(row),
..
} => {
if row.values.is_empty() {
self.write(" DEFAULT VALUES")?;
} else {
let columns = insert.columns.len();
self.write(" (")?;
for (i, c) in insert.columns.into_iter().enumerate() {
self.visit_column(c.name.into_owned().into())?;
if i < (columns - 1) {
self.write(",")?;
}
}
self.write(")")?;
self.write(" VALUES ")?;
self.visit_row(row)?;
}
}
Expression {
kind: ExpressionKind::Values(values),
..
} => {
let columns = insert.columns.len();
self.write(" (")?;
for (i, c) in insert.columns.into_iter().enumerate() {
self.visit_column(c.name.into_owned().into())?;
if i < (columns - 1) {
self.write(",")?;
}
}
self.write(")")?;
self.write(" VALUES ")?;
let values_len = values.len();
for (i, row) in values.into_iter().enumerate() {
self.visit_row(row)?;
if i < (values_len - 1) {
self.write(", ")?;
}
}
}
expr => self.surround_with("(", ")", |ref mut s| s.visit_expression(expr))?,
}
if let Some(OnConflict::DoNothing) = insert.on_conflict {
self.write(" ON CONFLICT DO NOTHING")?;
};
if let Some(returning) = insert.returning {
if !returning.is_empty() {
let values = returning.into_iter().map(|r| r.into()).collect();
self.write(" RETURNING ")?;
self.visit_columns(values)?;
}
};
if let Some(comment) = insert.comment {
self.write(" ")?;
self.visit_comment(comment)?;
}
Ok(())
}
fn visit_aggregate_to_string(&mut self, value: Expression<'a>) -> visitor::Result {
self.write("ARRAY_TO_STRING")?;
self.write("(")?;
self.write("ARRAY_AGG")?;
self.write("(")?;
self.visit_expression(value)?;
self.write(")")?;
self.write("','")?;
self.write(")")
}
fn visit_equals(&mut self, left: Expression<'a>, right: Expression<'a>) -> visitor::Result {
// LHS must be cast to json/xml-text if the right is a json/xml-text value and vice versa.
let right_cast = match left {
#[cfg(feature = "json")]
_ if left.is_json_value() => "::jsonb",
_ if left.is_xml_value() => "::text",
_ => "",
};
let left_cast = match right {
#[cfg(feature = "json")]
_ if right.is_json_value() => "::jsonb",
_ if right.is_xml_value() => "::text",
_ => "",
};
self.visit_expression(left)?;
self.write(left_cast)?;
self.write(" = ")?;
self.visit_expression(right)?;
self.write(right_cast)?;
Ok(())
}
fn visit_not_equals(&mut self, left: Expression<'a>, right: Expression<'a>) -> visitor::Result {
// LHS must be cast to json/xml-text if the right is a json/xml-text value and vice versa.
let right_cast = match left {
#[cfg(feature = "json")]
_ if left.is_json_value() => "::jsonb",
_ if left.is_xml_value() => "::text",
_ => "",
};
let left_cast = match right {
#[cfg(feature = "json")]
_ if right.is_json_value() => "::jsonb",
_ if right.is_xml_value() => "::text",
_ => "",
};
self.visit_expression(left)?;
self.write(left_cast)?;
self.write(" <> ")?;
self.visit_expression(right)?;
self.write(right_cast)?;
Ok(())
}
#[cfg(all(feature = "json", any(feature = "postgresql", feature = "mysql")))]
fn visit_json_extract(&mut self, json_extract: JsonExtract<'a>) -> visitor::Result {
match json_extract.path {
#[cfg(feature = "mysql")]
JsonPath::String(_) => panic!("JSON path string notation is not supported for Postgres"),
JsonPath::Array(json_path) => {
self.write("(")?;
self.visit_expression(*json_extract.column)?;
if json_extract.extract_as_string {
self.write("#>>")?;
} else {
self.write("#>")?;
}
// We use the `ARRAY[]::text[]` notation to better handle escaped character
// The text protocol used when sending prepared statement doesn't seem to work well with escaped characters
// when using the '{a, b, c}' string array notation.
self.surround_with("ARRAY[", "]::text[]", |s| {
let len = json_path.len();
for (index, path) in json_path.into_iter().enumerate() {
s.visit_parameterized(Value::text(path))?;
if index < len - 1 {
s.write(", ")?;
}
}
Ok(())
})?;
self.write(")")?;
if !json_extract.extract_as_string {
self.write("::jsonb")?;
}
}
}
Ok(())
}
#[cfg(all(feature = "json", any(feature = "postgresql", feature = "mysql")))]
fn visit_json_array_contains(&mut self, left: Expression<'a>, right: Expression<'a>, not: bool) -> visitor::Result {
if not {
self.write("( NOT ")?;
}
self.visit_expression(left)?;
self.write(" @> ")?;
self.visit_expression(right)?;
if not {
self.write(" )")?;
}
Ok(())
}
#[cfg(all(feature = "json", any(feature = "postgresql", feature = "mysql")))]
fn visit_json_extract_last_array_item(&mut self, extract: JsonExtractLastArrayElem<'a>) -> visitor::Result {
self.write("(")?;
self.visit_expression(*extract.expr)?;
self.write("->-1")?;
self.write(")")?;
Ok(())
}
#[cfg(all(feature = "json", any(feature = "postgresql", feature = "mysql")))]
fn visit_json_extract_first_array_item(&mut self, extract: JsonExtractFirstArrayElem<'a>) -> visitor::Result {
self.write("(")?;
self.visit_expression(*extract.expr)?;
self.write("->0")?;
self.write(")")?;
Ok(())
}
#[cfg(all(feature = "json", any(feature = "postgresql", feature = "mysql")))]
fn visit_json_type_equals(&mut self, left: Expression<'a>, json_type: JsonType) -> visitor::Result {
self.write("JSONB_TYPEOF")?;
self.write("(")?;
self.visit_expression(left)?;
self.write(")")?;
self.write(" = ")?;
match json_type {
JsonType::Array => self.visit_expression(Value::text("array").into()),
JsonType::Boolean => self.visit_expression(Value::text("boolean").into()),
JsonType::Number => self.visit_expression(Value::text("number").into()),
JsonType::Object => self.visit_expression(Value::text("object").into()),
JsonType::String => self.visit_expression(Value::text("string").into()),
JsonType::Null => self.visit_expression(Value::text("null").into()),
}
}
#[cfg(feature = "postgresql")]
fn visit_text_search(&mut self, text_search: crate::prelude::TextSearch<'a>) -> visitor::Result {
let len = text_search.exprs.len();
self.surround_with("to_tsvector(", ")", |s| {
for (i, expr) in text_search.exprs.into_iter().enumerate() {
s.visit_expression(expr)?;
if i < (len - 1) {
s.write("|| ' ' ||")?;
}
}
Ok(())
})
}
#[cfg(feature = "postgresql")]
fn visit_matches(&mut self, left: Expression<'a>, right: std::borrow::Cow<'a, str>, not: bool) -> visitor::Result {
if not {
self.write("(NOT ")?;
}
self.visit_expression(left)?;
self.write(" @@ ")?;
self.surround_with("to_tsquery(", ")", |s| s.visit_parameterized(Value::text(right)))?;
if not {
self.write(")")?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use crate::visitor::*;
fn expected_values<'a, T>(sql: &'static str, params: Vec<T>) -> (String, Vec<Value<'a>>)
where
T: Into<Value<'a>>,
{
(String::from(sql), params.into_iter().map(|p| p.into()).collect())
}
fn default_params<'a>(mut additional: Vec<Value<'a>>) -> Vec<Value<'a>> {
let mut result = Vec::new();
for param in additional.drain(0..) {
result.push(param)
}
result
}
#[test]
fn test_single_row_insert_default_values() {
let query = Insert::single_into("users");
let (sql, params) = Postgres::build(query).unwrap();
assert_eq!("INSERT INTO \"users\" DEFAULT VALUES", sql);
assert_eq!(default_params(vec![]), params);
}
#[test]
fn test_single_row_insert() {
let expected = expected_values("INSERT INTO \"users\" (\"foo\") VALUES ($1)", vec![10]);
let query = Insert::single_into("users").value("foo", 10);
let (sql, params) = Postgres::build(query).unwrap();
assert_eq!(expected.0, sql);
assert_eq!(expected.1, params);
}
#[test]
#[cfg(feature = "postgres")]
fn test_returning_insert() {
let expected = expected_values(
"INSERT INTO \"users\" (\"foo\") VALUES ($1) RETURNING \"foo\"",
vec![10],
);
let query = Insert::single_into("users").value("foo", 10);
let (sql, params) = Postgres::build(Insert::from(query).returning(vec!["foo"])).unwrap();
assert_eq!(expected.0, sql);
assert_eq!(expected.1, params);
}
#[test]
fn test_multi_row_insert() {
let expected = expected_values("INSERT INTO \"users\" (\"foo\") VALUES ($1), ($2)", vec![10, 11]);
let query = Insert::multi_into("users", vec!["foo"])
.values(vec![10])
.values(vec![11]);
let (sql, params) = Postgres::build(query).unwrap(); |
assert_eq!(expected.0, sql);
assert_eq!(expected.1, params);
}
#[test]
fn test_limit_and_offset_when_both_are_set() {
let expected = expected_values("SELECT \"users\".* FROM \"users\" LIMIT $1 OFFSET $2", vec![10, 2]);
let query = Select::from_table("users").limit(10).offset(2);
let (sql, params) = Postgres::build(query).unwrap();
assert_eq!(expected.0, sql);
assert_eq!(expected.1, params);
}
#[test]
fn test_limit_and_offset_when_only_offset_is_set() {
let expected = expected_values("SELECT \"users\".* FROM \"users\" OFFSET $1", vec![10]);
let query = Select::from_table("users").offset(10);
let (sql, params) = Postgres::build(query).unwrap();
assert_eq!(expected.0, sql);
assert_eq!(expected.1, params);
}
#[test]
fn test_limit_and_offset_when_only_limit_is_set() {
let expected = expected_values("SELECT \"users\".* FROM \"users\" LIMIT $1", vec![10]);
let query = Select::from_table("users").limit(10);
let (sql, params) = Postgres::build(query).unwrap();
assert_eq!(expected.0, sql);
assert_eq!(expected.1, params);
}
#[test]
fn test_distinct() {
let expected_sql = "SELECT DISTINCT \"bar\" FROM \"test\"";
let query = Select::from_table("test").column(Column::new("bar")).distinct();
let (sql, _) = Postgres::build(query).unwrap();
assert_eq!(expected_sql, sql);
}
#[test]
fn test_distinct_with_subquery() {
let expected_sql = "SELECT DISTINCT (SELECT $1 FROM \"test2\"), \"bar\" FROM \"test\"";
let query = Select::from_table("test")
.value(Select::from_table("test2").value(val!(1)))
.column(Column::new("bar"))
.distinct();
let (sql, _) = Postgres::build(query).unwrap();
assert_eq!(expected_sql, sql);
}
#[test]
fn test_from() {
let expected_sql = "SELECT \"foo\".*, \"bar\".\"a\" FROM \"foo\", (SELECT \"a\" FROM \"baz\") AS \"bar\"";
let query = Select::default()
.and_from("foo")
.and_from(Table::from(Select::from_table("baz").column("a")).alias("bar"))
.value(Table::from("foo").asterisk())
.column(("bar", "a"));
let (sql, _) = Postgres::build(query).unwrap();
assert_eq!(expected_sql, sql);
}
#[test]
fn test_comment_select() {
let expected_sql = "SELECT \"users\".* FROM \"users\" /* trace_id='5bd66ef5095369c7b0d1f8f4bd33716a', parent_id='c532cb4098ac3dd2' */";
let query = Select::from_table("users")
.comment("trace_id='5bd66ef5095369c7b0d1f8f4bd33716a', parent_id='c532cb4098ac3dd2'");
let (sql, _) = Postgres::build(query).unwrap();
assert_eq!(expected_sql, sql);
}
#[test]
fn test_comment_insert() {
let expected_sql = "INSERT INTO \"users\" DEFAULT VALUES /* trace_id='5bd66ef5095369c7b0d1f8f4bd33716a', parent_id='c532cb4098ac3dd2' */";
let query = Insert::single_into("users");
let insert =
Insert::from(query).comment("trace_id='5bd66ef5095369c7b0d1f8f4bd33716a', parent_id='c532cb4098ac3dd2'");
let (sql, _) = Postgres::build(insert).unwrap();
assert_eq!(expected_sql, sql);
}
#[test]
fn test_comment_update() {
let expected_sql = "UPDATE \"users\" SET \"foo\" = $1 /* trace_id='5bd66ef5095369c7b0d1f8f4bd33716a', parent_id='c532cb4098ac3dd2' */";
let query = Update::table("users")
.set("foo", 10)
.comment("trace_id='5bd66ef5095369c7b0d1f8f4bd33716a', parent_id='c532cb4098ac3dd2'");
let (sql, _) = Postgres::build(query).unwrap();
assert_eq!(expected_sql, sql);
}
#[test]
fn test_comment_delete() {
let expected_sql =
"DELETE FROM \"users\" /* trace_id='5bd66ef5095369c7b0d1f8f4bd33716a', parent_id='c532cb4098ac3dd2' */";
let query = Delete::from_table("users")
.comment("trace_id='5bd66ef5095369c7b0d1f8f4bd33716a', parent_id='c532cb4098ac3dd2'");
let (sql, _) = Postgres::build(query).unwrap();
assert_eq!(expected_sql, sql);
}
#[cfg(feature = "json")]
#[test]
fn equality_with_a_json_value() {
let expected = expected_values(
r#"SELECT "users".* FROM "users" WHERE "jsonField"::jsonb = $1"#,
vec![serde_json::json!({"a": "b"})],
);
let query = Select::from_table("users").so_that(Column::from("jsonField").equals(serde_json::json!({"a":"b"})));
let (sql, params) = Postgres::build(query).unwrap();
assert_eq!(expected.0, sql);
assert_eq!(expected.1, params);
}
#[cfg(feature = "json")]
#[test]
fn equality_with_a_lhs_json_value() {
// A bit artificial, but checks if the ::jsonb casting is done correctly on the right side as well.
let expected = expected_values(
r#"SELECT "users".* FROM "users" WHERE $1 = "jsonField"::jsonb"#,
vec![serde_json::json!({"a": "b"})],
);
let value_expr: Expression = Value::json(serde_json::json!({"a":"b"})).into();
let query = Select::from_table("users").so_that(value_expr.equals(Column::from("jsonField")));
let (sql, params) = Postgres::build(query).unwrap();
assert_eq!(expected.0, sql);
assert_eq!(expected.1, params);
}
#[cfg(feature = "json")]
#[test]
fn difference_with_a_json_value() {
let expected = expected_values(
r#"SELECT "users".* FROM "users" WHERE "jsonField"::jsonb <> $1"#,
vec![serde_json::json!({"a": "b"})],
);
let query =
Select::from_table("users").so_that(Column::from("jsonField").not_equals(serde_json::json!({"a":"b"})));
let (sql, params) = Postgres::build(query).unwrap();
assert_eq!(expected.0, sql);
assert_eq!(expected.1, params);
}
#[cfg(feature = "json")]
#[test]
fn difference_with_a_lhs_json_value() {
let expected = expected_values(
r#"SELECT "users".* FROM "users" WHERE $1 <> "jsonField"::jsonb"#,
vec![serde_json::json!({"a": "b"})],
);
let value_expr: Expression = Value::json(serde_json::json!({"a":"b"})).into();
let query = Select::from_table("users").so_that(value_expr.not_equals(Column::from("jsonField")));
let (sql, params) = Postgres::build(query).unwrap();
assert_eq!(expected.0, sql);
assert_eq!(expected.1, params);
}
#[test]
fn equality_with_a_xml_value() {
let expected = expected_values(
r#"SELECT "users".* FROM "users" WHERE "xmlField"::text = $1"#,
vec![Value::xml("<salad>wurst</salad>")],
);
let query =
Select::from_table("users").so_that(Column::from("xmlField").equals(Value::xml("<salad>wurst</salad>")));
let (sql, params) = Postgres::build(query).unwrap();
assert_eq!(expected.0, sql);
assert_eq!(expected.1, params);
}
#[test]
fn equality_with_a_lhs_xml_value() {
let expected = expected_values(
r#"SELECT "users".* FROM "users" WHERE $1 = "xmlField"::text"#,
vec![Value::xml("<salad>wurst</salad>")],
);
let value_expr: Expression = Value::xml("<salad>wurst</salad>").into();
let query = Select::from_table("users").so_that(value_expr.equals(Column::from("xmlField")));
let (sql, params) = Postgres::build(query).unwrap();
assert_eq!(expected.0, sql);
assert_eq!(expected.1, params);
}
#[test]
fn difference_with_a_xml_value() {
let expected = expected_values(
r#"SELECT "users".* FROM "users" WHERE "xmlField"::text <> $1"#,
vec![Value::xml("<salad>wurst</salad>")],
);
let query = Select::from_table("users")
.so_that(Column::from("xmlField").not_equals(Value::xml("<salad>wurst</salad>")));
let (sql, params) = Postgres::build(query).unwrap();
assert_eq!(expected.0, sql);
assert_eq!(expected.1, params);
}
#[test]
fn difference_with_a_lhs_xml_value() {
let expected = expected_values(
r#"SELECT "users".* FROM "users" WHERE $1 <> "xmlField"::text"#,
vec![Value::xml("<salad>wurst</salad>")],
);
let value_expr: Expression = Value::xml("<salad>wurst</salad>").into();
let query = Select::from_table("users").so_that(value_expr.not_equals(Column::from("xmlField")));
let (sql, params) = Postgres::build(query).unwrap();
assert_eq!(expected.0, sql);
assert_eq!(expected.1, params);
}
#[test]
fn test_raw_null() {
let (sql, params) = Postgres::build(Select::default().value(Value::Text(None).raw())).unwrap();
assert_eq!("SELECT null", sql);
assert!(params.is_empty());
}
#[test]
fn test_raw_int() {
let (sql, params) = Postgres::build(Select::default().value(1.raw())).unwrap();
assert_eq!("SELECT 1", sql);
assert!(params.is_empty());
}
#[test]
fn test_raw_real() {
let (sql, params) = Postgres::build(Select::default().value(1.3f64.raw())).unwrap();
assert_eq!("SELECT 1.3", sql);
assert!(params.is_empty());
}
#[test]
fn test_raw_text() {
let (sql, params) = Postgres::build(Select::default().value("foo".raw())).unwrap();
assert_eq!("SELECT 'foo'", sql);
assert!(params.is_empty());
}
#[test]
fn test_raw_bytes() {
let (sql, params) = Postgres::build(Select::default().value(Value::bytes(vec![1, 2, 3]).raw())).unwrap();
assert_eq!("SELECT E'010203'", sql);
assert!(params.is_empty());
}
#[test]
fn test_raw_boolean() {
let (sql, params) = Postgres::build(Select::default().value(true.raw())).unwrap();
assert_eq!("SELECT true", sql);
assert!(params.is_empty());
let (sql, params) = Postgres::build(Select::default().value(false.raw())).unwrap();
assert_eq!("SELECT false", sql);
assert!(params.is_empty());
}
#[test]
fn test_raw_char() {
let (sql, params) = Postgres::build(Select::default().value(Value::character('a').raw())).unwrap();
assert_eq!("SELECT 'a'", sql);
assert!(params.is_empty());
}
#[test]
#[cfg(feature = "json")]
fn test_raw_json() {
let (sql, params) =
Postgres::build(Select::default().value(serde_json::json!({ "foo": "bar" }).raw())).unwrap();
assert_eq!("SELECT '{\"foo\":\"bar\"}'", sql);
assert!(params.is_empty());
}
#[test]
#[cfg(feature = "uuid")]
fn test_raw_uuid() {
let uuid = uuid::Uuid::new_v4();
let (sql, params) = Postgres::build(Select::default().value(uuid.raw())).unwrap();
assert_eq!(format!("SELECT '{}'", uuid.to_hyphenated().to_string()), sql);
assert!(params.is_empty());
}
#[test]
#[cfg(feature = "chrono")]
fn test_raw_datetime() {
let dt = chrono::Utc::now();
let (sql, params) = Postgres::build(Select::default().value(dt.raw())).unwrap();
assert_eq!(format!("SELECT '{}'", dt.to_rfc3339(),), sql);
assert!(params.is_empty());
}
#[test]
fn test_raw_comparator() {
let (sql, _) = Postgres::build(Select::from_table("foo").so_that("bar".compare_raw("ILIKE", "baz%"))).unwrap();
assert_eq!(r#"SELECT "foo".* FROM "foo" WHERE "bar" ILIKE $1"#, sql);
}
#[test]
fn test_default_insert() {
let insert = Insert::single_into("foo")
.value("foo", "bar")
.value("baz", default_value());
let (sql, _) = Postgres::build(insert).unwrap();
assert_eq!("INSERT INTO \"foo\" (\"foo\",\"baz\") VALUES ($1,DEFAULT)", sql);
}
#[test]
fn join_is_inserted_positionally() {
let joined_table = Table::from("User").left_join(
"Post"
.alias("p")
.on(("p", "userId").equals(Column::from(("User", "id")))),
);
let q = Select::from_table(joined_table).and_from("Toto");
let (sql, _) = Postgres::build(q).unwrap();
assert_eq!("SELECT \"User\".*, \"Toto\".* FROM \"User\" LEFT JOIN \"Post\" AS \"p\" ON \"p\".\"userId\" = \"User\".\"id\", \"Toto\"", sql);
}
} | |
deserializers.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package cloud9
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws/protocol/restjson"
"github.com/aws/aws-sdk-go-v2/service/cloud9/types"
smithy "github.com/awslabs/smithy-go"
smithyio "github.com/awslabs/smithy-go/io"
"github.com/awslabs/smithy-go/middleware"
"github.com/awslabs/smithy-go/ptr"
smithytime "github.com/awslabs/smithy-go/time"
smithyhttp "github.com/awslabs/smithy-go/transport/http"
"io"
"strings"
)
type awsAwsjson11_deserializeOpCreateEnvironmentEC2 struct {
}
func (*awsAwsjson11_deserializeOpCreateEnvironmentEC2) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpCreateEnvironmentEC2) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorCreateEnvironmentEC2(response, &metadata)
}
output := &CreateEnvironmentEC2Output{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentCreateEnvironmentEC2Output(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorCreateEnvironmentEC2(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("BadRequestException", errorCode):
return awsAwsjson11_deserializeErrorBadRequestException(response, errorBody)
case strings.EqualFold("ConflictException", errorCode):
return awsAwsjson11_deserializeErrorConflictException(response, errorBody)
case strings.EqualFold("ForbiddenException", errorCode):
return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody)
case strings.EqualFold("InternalServerErrorException", errorCode):
return awsAwsjson11_deserializeErrorInternalServerErrorException(response, errorBody)
case strings.EqualFold("LimitExceededException", errorCode):
return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody)
case strings.EqualFold("NotFoundException", errorCode):
return awsAwsjson11_deserializeErrorNotFoundException(response, errorBody)
case strings.EqualFold("TooManyRequestsException", errorCode):
return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpCreateEnvironmentMembership struct {
}
func (*awsAwsjson11_deserializeOpCreateEnvironmentMembership) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpCreateEnvironmentMembership) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorCreateEnvironmentMembership(response, &metadata)
}
output := &CreateEnvironmentMembershipOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentCreateEnvironmentMembershipOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func | (response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("BadRequestException", errorCode):
return awsAwsjson11_deserializeErrorBadRequestException(response, errorBody)
case strings.EqualFold("ConflictException", errorCode):
return awsAwsjson11_deserializeErrorConflictException(response, errorBody)
case strings.EqualFold("ForbiddenException", errorCode):
return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody)
case strings.EqualFold("InternalServerErrorException", errorCode):
return awsAwsjson11_deserializeErrorInternalServerErrorException(response, errorBody)
case strings.EqualFold("LimitExceededException", errorCode):
return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody)
case strings.EqualFold("NotFoundException", errorCode):
return awsAwsjson11_deserializeErrorNotFoundException(response, errorBody)
case strings.EqualFold("TooManyRequestsException", errorCode):
return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDeleteEnvironment struct {
}
func (*awsAwsjson11_deserializeOpDeleteEnvironment) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDeleteEnvironment) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDeleteEnvironment(response, &metadata)
}
output := &DeleteEnvironmentOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDeleteEnvironmentOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDeleteEnvironment(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("BadRequestException", errorCode):
return awsAwsjson11_deserializeErrorBadRequestException(response, errorBody)
case strings.EqualFold("ConflictException", errorCode):
return awsAwsjson11_deserializeErrorConflictException(response, errorBody)
case strings.EqualFold("ForbiddenException", errorCode):
return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody)
case strings.EqualFold("InternalServerErrorException", errorCode):
return awsAwsjson11_deserializeErrorInternalServerErrorException(response, errorBody)
case strings.EqualFold("LimitExceededException", errorCode):
return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody)
case strings.EqualFold("NotFoundException", errorCode):
return awsAwsjson11_deserializeErrorNotFoundException(response, errorBody)
case strings.EqualFold("TooManyRequestsException", errorCode):
return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDeleteEnvironmentMembership struct {
}
func (*awsAwsjson11_deserializeOpDeleteEnvironmentMembership) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDeleteEnvironmentMembership) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDeleteEnvironmentMembership(response, &metadata)
}
output := &DeleteEnvironmentMembershipOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDeleteEnvironmentMembershipOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDeleteEnvironmentMembership(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("BadRequestException", errorCode):
return awsAwsjson11_deserializeErrorBadRequestException(response, errorBody)
case strings.EqualFold("ConflictException", errorCode):
return awsAwsjson11_deserializeErrorConflictException(response, errorBody)
case strings.EqualFold("ForbiddenException", errorCode):
return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody)
case strings.EqualFold("InternalServerErrorException", errorCode):
return awsAwsjson11_deserializeErrorInternalServerErrorException(response, errorBody)
case strings.EqualFold("LimitExceededException", errorCode):
return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody)
case strings.EqualFold("NotFoundException", errorCode):
return awsAwsjson11_deserializeErrorNotFoundException(response, errorBody)
case strings.EqualFold("TooManyRequestsException", errorCode):
return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDescribeEnvironmentMemberships struct {
}
func (*awsAwsjson11_deserializeOpDescribeEnvironmentMemberships) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDescribeEnvironmentMemberships) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDescribeEnvironmentMemberships(response, &metadata)
}
output := &DescribeEnvironmentMembershipsOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDescribeEnvironmentMembershipsOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDescribeEnvironmentMemberships(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("BadRequestException", errorCode):
return awsAwsjson11_deserializeErrorBadRequestException(response, errorBody)
case strings.EqualFold("ConflictException", errorCode):
return awsAwsjson11_deserializeErrorConflictException(response, errorBody)
case strings.EqualFold("ForbiddenException", errorCode):
return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody)
case strings.EqualFold("InternalServerErrorException", errorCode):
return awsAwsjson11_deserializeErrorInternalServerErrorException(response, errorBody)
case strings.EqualFold("LimitExceededException", errorCode):
return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody)
case strings.EqualFold("NotFoundException", errorCode):
return awsAwsjson11_deserializeErrorNotFoundException(response, errorBody)
case strings.EqualFold("TooManyRequestsException", errorCode):
return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDescribeEnvironments struct {
}
func (*awsAwsjson11_deserializeOpDescribeEnvironments) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDescribeEnvironments) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDescribeEnvironments(response, &metadata)
}
output := &DescribeEnvironmentsOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDescribeEnvironmentsOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDescribeEnvironments(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("BadRequestException", errorCode):
return awsAwsjson11_deserializeErrorBadRequestException(response, errorBody)
case strings.EqualFold("ConflictException", errorCode):
return awsAwsjson11_deserializeErrorConflictException(response, errorBody)
case strings.EqualFold("ForbiddenException", errorCode):
return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody)
case strings.EqualFold("InternalServerErrorException", errorCode):
return awsAwsjson11_deserializeErrorInternalServerErrorException(response, errorBody)
case strings.EqualFold("LimitExceededException", errorCode):
return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody)
case strings.EqualFold("NotFoundException", errorCode):
return awsAwsjson11_deserializeErrorNotFoundException(response, errorBody)
case strings.EqualFold("TooManyRequestsException", errorCode):
return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpDescribeEnvironmentStatus struct {
}
func (*awsAwsjson11_deserializeOpDescribeEnvironmentStatus) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpDescribeEnvironmentStatus) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorDescribeEnvironmentStatus(response, &metadata)
}
output := &DescribeEnvironmentStatusOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentDescribeEnvironmentStatusOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorDescribeEnvironmentStatus(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("BadRequestException", errorCode):
return awsAwsjson11_deserializeErrorBadRequestException(response, errorBody)
case strings.EqualFold("ConflictException", errorCode):
return awsAwsjson11_deserializeErrorConflictException(response, errorBody)
case strings.EqualFold("ForbiddenException", errorCode):
return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody)
case strings.EqualFold("InternalServerErrorException", errorCode):
return awsAwsjson11_deserializeErrorInternalServerErrorException(response, errorBody)
case strings.EqualFold("LimitExceededException", errorCode):
return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody)
case strings.EqualFold("NotFoundException", errorCode):
return awsAwsjson11_deserializeErrorNotFoundException(response, errorBody)
case strings.EqualFold("TooManyRequestsException", errorCode):
return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpListEnvironments struct {
}
func (*awsAwsjson11_deserializeOpListEnvironments) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpListEnvironments) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorListEnvironments(response, &metadata)
}
output := &ListEnvironmentsOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentListEnvironmentsOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorListEnvironments(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("BadRequestException", errorCode):
return awsAwsjson11_deserializeErrorBadRequestException(response, errorBody)
case strings.EqualFold("ConflictException", errorCode):
return awsAwsjson11_deserializeErrorConflictException(response, errorBody)
case strings.EqualFold("ForbiddenException", errorCode):
return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody)
case strings.EqualFold("InternalServerErrorException", errorCode):
return awsAwsjson11_deserializeErrorInternalServerErrorException(response, errorBody)
case strings.EqualFold("LimitExceededException", errorCode):
return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody)
case strings.EqualFold("NotFoundException", errorCode):
return awsAwsjson11_deserializeErrorNotFoundException(response, errorBody)
case strings.EqualFold("TooManyRequestsException", errorCode):
return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpListTagsForResource struct {
}
func (*awsAwsjson11_deserializeOpListTagsForResource) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpListTagsForResource) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorListTagsForResource(response, &metadata)
}
output := &ListTagsForResourceOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentListTagsForResourceOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorListTagsForResource(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("BadRequestException", errorCode):
return awsAwsjson11_deserializeErrorBadRequestException(response, errorBody)
case strings.EqualFold("InternalServerErrorException", errorCode):
return awsAwsjson11_deserializeErrorInternalServerErrorException(response, errorBody)
case strings.EqualFold("NotFoundException", errorCode):
return awsAwsjson11_deserializeErrorNotFoundException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpTagResource struct {
}
func (*awsAwsjson11_deserializeOpTagResource) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpTagResource) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorTagResource(response, &metadata)
}
output := &TagResourceOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentTagResourceOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorTagResource(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("BadRequestException", errorCode):
return awsAwsjson11_deserializeErrorBadRequestException(response, errorBody)
case strings.EqualFold("ConcurrentAccessException", errorCode):
return awsAwsjson11_deserializeErrorConcurrentAccessException(response, errorBody)
case strings.EqualFold("InternalServerErrorException", errorCode):
return awsAwsjson11_deserializeErrorInternalServerErrorException(response, errorBody)
case strings.EqualFold("NotFoundException", errorCode):
return awsAwsjson11_deserializeErrorNotFoundException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpUntagResource struct {
}
func (*awsAwsjson11_deserializeOpUntagResource) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpUntagResource) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorUntagResource(response, &metadata)
}
output := &UntagResourceOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentUntagResourceOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorUntagResource(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("BadRequestException", errorCode):
return awsAwsjson11_deserializeErrorBadRequestException(response, errorBody)
case strings.EqualFold("ConcurrentAccessException", errorCode):
return awsAwsjson11_deserializeErrorConcurrentAccessException(response, errorBody)
case strings.EqualFold("InternalServerErrorException", errorCode):
return awsAwsjson11_deserializeErrorInternalServerErrorException(response, errorBody)
case strings.EqualFold("NotFoundException", errorCode):
return awsAwsjson11_deserializeErrorNotFoundException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpUpdateEnvironment struct {
}
func (*awsAwsjson11_deserializeOpUpdateEnvironment) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpUpdateEnvironment) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorUpdateEnvironment(response, &metadata)
}
output := &UpdateEnvironmentOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentUpdateEnvironmentOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorUpdateEnvironment(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("BadRequestException", errorCode):
return awsAwsjson11_deserializeErrorBadRequestException(response, errorBody)
case strings.EqualFold("ConflictException", errorCode):
return awsAwsjson11_deserializeErrorConflictException(response, errorBody)
case strings.EqualFold("ForbiddenException", errorCode):
return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody)
case strings.EqualFold("InternalServerErrorException", errorCode):
return awsAwsjson11_deserializeErrorInternalServerErrorException(response, errorBody)
case strings.EqualFold("LimitExceededException", errorCode):
return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody)
case strings.EqualFold("NotFoundException", errorCode):
return awsAwsjson11_deserializeErrorNotFoundException(response, errorBody)
case strings.EqualFold("TooManyRequestsException", errorCode):
return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
type awsAwsjson11_deserializeOpUpdateEnvironmentMembership struct {
}
func (*awsAwsjson11_deserializeOpUpdateEnvironmentMembership) ID() string {
return "OperationDeserializer"
}
func (m *awsAwsjson11_deserializeOpUpdateEnvironmentMembership) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
out middleware.DeserializeOutput, metadata middleware.Metadata, err error,
) {
out, metadata, err = next.HandleDeserialize(ctx, in)
if err != nil {
return out, metadata, err
}
response, ok := out.RawResponse.(*smithyhttp.Response)
if !ok {
return out, metadata, &smithy.DeserializationError{Err: fmt.Errorf("unknown transport type %T", out.RawResponse)}
}
if response.StatusCode < 200 || response.StatusCode >= 300 {
return out, metadata, awsAwsjson11_deserializeOpErrorUpdateEnvironmentMembership(response, &metadata)
}
output := &UpdateEnvironmentMembershipOutput{}
out.Result = output
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(response.Body, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
err = awsAwsjson11_deserializeOpDocumentUpdateEnvironmentMembershipOutput(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return out, metadata, err
}
return out, metadata, err
}
func awsAwsjson11_deserializeOpErrorUpdateEnvironmentMembership(response *smithyhttp.Response, metadata *middleware.Metadata) error {
var errorBuffer bytes.Buffer
if _, err := io.Copy(&errorBuffer, response.Body); err != nil {
return &smithy.DeserializationError{Err: fmt.Errorf("failed to copy error response body, %w", err)}
}
errorBody := bytes.NewReader(errorBuffer.Bytes())
errorCode := "UnknownError"
errorMessage := errorCode
code := response.Header.Get("X-Amzn-ErrorType")
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
code, message, err := restjson.GetErrorInfo(decoder)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
if len(code) != 0 {
errorCode = restjson.SanitizeErrorCode(code)
}
if len(message) != 0 {
errorMessage = message
}
switch {
case strings.EqualFold("BadRequestException", errorCode):
return awsAwsjson11_deserializeErrorBadRequestException(response, errorBody)
case strings.EqualFold("ConflictException", errorCode):
return awsAwsjson11_deserializeErrorConflictException(response, errorBody)
case strings.EqualFold("ForbiddenException", errorCode):
return awsAwsjson11_deserializeErrorForbiddenException(response, errorBody)
case strings.EqualFold("InternalServerErrorException", errorCode):
return awsAwsjson11_deserializeErrorInternalServerErrorException(response, errorBody)
case strings.EqualFold("LimitExceededException", errorCode):
return awsAwsjson11_deserializeErrorLimitExceededException(response, errorBody)
case strings.EqualFold("NotFoundException", errorCode):
return awsAwsjson11_deserializeErrorNotFoundException(response, errorBody)
case strings.EqualFold("TooManyRequestsException", errorCode):
return awsAwsjson11_deserializeErrorTooManyRequestsException(response, errorBody)
default:
genericError := &smithy.GenericAPIError{
Code: errorCode,
Message: errorMessage,
}
return genericError
}
}
func awsAwsjson11_deserializeErrorBadRequestException(response *smithyhttp.Response, errorBody *bytes.Reader) error {
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
output := &types.BadRequestException{}
err := awsAwsjson11_deserializeDocumentBadRequestException(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
return output
}
func awsAwsjson11_deserializeErrorConcurrentAccessException(response *smithyhttp.Response, errorBody *bytes.Reader) error {
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
output := &types.ConcurrentAccessException{}
err := awsAwsjson11_deserializeDocumentConcurrentAccessException(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
return output
}
func awsAwsjson11_deserializeErrorConflictException(response *smithyhttp.Response, errorBody *bytes.Reader) error {
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
output := &types.ConflictException{}
err := awsAwsjson11_deserializeDocumentConflictException(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
return output
}
func awsAwsjson11_deserializeErrorForbiddenException(response *smithyhttp.Response, errorBody *bytes.Reader) error {
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
output := &types.ForbiddenException{}
err := awsAwsjson11_deserializeDocumentForbiddenException(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
return output
}
func awsAwsjson11_deserializeErrorInternalServerErrorException(response *smithyhttp.Response, errorBody *bytes.Reader) error {
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
output := &types.InternalServerErrorException{}
err := awsAwsjson11_deserializeDocumentInternalServerErrorException(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
return output
}
func awsAwsjson11_deserializeErrorLimitExceededException(response *smithyhttp.Response, errorBody *bytes.Reader) error {
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
output := &types.LimitExceededException{}
err := awsAwsjson11_deserializeDocumentLimitExceededException(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
return output
}
func awsAwsjson11_deserializeErrorNotFoundException(response *smithyhttp.Response, errorBody *bytes.Reader) error {
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
output := &types.NotFoundException{}
err := awsAwsjson11_deserializeDocumentNotFoundException(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
return output
}
func awsAwsjson11_deserializeErrorTooManyRequestsException(response *smithyhttp.Response, errorBody *bytes.Reader) error {
var buff [1024]byte
ringBuffer := smithyio.NewRingBuffer(buff[:])
body := io.TeeReader(errorBody, ringBuffer)
decoder := json.NewDecoder(body)
decoder.UseNumber()
var shape interface{}
if err := decoder.Decode(&shape); err != nil && err != io.EOF {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
output := &types.TooManyRequestsException{}
err := awsAwsjson11_deserializeDocumentTooManyRequestsException(&output, shape)
if err != nil {
var snapshot bytes.Buffer
io.Copy(&snapshot, ringBuffer)
err = &smithy.DeserializationError{
Err: fmt.Errorf("failed to decode response body, %w", err),
Snapshot: snapshot.Bytes(),
}
return err
}
errorBody.Seek(0, io.SeekStart)
return output
}
func awsAwsjson11_deserializeDocumentBadRequestException(v **types.BadRequestException, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.BadRequestException
if *v == nil {
sv = &types.BadRequestException{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "className":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.ClassName = ptr.String(jtv)
}
case "code":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected Integer to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Code = int32(i64)
}
case "message":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.Message = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentConcurrentAccessException(v **types.ConcurrentAccessException, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.ConcurrentAccessException
if *v == nil {
sv = &types.ConcurrentAccessException{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "className":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.ClassName = ptr.String(jtv)
}
case "code":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected Integer to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Code = int32(i64)
}
case "message":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.Message = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentConflictException(v **types.ConflictException, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.ConflictException
if *v == nil {
sv = &types.ConflictException{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "className":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.ClassName = ptr.String(jtv)
}
case "code":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected Integer to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Code = int32(i64)
}
case "message":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.Message = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentEnvironment(v **types.Environment, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.Environment
if *v == nil {
sv = &types.Environment{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "arn":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.Arn = ptr.String(jtv)
}
case "connectionType":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected ConnectionType to be of type string, got %T instead", value)
}
sv.ConnectionType = types.ConnectionType(jtv)
}
case "description":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected EnvironmentDescription to be of type string, got %T instead", value)
}
sv.Description = ptr.String(jtv)
}
case "id":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected EnvironmentId to be of type string, got %T instead", value)
}
sv.Id = ptr.String(jtv)
}
case "lifecycle":
if err := awsAwsjson11_deserializeDocumentEnvironmentLifecycle(&sv.Lifecycle, value); err != nil {
return err
}
case "name":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected EnvironmentName to be of type string, got %T instead", value)
}
sv.Name = ptr.String(jtv)
}
case "ownerArn":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.OwnerArn = ptr.String(jtv)
}
case "type":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected EnvironmentType to be of type string, got %T instead", value)
}
sv.Type = types.EnvironmentType(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentEnvironmentIdList(v *[]string, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []string
if *v == nil {
cv = []string{}
} else {
cv = *v
}
for _, value := range shape {
var col string
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected EnvironmentId to be of type string, got %T instead", value)
}
col = jtv
}
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeDocumentEnvironmentLifecycle(v **types.EnvironmentLifecycle, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.EnvironmentLifecycle
if *v == nil {
sv = &types.EnvironmentLifecycle{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "failureResource":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.FailureResource = ptr.String(jtv)
}
case "reason":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.Reason = ptr.String(jtv)
}
case "status":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected EnvironmentLifecycleStatus to be of type string, got %T instead", value)
}
sv.Status = types.EnvironmentLifecycleStatus(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentEnvironmentList(v *[]types.Environment, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []types.Environment
if *v == nil {
cv = []types.Environment{}
} else {
cv = *v
}
for _, value := range shape {
var col types.Environment
destAddr := &col
if err := awsAwsjson11_deserializeDocumentEnvironment(&destAddr, value); err != nil {
return err
}
col = *destAddr
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeDocumentEnvironmentMember(v **types.EnvironmentMember, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.EnvironmentMember
if *v == nil {
sv = &types.EnvironmentMember{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "environmentId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected EnvironmentId to be of type string, got %T instead", value)
}
sv.EnvironmentId = ptr.String(jtv)
}
case "lastAccess":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected Timestamp to be json.Number, got %T instead", value)
}
f64, err := jtv.Float64()
if err != nil {
return err
}
sv.LastAccess = ptr.Time(smithytime.ParseEpochSeconds(f64))
}
case "permissions":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected Permissions to be of type string, got %T instead", value)
}
sv.Permissions = types.Permissions(jtv)
}
case "userArn":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected UserArn to be of type string, got %T instead", value)
}
sv.UserArn = ptr.String(jtv)
}
case "userId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.UserId = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentEnvironmentMembersList(v *[]types.EnvironmentMember, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []types.EnvironmentMember
if *v == nil {
cv = []types.EnvironmentMember{}
} else {
cv = *v
}
for _, value := range shape {
var col types.EnvironmentMember
destAddr := &col
if err := awsAwsjson11_deserializeDocumentEnvironmentMember(&destAddr, value); err != nil {
return err
}
col = *destAddr
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeDocumentForbiddenException(v **types.ForbiddenException, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.ForbiddenException
if *v == nil {
sv = &types.ForbiddenException{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "className":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.ClassName = ptr.String(jtv)
}
case "code":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected Integer to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Code = int32(i64)
}
case "message":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.Message = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentInternalServerErrorException(v **types.InternalServerErrorException, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.InternalServerErrorException
if *v == nil {
sv = &types.InternalServerErrorException{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "className":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.ClassName = ptr.String(jtv)
}
case "code":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected Integer to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Code = int32(i64)
}
case "message":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.Message = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentLimitExceededException(v **types.LimitExceededException, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.LimitExceededException
if *v == nil {
sv = &types.LimitExceededException{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "className":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.ClassName = ptr.String(jtv)
}
case "code":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected Integer to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Code = int32(i64)
}
case "message":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.Message = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentNotFoundException(v **types.NotFoundException, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.NotFoundException
if *v == nil {
sv = &types.NotFoundException{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "className":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.ClassName = ptr.String(jtv)
}
case "code":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected Integer to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Code = int32(i64)
}
case "message":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.Message = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentTag(v **types.Tag, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.Tag
if *v == nil {
sv = &types.Tag{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "Key":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected TagKey to be of type string, got %T instead", value)
}
sv.Key = ptr.String(jtv)
}
case "Value":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected TagValue to be of type string, got %T instead", value)
}
sv.Value = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeDocumentTagList(v *[]types.Tag, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.([]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var cv []types.Tag
if *v == nil {
cv = []types.Tag{}
} else {
cv = *v
}
for _, value := range shape {
var col types.Tag
destAddr := &col
if err := awsAwsjson11_deserializeDocumentTag(&destAddr, value); err != nil {
return err
}
col = *destAddr
cv = append(cv, col)
}
*v = cv
return nil
}
func awsAwsjson11_deserializeDocumentTooManyRequestsException(v **types.TooManyRequestsException, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *types.TooManyRequestsException
if *v == nil {
sv = &types.TooManyRequestsException{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "className":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.ClassName = ptr.String(jtv)
}
case "code":
if value != nil {
jtv, ok := value.(json.Number)
if !ok {
return fmt.Errorf("expected Integer to be json.Number, got %T instead", value)
}
i64, err := jtv.Int64()
if err != nil {
return err
}
sv.Code = int32(i64)
}
case "message":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.Message = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentCreateEnvironmentEC2Output(v **CreateEnvironmentEC2Output, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *CreateEnvironmentEC2Output
if *v == nil {
sv = &CreateEnvironmentEC2Output{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "environmentId":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected EnvironmentId to be of type string, got %T instead", value)
}
sv.EnvironmentId = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentCreateEnvironmentMembershipOutput(v **CreateEnvironmentMembershipOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *CreateEnvironmentMembershipOutput
if *v == nil {
sv = &CreateEnvironmentMembershipOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "membership":
if err := awsAwsjson11_deserializeDocumentEnvironmentMember(&sv.Membership, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDeleteEnvironmentMembershipOutput(v **DeleteEnvironmentMembershipOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DeleteEnvironmentMembershipOutput
if *v == nil {
sv = &DeleteEnvironmentMembershipOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDeleteEnvironmentOutput(v **DeleteEnvironmentOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DeleteEnvironmentOutput
if *v == nil {
sv = &DeleteEnvironmentOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDescribeEnvironmentMembershipsOutput(v **DescribeEnvironmentMembershipsOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DescribeEnvironmentMembershipsOutput
if *v == nil {
sv = &DescribeEnvironmentMembershipsOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "memberships":
if err := awsAwsjson11_deserializeDocumentEnvironmentMembersList(&sv.Memberships, value); err != nil {
return err
}
case "nextToken":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.NextToken = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDescribeEnvironmentsOutput(v **DescribeEnvironmentsOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DescribeEnvironmentsOutput
if *v == nil {
sv = &DescribeEnvironmentsOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "environments":
if err := awsAwsjson11_deserializeDocumentEnvironmentList(&sv.Environments, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentDescribeEnvironmentStatusOutput(v **DescribeEnvironmentStatusOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *DescribeEnvironmentStatusOutput
if *v == nil {
sv = &DescribeEnvironmentStatusOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "message":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.Message = ptr.String(jtv)
}
case "status":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected EnvironmentStatus to be of type string, got %T instead", value)
}
sv.Status = types.EnvironmentStatus(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentListEnvironmentsOutput(v **ListEnvironmentsOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *ListEnvironmentsOutput
if *v == nil {
sv = &ListEnvironmentsOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "environmentIds":
if err := awsAwsjson11_deserializeDocumentEnvironmentIdList(&sv.EnvironmentIds, value); err != nil {
return err
}
case "nextToken":
if value != nil {
jtv, ok := value.(string)
if !ok {
return fmt.Errorf("expected String to be of type string, got %T instead", value)
}
sv.NextToken = ptr.String(jtv)
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentListTagsForResourceOutput(v **ListTagsForResourceOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *ListTagsForResourceOutput
if *v == nil {
sv = &ListTagsForResourceOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "Tags":
if err := awsAwsjson11_deserializeDocumentTagList(&sv.Tags, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentTagResourceOutput(v **TagResourceOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *TagResourceOutput
if *v == nil {
sv = &TagResourceOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentUntagResourceOutput(v **UntagResourceOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *UntagResourceOutput
if *v == nil {
sv = &UntagResourceOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentUpdateEnvironmentMembershipOutput(v **UpdateEnvironmentMembershipOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *UpdateEnvironmentMembershipOutput
if *v == nil {
sv = &UpdateEnvironmentMembershipOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
case "membership":
if err := awsAwsjson11_deserializeDocumentEnvironmentMember(&sv.Membership, value); err != nil {
return err
}
default:
_, _ = key, value
}
}
*v = sv
return nil
}
func awsAwsjson11_deserializeOpDocumentUpdateEnvironmentOutput(v **UpdateEnvironmentOutput, value interface{}) error {
if v == nil {
return fmt.Errorf("unexpected nil of type %T", v)
}
if value == nil {
return nil
}
shape, ok := value.(map[string]interface{})
if !ok {
return fmt.Errorf("unexpected JSON type %v", value)
}
var sv *UpdateEnvironmentOutput
if *v == nil {
sv = &UpdateEnvironmentOutput{}
} else {
sv = *v
}
for key, value := range shape {
switch key {
default:
_, _ = key, value
}
}
*v = sv
return nil
}
| awsAwsjson11_deserializeOpErrorCreateEnvironmentMembership |
mail.ts | import {Email, Mailbox} from '../models/mail';
import {Observable} from 'rxjs/Rx';
import {DatabaseService} from './db';
import {IStorageService} from './istorage';
import {ParsedMail} from '../models/parsedmail';
export class | {
constructor (
private storage: IStorageService,
private db: DatabaseService
) {}
saveMail(to: string[], mail: ParsedMail): Observable<any> {
// Save contents to Storage service
return this.storage.save(mail)
.flatMap(
location => {
// Save Storage link to DB with Subject, DT, From
const emailQuery = 'INSERT INTO `emails` (`Location`, `Subject`, `From`) VALUES (?, ?, ?);';
return this.db.query(emailQuery, [location, mail.subject, mail.from.address])
.map(result => result.insertId);
}
)
.flatMap(
emailId => {
// Save Each "to" mapped to Email ID in Emails_To
const emailMap = to.map(t => [t, emailId]);
const mapQ = 'INSERT INTO `emails_to` (`To`, `EmailId`) VALUES ' + this.db.escape(emailMap) + ';';
return this.db.query(mapQ, emailMap);
}
);
}
getMailboxes(page?: number): Observable<Mailbox[]> {
let q = 'Select `to` as mailbox, Count(*) as messageCount, Max(`CreatedDate`) as latestMessage \
from `emails_to` \
Group By mailbox \
ORDER BY latestMessage DESC';
if (page) {
q += this.db.generatePageQuery(page);
}
q += ';';
return this.db.query(q);
}
searchMailboxes(query: string, page?: number): Observable<Mailbox[]> {
let q = 'Select `to` as mailbox, Count(*) as messageCount, Max(`CreatedDate`) as latestMessage \
from `emails_to` \
Where `to` like ? \
Group By mailbox \
ORDER BY latestMessage DESC';
if (page) {
q += this.db.generatePageQuery(page);
}
q += ';';
return this.db.query(q, [`%${query}%`]);
}
getMailbox(mailbox: string, page?: number): Observable<Email[]> {
let q = 'Select `emails`.* from `emails_to` \
join `emails` on `emails`.`EmailId`=`emails_to`.`EmailId` \
Where `To` = ? \
ORDER BY `CreatedDate` DESC';
if (page) {
q += this.db.generatePageQuery(page);
}
q += ';';
return this.db.query(q, [mailbox]);
}
getAllMail(page?: number): Observable<Email[]> {
let q = 'Select * from `emails` ORDER BY `CreatedDate` DESC';
if (page) {
q += this.db.generatePageQuery(page);
}
q += ';';
return this.db.query(q);
}
getMail(emailId: number): Observable<ParsedMail> {
const q = 'Select * from `emails` Where `EmailId`=? LIMIT 1;';
return this.db.query(q, emailId)
.flatMap(
emails => {
if (emails.length < 1) {
return Observable.throw(404);
} else {
const email = emails[0];
return this.storage.retrieve(email.Location);
}
}
);
}
}
| MailService |
test_domains.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import uuid
from keystoneclient.tests.v3 import utils
from keystoneclient.v3 import domains
class DomainTests(utils.TestCase, utils.CrudTests):
| def setUp(self):
super(DomainTests, self).setUp()
self.key = 'domain'
self.collection_key = 'domains'
self.model = domains.Domain
self.manager = self.client.domains
def new_ref(self, **kwargs):
kwargs = super(DomainTests, self).new_ref(**kwargs)
kwargs.setdefault('enabled', True)
kwargs.setdefault('name', uuid.uuid4().hex)
return kwargs |
|
icon_tv.rs | pub struct IconTv {
props: crate::Props,
}
impl yew::Component for IconTv {
type Properties = crate::Props;
type Message = ();
fn create(props: Self::Properties, _: yew::prelude::ComponentLink<Self>) -> Self
{
Self { props }
}
fn update(&mut self, _: Self::Message) -> yew::prelude::ShouldRender
{
true
}
fn change(&mut self, _: Self::Properties) -> yew::prelude::ShouldRender
{
false
} | {
yew::prelude::html! {
<svg
class=self.props.class.unwrap_or("")
width=self.props.size.unwrap_or(24).to_string()
height=self.props.size.unwrap_or(24).to_string()
viewBox="0 0 24 24"
fill=self.props.fill.unwrap_or("none")
stroke=self.props.color.unwrap_or("currentColor")
stroke-width=self.props.stroke_width.unwrap_or(2).to_string()
stroke-linecap=self.props.stroke_linecap.unwrap_or("round")
stroke-linejoin=self.props.stroke_linejoin.unwrap_or("round")
>
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0z" fill="none"/><path d="M21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.1-.9-2-2-2zm0 14H3V5h18v12z"/></svg>
</svg>
}
}
} |
fn view(&self) -> yew::prelude::Html |
browser.js | !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.to5=e()}}(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){(function(global){"use strict";var transform=module.exports=require("./transformation/transform");transform.version=require("../../package").version;transform.transform=transform;transform.run=function(code,opts){opts=opts||{};opts.sourceMap="inline";return new Function(transform(code,opts).code)()};transform.load=function(url,callback,opts,hold){opts=opts||{};opts.filename=opts.filename||url;var xhr=global.ActiveXObject?new global.ActiveXObject("Microsoft.XMLHTTP"):new global.XMLHttpRequest;xhr.open("GET",url,true);if("overrideMimeType"in xhr)xhr.overrideMimeType("text/plain");xhr.onreadystatechange=function(){if(xhr.readyState!==4)return;var status=xhr.status;if(status===0||status===200){var param=[xhr.responseText,opts];if(!hold)transform.run.apply(transform,param);if(callback)callback(param)}else{throw new Error("Could not load "+url)}};xhr.send(null)};var runScripts=function(){var scripts=[];var types=["text/ecmascript-6","text/6to5","module"];var index=0;var exec=function(){var param=scripts[index];if(param instanceof Array){transform.run.apply(transform,param);index++;exec()}};var run=function(script,i){var opts={};if(script.src){transform.load(script.src,function(param){scripts[i]=param;exec()},opts,true)}else{opts.filename="embedded";scripts[i]=[script.innerHTML,opts]}};var _scripts=global.document.getElementsByTagName("script");for(var i=0;i<_scripts.length;++i){var _script=_scripts[i];if(types.indexOf(_script.type)>=0)scripts.push(_script)}for(i in scripts){run(scripts[i],i)}exec()};if(global.addEventListener){global.addEventListener("DOMContentLoaded",runScripts,false)}else if(global.attachEvent){global.attachEvent("onload",runScripts)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../package":193,"./transformation/transform":47}],2:[function(require,module,exports){"use strict";module.exports=File;var SHEBANG_REGEX=/^\#\!.*/;var transform=require("./transformation/transform");var generate=require("./generation/generator");var clone=require("./helpers/clone");var Scope=require("./traverse/scope");var util=require("./util");var t=require("./types");var _=require("lodash");function File(opts){this.dynamicImportIds={};this.dynamicImported=[];this.dynamicImports=[];this.dynamicData={};this.data={};this.lastStatements=[];this.opts=File.normaliseOptions(opts);this.ast={};this.buildTransformers()}File.helpers=["inherits","defaults","prototype-properties","apply-constructor","tagged-template-literal","tagged-template-literal-loose","interop-require","to-array","sliced-to-array","object-without-properties","has-own","slice","bind","define-property","async-to-generator","interop-require-wildcard","typeof","extends","get"];File.validOptions=["filename","filenameRelative","blacklist","whitelist","loose","optional","modules","sourceMap","sourceMapName","sourceFileName","sourceRoot","moduleRoot","moduleIds","comments","reactCompat","keepModuleIdExtensions","code","ast","format","playground","experimental"];File.normaliseOptions=function(opts){opts=clone(opts);for(var key in opts){if(File.validOptions.indexOf(key)<0){throw new ReferenceError("Unknown option: "+key)}}_.defaults(opts,{keepModuleIdExtensions:false,experimental:false,reactCompat:false,playground:false,whitespace:true,moduleIds:false,blacklist:[],whitelist:[],sourceMap:false,optional:[],comments:true,filename:"unknown",modules:"common",loose:[],code:true,ast:true});opts.filename=opts.filename.replace(/\\/g,"/");opts.blacklist=util.arrayify(opts.blacklist);opts.whitelist=util.arrayify(opts.whitelist);opts.optional=util.arrayify(opts.optional);opts.loose=util.arrayify(opts.loose);if(_.contains(opts.loose,"all")){opts.loose=Object.keys(transform.transformers)}_.defaults(opts,{moduleRoot:opts.sourceRoot});_.defaults(opts,{sourceRoot:opts.moduleRoot});_.defaults(opts,{filenameRelative:opts.filename});_.defaults(opts,{sourceFileName:opts.filenameRelative,sourceMapName:opts.filenameRelative});if(opts.playground){opts.experimental=true}opts.blacklist=transform._ensureTransformerNames("blacklist",opts.blacklist);opts.whitelist=transform._ensureTransformerNames("whitelist",opts.whitelist);opts.optional=transform._ensureTransformerNames("optional",opts.optional);opts.loose=transform._ensureTransformerNames("loose",opts.loose);return opts};File.prototype.isLoose=function(key){return _.contains(this.opts.loose,key)};File.prototype.buildTransformers=function(){var file=this;var transformers={};var secondaryStack=[];var stack=[];_.each(transform.transformers,function(transformer,key){var pass=transformers[key]=transformer.buildPass(file);if(pass.canRun(file)){stack.push(pass);if(transformer.secondPass){secondaryStack.push(pass)}if(transformer.manipulateOptions){transformer.manipulateOptions(file.opts,file)}}});this.transformerStack=stack.concat(secondaryStack);this.transformers=transformers};File.prototype.toArray=function(node,i){if(t.isArrayExpression(node)){return node}else if(t.isIdentifier(node)&&node.name==="arguments"){return t.callExpression(t.memberExpression(this.addHelper("slice"),t.identifier("call")),[node])}else{var declarationName="to-array";var args=[node];if(i){args.push(t.literal(i));declarationName="sliced-to-array"}return t.callExpression(this.addHelper(declarationName),args)}};File.prototype.getModuleFormatter=function(type){var ModuleFormatter=_.isFunction(type)?type:transform.moduleFormatters[type];if(!ModuleFormatter){var loc=util.resolve(type);if(loc)ModuleFormatter=require(loc)}if(!ModuleFormatter){throw new ReferenceError("Unknown module formatter type "+JSON.stringify(type))}return new ModuleFormatter(this)};File.prototype.parseShebang=function(code){var shebangMatch=code.match(SHEBANG_REGEX);if(shebangMatch){this.shebang=shebangMatch[0];code=code.replace(SHEBANG_REGEX,"")}return code};File.prototype.set=function(key,val){return this.data[key]=val};File.prototype.setDynamic=function(key,fn){this.dynamicData[key]=fn};File.prototype.get=function(key){var data=this.data[key];if(data){return data}else{var dynamic=this.dynamicData[key];if(dynamic){return this.set(key,dynamic())}}};File.prototype.addImport=function(source,name){name=name||source;var id=this.dynamicImportIds[name];if(!id){id=this.dynamicImportIds[name]=this.generateUidIdentifier(name);var specifiers=[t.importSpecifier(t.identifier("default"),id)];var declar=t.importDeclaration(specifiers,t.literal(source));declar._blockHoist=3;this.dynamicImported.push(declar);this.moduleFormatter.importSpecifier(specifiers[0],declar,this.dynamicImports)}return id};File.prototype.isConsequenceExpressionStatement=function(node){return t.isExpressionStatement(node)&&this.lastStatements.indexOf(node)>=0};File.prototype.addHelper=function(name){if(!_.contains(File.helpers,name)){throw new ReferenceError("unknown declaration "+name)}var program=this.ast.program;var declar=program._declarations&&program._declarations[name];if(declar)return declar.id;var runtime=this.get("runtimeIdentifier");if(runtime){name=t.identifier(t.toIdentifier(name));return t.memberExpression(runtime,name)}else{var ref=util.template(name);ref._compact=true;var uid=this.generateUidIdentifier(name);this.scope.push({key:name,id:uid,init:ref});return uid}};File.prototype.errorWithNode=function(node,msg,Error){Error=Error||SyntaxError;var loc=node.loc.start;var err=new Error("Line "+loc.line+": "+msg);err.loc=loc;return err};File.prototype.addCode=function(code){code=(code||"")+"";this.code=code;return this.parseShebang(code)};File.prototype.parse=function(code){var self=this;code=this.addCode(code);var opts=this.opts;opts.allowImportExportEverywhere=this.isLoose("modules");return util.parse(opts,code,function(tree){self.transform(tree);return self.generate()})};File.prototype.transform=function(ast){var self=this;this.ast=ast;this.lastStatements=t.getLastStatements(ast.program);this.scope=new Scope(ast.program,null,this);this.moduleFormatter=this.getModuleFormatter(this.opts.modules);var astRun=function(key){_.each(self.transformerStack,function(pass){pass.astRun(key)})};astRun("enter");_.each(this.transformerStack,function(pass){pass.transform()});astRun("exit")};File.prototype.generate=function(){var opts=this.opts;var ast=this.ast;var result={code:"",opts:opts,map:null,ast:null};if(opts.ast)result.ast=ast;if(!opts.code)return result;var _result=generate(ast,opts,this.code);result.code=_result.code;result.map=_result.map;if(this.shebang){result.code=this.shebang+"\n"+result.code}if(opts.sourceMap==="inline"){result.code+="\n"+util.sourceMapToComment(result.map)}return result};File.prototype.generateUid=function(name,scope){name=t.toIdentifier(name).replace(/^_+/,"");scope=scope||this.scope;var uid;var i=0;do{uid=this._generateUid(name,i);i++}while(scope.has(uid));return uid};File.prototype.generateUidIdentifier=function(name,scope){scope=scope||this.scope;var id=t.identifier(this.generateUid(name,scope));scope.add(id);return id};File.prototype._generateUid=function(name,i){var id=name;if(i>1)id+=i;return"_"+id}},{"./generation/generator":4,"./helpers/clone":23,"./transformation/transform":47,"./traverse/scope":98,"./types":101,"./util":104,lodash:164}],3:[function(require,module,exports){"use strict";module.exports=Buffer;var util=require("../util");var _=require("lodash");function Buffer(position,format){this.position=position;this._indent=format.indent.base;this.format=format;this.buf=""}Buffer.prototype.get=function(){return util.trimRight(this.buf)};Buffer.prototype.getIndent=function(){if(this.format.compact){return""}else{return util.repeat(this._indent,this.format.indent.style)}};Buffer.prototype.indentSize=function(){return this.getIndent().length};Buffer.prototype.indent=function(){this._indent++};Buffer.prototype.dedent=function(){this._indent--};Buffer.prototype.semicolon=function(){this.push(";")};Buffer.prototype.ensureSemicolon=function(){if(!this.isLast(";"))this.semicolon()};Buffer.prototype.rightBrace=function(){this.newline(true);this.push("}")};Buffer.prototype.keyword=function(name){this.push(name);this.push(" ")};Buffer.prototype.space=function(){if(this.buf&&!this.isLast([" ","\n"])){this.push(" ")}};Buffer.prototype.removeLast=function(cha){if(!this.isLast(cha))return;this.buf=this.buf.substr(0,this.buf.length-1);this.position.unshift(cha)};Buffer.prototype.newline=function(i,removeLast){if(this.format.compact){this.space();return}removeLast=removeLast||false;if(_.isNumber(i)){if(this.endsWith("{\n"))i--;if(this.endsWith(util.repeat(i,"\n")))return;while(i--){this._newline(removeLast)}return}if(_.isBoolean(i)){removeLast=i}this._newline(removeLast)};Buffer.prototype._newline=function(removeLast){if(removeLast&&this.isLast("\n"))this.removeLast("\n");this.removeLast(" ");this._removeSpacesAfterLastNewline();this._push("\n")};Buffer.prototype._removeSpacesAfterLastNewline=function(){var lastNewlineIndex=this.buf.lastIndexOf("\n");if(lastNewlineIndex===-1)return;var index=this.buf.length-1;while(index>lastNewlineIndex){if(this.buf[index]!==" "){break}index--}if(index===lastNewlineIndex){this.buf=this.buf.substring(0,index+1)}};Buffer.prototype.push=function(str,noIndent){if(this._indent&&!noIndent&&str!=="\n"){var indent=this.getIndent();str=str.replace(/\n/g,"\n"+indent);if(this.isLast("\n"))str=indent+str}this._push(str)};Buffer.prototype._push=function(str){this.position.push(str);this.buf+=str};Buffer.prototype.endsWith=function(str){var d=this.buf.length-str.length;return d>=0&&this.buf.lastIndexOf(str)===d};Buffer.prototype.isLast=function(cha,trimRight){var buf=this.buf;if(trimRight)buf=util.trimRight(buf);var last=buf[buf.length-1];if(Array.isArray(cha)){return _.contains(cha,last)}else{return cha===last}}},{"../util":104,lodash:164}],4:[function(require,module,exports){"use strict";module.exports=function(ast,opts,code){var gen=new CodeGenerator(ast,opts,code);return gen.generate()};module.exports.CodeGenerator=CodeGenerator;var detectIndent=require("detect-indent");var Whitespace=require("./whitespace");var SourceMap=require("./source-map");var Position=require("./position");var Buffer=require("./buffer");var util=require("../util");var n=require("./node");var t=require("../types");var _=require("lodash");function CodeGenerator(ast,opts,code){opts=opts||{};this.comments=ast.comments||[];this.tokens=ast.tokens||[];this.format=CodeGenerator.normaliseOptions(code,opts);this.ast=ast;this.whitespace=new Whitespace(this.tokens,this.comments);this.position=new Position;this.map=new SourceMap(this.position,opts,code);this.buffer=new Buffer(this.position,this.format)}_.each(Buffer.prototype,function(fn,key){CodeGenerator.prototype[key]=function(){return fn.apply(this.buffer,arguments)}});CodeGenerator.normaliseOptions=function(code,opts){var indent=detectIndent(code);var style=indent.indent;if(!style||style===" ")style=" ";return _.merge({parentheses:true,comments:opts.comments==null||opts.comments,compact:false,indent:{adjustMultilineComment:true,style:style,base:0}},opts.format||{})};CodeGenerator.generators={templateLiterals:require("./generators/template-literals"),comprehensions:require("./generators/comprehensions"),expressions:require("./generators/expressions"),statements:require("./generators/statements"),playground:require("./generators/playground"),classes:require("./generators/classes"),methods:require("./generators/methods"),modules:require("./generators/modules"),types:require("./generators/types"),flow:require("./generators/flow"),base:require("./generators/base"),jsx:require("./generators/jsx")};_.each(CodeGenerator.generators,function(generator){_.extend(CodeGenerator.prototype,generator)});CodeGenerator.prototype.generate=function(){var ast=this.ast;this.print(ast);var comments=[];_.each(ast.comments,function(comment){if(!comment._displayed)comments.push(comment)});this._printComments(comments);return{map:this.map.get(),code:this.buffer.get()}};CodeGenerator.prototype.buildPrint=function(parent){var self=this;var print=function(node,opts){return self.print(node,parent,opts)};print.sequence=function(nodes,opts){opts=opts||{};opts.statement=true;return self.printJoin(print,nodes,opts)};print.join=function(nodes,opts){return self.printJoin(print,nodes,opts)};print.block=function(node){return self.printBlock(print,node)};print.indentOnComments=function(node){return self.printAndIndentOnComments(print,node)};return print};CodeGenerator.prototype.print=function(node,parent,opts){if(!node)return"";if(parent&&parent._compact){node._compact=true}var oldCompact=this.format.compact;if(node._compact){this.format.compact=true}var self=this;opts=opts||{};var newline=function(leading){if(!opts.statement&&!n.isUserWhitespacable(node,parent)){return}var lines=0;if(node.start!=null&&!node._ignoreUserWhitespace){if(leading){lines=self.whitespace.getNewlinesBefore(node)}else{lines=self.whitespace.getNewlinesAfter(node)}}else{if(!leading)lines++;var needs=n.needsWhitespaceAfter;if(leading)needs=n.needsWhitespaceBefore;lines+=needs(node,parent);if(!self.buffer.get())lines=0}self.newline(lines)};if(this[node.type]){var needsNoLineTermParens=n.needsParensNoLineTerminator(node,parent);var needsParens=needsNoLineTermParens||n.needsParens(node,parent);if(needsParens)this.push("(");if(needsNoLineTermParens)this.indent();this.printLeadingComments(node,parent);newline(true);if(opts.before)opts.before();this.map.mark(node,"start");this[node.type](node,this.buildPrint(node),parent);if(needsNoLineTermParens){this.newline();this.dedent()}if(needsParens)this.push(")");this.map.mark(node,"end");if(opts.after)opts.after();newline(false);this.printTrailingComments(node,parent)}else{throw new ReferenceError("unknown node of type "+JSON.stringify(node.type)+" with constructor "+JSON.stringify(node&&node.constructor.name))}this.format.compact=oldCompact};CodeGenerator.prototype.printJoin=function(print,nodes,opts){if(!nodes||!nodes.length)return;opts=opts||{};var self=this;var len=nodes.length;if(opts.indent)self.indent();_.each(nodes,function(node,i){print(node,{statement:opts.statement,after:function(){if(opts.iterator){opts.iterator(node,i)}if(opts.separator&&i<len-1){self.push(opts.separator)}}})});if(opts.indent)self.dedent()};CodeGenerator.prototype.printAndIndentOnComments=function(print,node){var indent=!!node.leadingComments;if(indent)this.indent();print(node);if(indent)this.dedent()};CodeGenerator.prototype.printBlock=function(print,node){if(t.isEmptyStatement(node)){this.semicolon()}else{this.push(" ");print(node)}};CodeGenerator.prototype.generateComment=function(comment){var val=comment.value;if(comment.type==="Line"){val="//"+val}else{val="/*"+val+"*/"}return val};CodeGenerator.prototype.printTrailingComments=function(node,parent){this._printComments(this.getComments("trailingComments",node,parent))};CodeGenerator.prototype.printLeadingComments=function(node,parent){this._printComments(this.getComments("leadingComments",node,parent))};CodeGenerator.prototype.getComments=function(key,node,parent){if(t.isExpressionStatement(parent)){return[]}var comments=[];var nodes=[node];var self=this;if(t.isExpressionStatement(node)){nodes.push(node.argument)}_.each(nodes,function(node){comments=comments.concat(self._getComments(key,node))});return comments};CodeGenerator.prototype._getComments=function(key,node){return node&&node[key]||[]};CodeGenerator.prototype._printComments=function(comments){if(this.format.compact)return;if(!this.format.comments)return;if(!comments||!comments.length)return;var self=this;_.each(comments,function(comment){var skip=false;_.each(self.ast.comments,function(origComment){if(origComment.start===comment.start){if(origComment._displayed)skip=true;origComment._displayed=true;return false}});if(skip)return;self.newline(self.whitespace.getNewlinesBefore(comment));var column=self.position.column;var val=self.generateComment(comment);if(column&&!self.isLast(["\n"," ","[","{"])){self._push(" ");column++}if(comment.type==="Block"&&self.format.indent.adjustMultilineComment){var offset=comment.loc.start.column;if(offset){var newlineRegex=new RegExp("\\n\\s{1,"+offset+"}","g");val=val.replace(newlineRegex,"\n")}var indent=Math.max(self.indentSize(),column);val=val.replace(/\n/g,"\n"+util.repeat(indent))}if(column===0){val=self.getIndent()+val}self._push(val);self.newline(self.whitespace.getNewlinesAfter(comment))})}},{"../types":101,"../util":104,"./buffer":3,"./generators/base":5,"./generators/classes":6,"./generators/comprehensions":7,"./generators/expressions":8,"./generators/flow":9,"./generators/jsx":10,"./generators/methods":11,"./generators/modules":12,"./generators/playground":13,"./generators/statements":14,"./generators/template-literals":15,"./generators/types":16,"./node":17,"./position":20,"./source-map":21,"./whitespace":22,"detect-indent":155,lodash:164}],5:[function(require,module,exports){"use strict";exports.File=function(node,print){print(node.program)};exports.Program=function(node,print){print.sequence(node.body)};exports.BlockStatement=function(node,print){if(node.body.length===0){this.push("{}")}else{this.push("{");this.newline();print.sequence(node.body,{indent:true});this.removeLast("\n");this.rightBrace()}}},{}],6:[function(require,module,exports){"use strict";exports.ClassExpression=exports.ClassDeclaration=function(node,print){this.push("class");if(node.id){this.space();print(node.id)}if(node.superClass){this.push(" extends ");print(node.superClass)}this.space();print(node.body)};exports.ClassBody=function(node,print){if(node.body.length===0){this.push("{}")}else{this.push("{");this.newline();this.indent();print.sequence(node.body);this.dedent();this.rightBrace()}};exports.MethodDefinition=function(node,print){if(node.static){this.push("static ")}this._method(node,print)}},{}],7:[function(require,module,exports){"use strict";exports.ComprehensionBlock=function(node,print){this.keyword("for");this.push("(");print(node.left);this.push(" of ");print(node.right);this.push(")")};exports.ComprehensionExpression=function(node,print){this.push(node.generator?"(":"[");print.join(node.blocks,{separator:" "});this.space();if(node.filter){this.keyword("if");this.push("(");print(node.filter);this.push(")");this.space()}print(node.body);this.push(node.generator?")":"]")}},{}],8:[function(require,module,exports){"use strict";var util=require("../../util");var t=require("../../types");var _=require("lodash");exports.UnaryExpression=function(node,print){var hasSpace=/[a-z]$/.test(node.operator);var arg=node.argument;if(t.isUpdateExpression(arg)||t.isUnaryExpression(arg)){hasSpace=true}if(t.isUnaryExpression(arg)&&arg.operator==="!"){hasSpace=false}this.push(node.operator);if(hasSpace)this.space();print(node.argument)};exports.UpdateExpression=function(node,print){if(node.prefix){this.push(node.operator);print(node.argument)}else{print(node.argument);this.push(node.operator)}};exports.ConditionalExpression=function(node,print){print(node.test);this.push(" ? ");print(node.consequent);this.push(" : ");print(node.alternate)};exports.NewExpression=function(node,print){this.push("new ");print(node.callee);if(node.arguments.length||this.format.parentheses){this.push("(");print.join(node.arguments,{separator:", "});this.push(")")}};exports.SequenceExpression=function(node,print){print.join(node.expressions,{separator:", "})};exports.ThisExpression=function(){this.push("this")};exports.CallExpression=function(node,print){print(node.callee);this.push("(");var separator=",";if(node._prettyCall){separator+="\n";this.newline();this.indent()}else{separator+=" "}print.join(node.arguments,{separator:separator});if(node._prettyCall){this.newline();this.dedent()}this.push(")")};var buildYieldAwait=function(keyword){return function(node,print){this.push(keyword);if(node.delegate)this.push("*");if(node.argument){this.space();print(node.argument)}}};exports.YieldExpression=buildYieldAwait("yield");exports.AwaitExpression=buildYieldAwait("await");exports.EmptyStatement=function(){this.semicolon()};exports.ExpressionStatement=function(node,print){print(node.expression);this.semicolon()};exports.BinaryExpression=exports.LogicalExpression=exports.AssignmentPattern=exports.AssignmentExpression=function(node,print){print(node.left);this.space();this.push(node.operator);this.space();print(node.right)};var SCIENTIFIC_NOTATION=/e/i;exports.MemberExpression=function(node,print){var obj=node.object;print(obj);if(!node.computed&&t.isMemberExpression(node.property)){throw new TypeError("Got a MemberExpression for MemberExpression property")}var computed=node.computed;if(t.isLiteral(node.property)&&_.isNumber(node.property.value)){computed=true}if(computed){this.push("[");print(node.property);this.push("]")}else{if(t.isLiteral(obj)&&util.isInteger(obj.value)&&!SCIENTIFIC_NOTATION.test(obj.value.toString())){this.push(".")}this.push(".");print(node.property)}}},{"../../types":101,"../../util":104,lodash:164}],9:[function(require,module,exports){"use strict";exports.AnyTypeAnnotation=exports.ArrayTypeAnnotation=exports.BooleanTypeAnnotation=exports.ClassProperty=exports.DeclareClass=exports.DeclareFunction=exports.DeclareModule=exports.DeclareVariable=exports.FunctionTypeAnnotation=exports.FunctionTypeParam=exports.GenericTypeAnnotation=exports.InterfaceExtends=exports.InterfaceDeclaration=exports.IntersectionTypeAnnotation=exports.NullableTypeAnnotation=exports.NumberTypeAnnotation=exports.StringLiteralTypeAnnotation=exports.StringTypeAnnotation=exports.TupleTypeAnnotation=exports.TypeofTypeAnnotation=exports.TypeAlias=exports.TypeAnnotation=exports.TypeParameterDeclaration=exports.TypeParameterInstantiation=exports.ObjectTypeAnnotation=exports.ObjectTypeCallProperty=exports.ObjectTypeIndexer=exports.ObjectTypeProperty=exports.QualifiedTypeIdentifier=exports.UnionTypeAnnotation=exports.VoidTypeAnnotation=function(){}},{}],10:[function(require,module,exports){"use strict";var t=require("../../types");var _=require("lodash");exports.JSXAttribute=function(node,print){print(node.name);if(node.value){this.push("=");print(node.value)}};exports.JSXIdentifier=function(node){this.push(node.name)};exports.JSXNamespacedName=function(node,print){print(node.namespace);this.push(":");print(node.name)};exports.JSXMemberExpression=function(node,print){print(node.object);this.push(".");print(node.property)};exports.JSXSpreadAttribute=function(node,print){this.push("{...");print(node.argument);this.push("}")};exports.JSXExpressionContainer=function(node,print){this.push("{");print(node.expression);this.push("}")};exports.JSXElement=function(node,print){var self=this;var open=node.openingElement;print(open);if(open.selfClosing)return;this.indent();_.each(node.children,function(child){if(t.isLiteral(child)){self.push(child.value)}else{print(child)}});this.dedent();print(node.closingElement)};exports.JSXOpeningElement=function(node,print){this.push("<");print(node.name);if(node.attributes.length>0){this.push(" ");print.join(node.attributes,{separator:" "})}this.push(node.selfClosing?" />":">")};exports.JSXClosingElement=function(node,print){this.push("</");print(node.name);this.push(">")};exports.JSXEmptyExpression=function(){}},{"../../types":101,lodash:164}],11:[function(require,module,exports){"use strict";var t=require("../../types");exports._params=function(node,print){this.push("(");print.join(node.params,{separator:", "});this.push(")")};exports._method=function(node,print){var value=node.value;var kind=node.kind;var key=node.key;if(!kind||kind==="init"){if(value.generator){this.push("*")}}else{this.push(kind+" ")}if(value.async)this.push("async ");if(node.computed){this.push("[");print(key);this.push("]")}else{print(key)}this._params(value,print);this.push(" ");print(value.body)};exports.FunctionDeclaration=exports.FunctionExpression=function(node,print){if(node.async)this.push("async ");this.push("function");if(node.generator)this.push("*");this.push(" ");if(node.id){this.space();print(node.id)}this._params(node,print);this.space();print(node.body)};exports.ArrowFunctionExpression=function(node,print){if(node.async)this.push("async ");if(node.params.length===1&&t.isIdentifier(node.params[0])){print(node.params[0])}else{this._params(node,print)}this.push(" => ");print(node.body)}},{"../../types":101}],12:[function(require,module,exports){"use strict";var t=require("../../types");var _=require("lodash");exports.ImportSpecifier=function(node,print){if(t.isSpecifierDefault(node)){print(t.getSpecifierName(node))}else{return exports.ExportSpecifier.apply(this,arguments)}};exports.ExportSpecifier=function(node,print){print(node.id);if(node.name){this.push(" as ");print(node.name)}};exports.ExportBatchSpecifier=function(){this.push("*")};exports.ExportDeclaration=function(node,print){this.push("export ");var specifiers=node.specifiers;if(node.default){this.push("default ")}if(node.declaration){print(node.declaration);if(t.isStatement(node.declaration))return}else{if(specifiers.length===1&&t.isExportBatchSpecifier(specifiers[0])){print(specifiers[0])}else{this.push("{");if(specifiers.length){this.space();print.join(specifiers,{separator:", "});this.space()}this.push("}")}if(node.source){this.push(" from ");print(node.source)}}this.ensureSemicolon()};exports.ImportDeclaration=function(node,print){var self=this;this.push("import ");var specfiers=node.specifiers;if(specfiers&&specfiers.length){var foundImportSpecifier=false;_.each(node.specifiers,function(spec,i){if(+i>0){self.push(", ")}var isDefault=t.isSpecifierDefault(spec);if(!isDefault&&spec.type!=="ImportBatchSpecifier"&&!foundImportSpecifier){foundImportSpecifier=true;self.push("{ ")}print(spec)});if(foundImportSpecifier){this.push(" }")}this.push(" from ")}print(node.source);this.semicolon()};exports.ImportBatchSpecifier=function(node,print){this.push("* as ");print(node.name)}},{"../../types":101,lodash:164}],13:[function(require,module,exports){"use strict";var _=require("lodash");_.each(["BindMemberExpression","BindFunctionExpression"],function(type){exports[type]=function(){throw new ReferenceError("Trying to render non-standard playground node "+JSON.stringify(type))}})},{lodash:164}],14:[function(require,module,exports){"use strict";var util=require("../../util");var t=require("../../types");exports.WithStatement=function(node,print){this.keyword("with");this.push("(");print(node.object);this.push(")");print.block(node.body)};exports.IfStatement=function(node,print){this.keyword("if");this.push("(");print(node.test);this.push(")");this.space();print.indentOnComments(node.consequent);if(node.alternate){if(this.isLast("}"))this.push(" ");this.keyword("else");print.indentOnComments(node.alternate)}};exports.ForStatement=function(node,print){this.keyword("for");this.push("(");print(node.init);this.push(";");if(node.test){this.push(" ");print(node.test)}this.push(";");if(node.update){this.push(" ");print(node.update)}this.push(")");print.block(node.body)};exports.WhileStatement=function(node,print){this.keyword("while");this.push("(");print(node.test);this.push(")");print.block(node.body)};var buildForXStatement=function(op){return function(node,print){this.keyword("for");this.push("(");print(node.left);this.push(" "+op+" ");print(node.right);this.push(")");print.block(node.body)}};exports.ForInStatement=buildForXStatement("in");exports.ForOfStatement=buildForXStatement("of");exports.DoWhileStatement=function(node,print){this.keyword("do");print(node.body);this.space();this.keyword("while");this.push("(");print(node.test);this.push(");")};var buildLabelStatement=function(prefix,key){return function(node,print){this.push(prefix);var label=node[key||"label"];if(label){this.push(" ");print(label)}this.semicolon()}};exports.ContinueStatement=buildLabelStatement("continue");exports.ReturnStatement=buildLabelStatement("return","argument");exports.BreakStatement=buildLabelStatement("break");exports.LabeledStatement=function(node,print){print(node.label);this.push(": ");print(node.body)};exports.TryStatement=function(node,print){this.keyword("try");print(node.block);this.space();if(node.handlers){print(node.handlers[0])}else{print(node.handler)}if(node.finalizer){this.space();this.push("finally ");print(node.finalizer)}};exports.CatchClause=function(node,print){this.keyword("catch");this.push("(");print(node.param);this.push(") ");print(node.body)};exports.ThrowStatement=function(node,print){this.push("throw ");print(node.argument);this.semicolon()};exports.SwitchStatement=function(node,print){this.keyword("switch");this.push("(");print(node.discriminant);this.push(")");this.space();this.push("{");print.sequence(node.cases,{indent:true});this.push("}")};exports.SwitchCase=function(node,print){if(node.test){this.push("case ");print(node.test);this.push(":")}else{this.push("default:")}this.newline();print.sequence(node.consequent,{indent:true})};exports.DebuggerStatement=function(){this.push("debugger;")};exports.VariableDeclaration=function(node,print,parent){this.push(node.kind+" ");var hasInits=false;if(!t.isFor(parent)){for(var i=0;i<node.declarations.length;i++){if(node.declarations[i].init){hasInits=true}}}var sep=",";if(hasInits){sep+="\n"+util.repeat(node.kind.length+1)}else{sep+=" "}print.join(node.declarations,{separator:sep});
if(!t.isFor(parent)){this.semicolon()}};exports.PrivateDeclaration=function(node,print){this.push("private ");print.join(node.declarations,{separator:", "});this.semicolon()};exports.VariableDeclarator=function(node,print){if(node.init){print(node.id);this.space();this.push("=");this.space();print(node.init)}else{print(node.id)}}},{"../../types":101,"../../util":104}],15:[function(require,module,exports){"use strict";var _=require("lodash");exports.TaggedTemplateExpression=function(node,print){print(node.tag);print(node.quasi)};exports.TemplateElement=function(node){this._push(node.value.raw)};exports.TemplateLiteral=function(node,print){this.push("`");var quasis=node.quasis;var self=this;var len=quasis.length;_.each(quasis,function(quasi,i){print(quasi);if(i+1<len){self.push("${ ");print(node.expressions[i]);self.push(" }")}});this._push("`")}},{lodash:164}],16:[function(require,module,exports){"use strict";var _=require("lodash");exports.Identifier=function(node){this.push(node.name)};exports.RestElement=exports.SpreadElement=exports.SpreadProperty=function(node,print){this.push("...");print(node.argument)};exports.VirtualPropertyExpression=function(node,print){print(node.object);this.push("::");print(node.property)};exports.ObjectExpression=exports.ObjectPattern=function(node,print){var props=node.properties;if(props.length){this.push("{");this.space();print.join(props,{separator:", ",indent:true});this.space();this.push("}")}else{this.push("{}")}};exports.Property=function(node,print){if(node.method||node.kind==="get"||node.kind==="set"){this._method(node,print)}else{if(node.computed){this.push("[");print(node.key);this.push("]")}else{print(node.key);if(node.shorthand)return}this.push(": ");print(node.value)}};exports.ArrayExpression=exports.ArrayPattern=function(node,print){var elems=node.elements;var self=this;var len=elems.length;this.push("[");_.each(elems,function(elem,i){if(!elem){self.push(",")}else{if(i>0)self.push(" ");print(elem);if(i<len-1)self.push(",")}});this.push("]")};exports.Literal=function(node){var val=node.value;var type=typeof val;if(type==="string"){val=JSON.stringify(val);val=val.replace(/[\u000A\u000D\u2028\u2029]/g,function(c){return"\\u"+("0000"+c.charCodeAt(0).toString(16)).slice(-4)});this.push(val)}else if(type==="boolean"||type==="number"){this.push(JSON.stringify(val))}else if(node.regex){this.push("/"+node.regex.pattern+"/"+node.regex.flags)}else if(val===null){this.push("null")}}},{lodash:164}],17:[function(require,module,exports){"use strict";module.exports=Node;var whitespace=require("./whitespace");var parens=require("./parentheses");var t=require("../../types");var _=require("lodash");var find=function(obj,node,parent){if(!obj)return;var result;var types=Object.keys(obj);for(var i=0;i<types.length;i++){var type=types[i];if(t.is(type,node)){var fn=obj[type];result=fn(node,parent);if(result!=null)break}}return result};function Node(node,parent){this.parent=parent;this.node=node}Node.isUserWhitespacable=function(node){return t.isUserWhitespacable(node)};Node.needsWhitespace=function(node,parent,type){if(!node)return 0;if(t.isExpressionStatement(node)){node=node.expression}var lines=find(whitespace[type].nodes,node,parent);if(lines)return lines;_.each(find(whitespace[type].list,node,parent),function(expr){lines=Node.needsWhitespace(expr,node,type);if(lines)return false});return lines||0};Node.needsWhitespaceBefore=function(node,parent){return Node.needsWhitespace(node,parent,"before")};Node.needsWhitespaceAfter=function(node,parent){return Node.needsWhitespace(node,parent,"after")};Node.needsParens=function(node,parent){if(!parent)return false;if(t.isNewExpression(parent)&&parent.callee===node){if(t.isCallExpression(node))return true;var hasCall=_.some(node,function(val){return t.isCallExpression(val)});if(hasCall)return true}return find(parens,node,parent)};Node.needsParensNoLineTerminator=function(node,parent){if(!parent)return false;if(!node.leadingComments||!node.leadingComments.length){return false}if(t.isYieldExpression(parent)||t.isAwaitExpression(parent)){return true}if(t.isContinueStatement(parent)||t.isBreakStatement(parent)||t.isReturnStatement(parent)||t.isThrowStatement(parent)){return true}return false};_.each(Node,function(fn,key){Node.prototype[key]=function(){var args=new Array(arguments.length+2);args[0]=this.node;args[1]=this.parent;for(var i=0;i<args.length;i++){args[i+2]=arguments[i]}return Node[key].apply(null,args)}})},{"../../types":101,"./parentheses":18,"./whitespace":19,lodash:164}],18:[function(require,module,exports){"use strict";var t=require("../../types");var _=require("lodash");var PRECEDENCE={};_.each([["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"],["**"]],function(tier,i){_.each(tier,function(op){PRECEDENCE[op]=i})});exports.UpdateExpression=function(node,parent){if(t.isMemberExpression(parent)&&parent.object===node){return true}};exports.ObjectExpression=function(node,parent){if(t.isExpressionStatement(parent)){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}return false};exports.Binary=function(node,parent){if((t.isCallExpression(parent)||t.isNewExpression(parent))&&parent.callee===node){return true}if(t.isUnaryLike(parent)){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}if(t.isBinary(parent)){var parentOp=parent.operator;var parentPos=PRECEDENCE[parentOp];var nodeOp=node.operator;var nodePos=PRECEDENCE[nodeOp];if(parentPos>nodePos){return true}if(parentPos===nodePos&&parent.right===node){return true}}};exports.BinaryExpression=function(node,parent){if(node.operator==="in"){if(t.isVariableDeclarator(parent)){return true}if(t.isFor(parent)){return true}}};exports.SequenceExpression=function(node,parent){if(t.isForStatement(parent)){return false}if(t.isExpressionStatement(parent)&&parent.expression===node){return false}return true};exports.YieldExpression=function(node,parent){return t.isBinary(parent)||t.isUnaryLike(parent)||t.isCallExpression(parent)||t.isMemberExpression(parent)||t.isNewExpression(parent)||t.isConditionalExpression(parent)||t.isYieldExpression(parent)};exports.ClassExpression=function(node,parent){return t.isExpressionStatement(parent)};exports.UnaryLike=function(node,parent){return t.isMemberExpression(parent)&&parent.object===node};exports.FunctionExpression=function(node,parent){if(t.isExpressionStatement(parent)){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}if(t.isCallExpression(parent)&&parent.callee===node){return true}};exports.AssignmentExpression=exports.ConditionalExpression=function(node,parent){if(t.isUnaryLike(parent)){return true}if(t.isBinary(parent)){return true}if(t.isCallExpression(parent)||t.isNewExpression(parent)){if(parent.callee===node){return true}}if(t.isConditionalExpression(parent)&&parent.test===node){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}return false}},{"../../types":101,lodash:164}],19:[function(require,module,exports){"use strict";var _=require("lodash");var t=require("../../types");exports.before={nodes:{Property:function(node,parent){if(parent.properties[0]===node){return 1}},SpreadProperty:function(node,parent){return exports.before.nodes.Property(node,parent)},SwitchCase:function(node,parent){if(parent.cases[0]===node){return 1}},CallExpression:function(node){if(t.isFunction(node.callee)){return 1}}}};exports.after={nodes:{AssignmentExpression:function(node){if(t.isFunction(node.right)){return 1}}},list:{VariableDeclaration:function(node){return _.map(node.declarations,"init")},ArrayExpression:function(node){return node.elements},ObjectExpression:function(node){return node.properties}}};_.each({Function:1,Class:1,For:1,ArrayExpression:{after:1},ObjectExpression:{after:1},SwitchStatement:1,IfStatement:{before:1},CallExpression:{after:1},Literal:{after:1}},function(amounts,type){if(_.isNumber(amounts)){amounts={after:amounts,before:amounts}}_.each([type].concat(t.FLIPPED_ALIAS_KEYS[type]||[]),function(type){_.each(amounts,function(amount,key){exports[key].nodes[type]=function(){return amount}})})})},{"../../types":101,lodash:164}],20:[function(require,module,exports){"use strict";module.exports=Position;function Position(){this.line=1;this.column=0}Position.prototype.push=function(str){for(var i=0;i<str.length;i++){if(str[i]==="\n"){this.line++;this.column=0}else{this.column++}}};Position.prototype.unshift=function(str){for(var i=0;i<str.length;i++){if(str[i]==="\n"){this.line--}else{this.column--}}}},{}],21:[function(require,module,exports){"use strict";module.exports=SourceMap;var sourceMap=require("source-map");var t=require("../types");function SourceMap(position,opts,code){this.position=position;this.opts=opts;if(opts.sourceMap){this.map=new sourceMap.SourceMapGenerator({file:opts.sourceMapName,sourceRoot:opts.sourceRoot});this.map.setSourceContent(opts.sourceFileName,code)}else{this.map=null}}SourceMap.prototype.get=function(){var map=this.map;if(map){return map.toJSON()}else{return map}};SourceMap.prototype.mark=function(node,type){var loc=node.loc;if(!loc)return;var map=this.map;if(!map)return;if(t.isProgram(node)||t.isFile(node))return;var position=this.position;var generated={line:position.line,column:position.column};var original=loc[type];if(generated.line===original.line&&generated.column===original.column)return;map.addMapping({source:this.opts.sourceFileName,generated:generated,original:original})}},{"../types":101,"source-map":181}],22:[function(require,module,exports){"use strict";module.exports=Whitespace;var _=require("lodash");function getLookupIndex(i,base,max){i+=base;if(i>=max)i-=max;return i}function Whitespace(tokens,comments){this.tokens=_.sortBy(tokens.concat(comments),"start");this.used={};this._lastFoundIndex=0}Whitespace.prototype.getNewlinesBefore=function(node){var startToken;var endToken;var tokens=this.tokens;var token;for(var j=0;j<tokens.length;j++){var i=getLookupIndex(j,this._lastFoundIndex,this.tokens.length);token=tokens[i];if(node.start===token.start){startToken=tokens[i-1];endToken=token;this._lastFoundIndex=i;break}}return this.getNewlinesBetween(startToken,endToken)};Whitespace.prototype.getNewlinesAfter=function(node){var startToken;var endToken;var tokens=this.tokens;var token;for(var j=0;j<tokens.length;j++){var i=getLookupIndex(j,this._lastFoundIndex,this.tokens.length);token=tokens[i];if(node.end===token.end){startToken=token;endToken=tokens[i+1];this._lastFoundIndex=i;break}}if(endToken.type.type==="eof"){return 1}else{var lines=this.getNewlinesBetween(startToken,endToken);if(node.type==="Line"&&!lines){return 1}else{return lines}}};Whitespace.prototype.getNewlinesBetween=function(startToken,endToken){var start=startToken?startToken.loc.end.line:1;var end=endToken.loc.start.line;var lines=0;for(var line=start;line<end;line++){if(typeof this.used[line]==="undefined"){this.used[line]=true;lines++}}return lines}},{lodash:164}],23:[function(require,module,exports){"use strict";module.exports=function cloneDeep(obj){var obj2={};if(!obj)return obj2;for(var key in obj){obj2[key]=obj[key]}return obj2}},{}],24:[function(require,module,exports){var supportsColor=require("supports-color");var tokenize=require("js-tokenizer");var chalk=require("chalk");var util=require("../util");var defs={string1:"red",string2:"red",punct:["white","bold"],curly:"green",parens:["blue","bold"],square:["yellow"],name:"white",keyword:["cyan"],number:"magenta",regexp:"magenta",comment1:"grey",comment2:"grey"};var highlight=function(text){var colorize=function(str,col){if(!col)return str;if(Array.isArray(col)){col.forEach(function(col){str=chalk[col](str)})}else{str=chalk[col](str)}return str};return tokenize(text,true).map(function(str){var type=tokenize.type(str);return colorize(str,defs[type])}).join("")};module.exports=function(lines,lineNumber,colNumber){colNumber=Math.max(colNumber,0);if(supportsColor){lines=highlight(lines)}lines=lines.split("\n");var start=Math.max(lineNumber-3,0);var end=Math.min(lines.length,lineNumber+3);var width=(end+"").length;if(!lineNumber&&!colNumber){start=0;end=lines.length}return"\n"+lines.slice(start,end).map(function(line,i){var curr=i+start+1;var gutter=curr===lineNumber?"> ":" ";var sep=curr+util.repeat(width+1);gutter+=sep+"| ";var str=gutter+line;if(colNumber&&curr===lineNumber){str+="\n";str+=util.repeat(gutter.length-2);str+="|"+util.repeat(colNumber)+"^"}return str}).join("\n")}},{"../util":104,chalk:146,"js-tokenizer":163,"supports-color":192}],25:[function(require,module,exports){"use strict";module.exports=function(){return Object.create(null)}},{}],26:[function(require,module,exports){"use strict";module.exports=function toFastProperties(obj){function f(){}f.prototype=obj;return f;eval(obj)}},{}],27:[function(require,module,exports){"use strict";var t=require("./types");var _=require("lodash");require("./types/node");var estraverse=require("estraverse");_.extend(estraverse.VisitorKeys,t.VISITOR_KEYS);var types=require("ast-types");var def=types.Type.def;var or=types.Type.or;def("File").bases("Node").build("program").field("program",def("Program"));def("AssignmentPattern").bases("Pattern").build("left","right").field("left",def("Pattern")).field("right",def("Expression"));def("ImportBatchSpecifier").bases("Specifier").build("name").field("name",def("Identifier"));def("RestElement").bases("Node").build("argument").field("argument",def("Pattern"));def("VirtualPropertyExpression").bases("Expression").build("object","property").field("object",def("Expression")).field("property",or(def("Identifier"),def("Expression")));def("PrivateDeclaration").bases("Declaration").build("declarations").field("declarations",[def("Identifier")]);def("BindMemberExpression").bases("Expression").build("object","property","arguments").field("object",def("Expression")).field("property",or(def("Identifier"),def("Expression"))).field("arguments",[def("Expression")]);def("BindFunctionExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);types.finalize()},{"./types":101,"./types/node":102,"ast-types":119,estraverse:158,lodash:164}],28:[function(require,module,exports){"use strict";var explode=require("./explode-assignable-expression");var t=require("../../types");module.exports=function(exports,opts){var isAssignment=function(node){return node.operator===opts.operator+"="};var buildAssignment=function(left,right){return t.assignmentExpression("=",left,right)};exports.ExpressionStatement=function(node,parent,scope,context,file){if(file.isConsequenceExpressionStatement(node))return;var expr=node.expression;if(!isAssignment(expr))return;var nodes=[];var exploded=explode(expr.left,nodes,file,scope,true);nodes.push(t.expressionStatement(buildAssignment(exploded.ref,opts.build(exploded.uid,expr.right))));return nodes};exports.AssignmentExpression=function(node,parent,scope,context,file){if(!isAssignment(node))return;var nodes=[];var exploded=explode(node.left,nodes,file,scope);nodes.push(buildAssignment(exploded.ref,opts.build(exploded.uid,node.right)));return t.toSequenceExpression(nodes,scope)};exports.BinaryExpression=function(node){if(node.operator!==opts.operator)return;return opts.build(node.left,node.right)}}},{"../../types":101,"./explode-assignable-expression":31}],29:[function(require,module,exports){"use strict";var t=require("../../types");module.exports=function build(node,buildBody){var self=node.blocks.shift();if(!self)return;var child=build(node,buildBody);if(!child){child=buildBody();if(node.filter){child=t.ifStatement(node.filter,t.blockStatement([child]))}}return t.forOfStatement(t.variableDeclaration("let",[t.variableDeclarator(self.left)]),self.right,t.blockStatement([child]))}},{"../../types":101}],30:[function(require,module,exports){"use strict";var explode=require("./explode-assignable-expression");var t=require("../../types");module.exports=function(exports,opts){var buildAssignment=function(left,right){return t.assignmentExpression("=",left,right)};exports.ExpressionStatement=function(node,parent,scope,context,file){if(file.isConsequenceExpressionStatement(node))return;var expr=node.expression;if(!opts.is(expr,file))return;var nodes=[];var exploded=explode(expr.left,nodes,file,scope);nodes.push(t.ifStatement(opts.build(exploded.uid,file),t.expressionStatement(buildAssignment(exploded.ref,expr.right))));return nodes};exports.AssignmentExpression=function(node,parent,scope,context,file){if(!opts.is(node,file))return;var nodes=[];var exploded=explode(node.left,nodes,file,scope);nodes.push(t.logicalExpression("&&",opts.build(exploded.uid,file),buildAssignment(exploded.ref,node.right)));nodes.push(exploded.ref);return t.toSequenceExpression(nodes,scope)}}},{"../../types":101,"./explode-assignable-expression":31}],31:[function(require,module,exports){"use strict";var t=require("../../types");var getObjRef=function(node,nodes,file,scope){var ref;if(t.isIdentifier(node)){if(scope.has(node.name,true)){return node}else{ref=node}}else if(t.isMemberExpression(node)){ref=node.object;if(t.isIdentifier(ref)&&scope.has(ref.name)){return ref}}else{throw new Error("We can't explode this node type "+node.type)}var temp=scope.generateUidBasedOnNode(ref);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(temp,ref)]));return temp};var getPropRef=function(node,nodes,file,scope){var prop=node.property;var key=t.toComputedKey(node,prop);if(t.isLiteral(key))return key;var temp=scope.generateUidBasedOnNode(prop);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(temp,prop)]));return temp};module.exports=function(node,nodes,file,scope,allowedSingleIdent){var obj;if(t.isIdentifier(node)&&allowedSingleIdent){obj=node}else{obj=getObjRef(node,nodes,file,scope)}var ref,uid;if(t.isIdentifier(node)){ref=node;uid=obj}else{var prop=getPropRef(node,nodes,file,scope);var computed=node.computed||t.isLiteral(prop);uid=ref=t.memberExpression(obj,prop,computed)}return{uid:uid,ref:ref}}},{"../../types":101}],32:[function(require,module,exports){"use strict";var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var visitor={enter:function(node,parent,scope,context,state){if(!t.isIdentifier(node,{name:state.id}))return;if(!t.isReferenced(node,parent))return;var localDeclar=scope.get(state.id,true);if(localDeclar!==state.outerDeclar)return;state.selfReference=true;context.stop()}};exports.property=function(node,file,scope){var key=t.toComputedKey(node,node.key);if(!t.isLiteral(key))return node;var id=t.toIdentifier(key.value);key=t.identifier(id);var state={id:id,selfReference:false,outerDeclar:scope.get(id,true)};traverse(node,visitor,scope,state);if(state.selfReference){node.value=util.template("property-method-assignment-wrapper",{FUNCTION:node.value,FUNCTION_ID:key,FUNCTION_KEY:scope.generateUidIdentifier(id),WRAPPER_KEY:scope.generateUidIdentifier(id+"Wrapper")})}else{node.value.id=key}}},{"../../traverse":97,"../../types":101,"../../util":104}],33:[function(require,module,exports){"use strict";var traverse=require("../../traverse");var t=require("../../types");var visitor={enter:function(node,parent,scope,context){if(t.isFunction(node))context.skip();if(t.isAwaitExpression(node)){node.type="YieldExpression"}}};module.exports=function(node,callId,scope){node.async=false;node.generator=true;traverse(node,visitor,scope);var call=t.callExpression(callId,[node]);var id=node.id;delete node.id;if(t.isFunctionDeclaration(node)){var declar=t.variableDeclaration("let",[t.variableDeclarator(id,call)]);declar._blockHoist=true;return declar}else{return call}}},{"../../traverse":97,"../../types":101}],34:[function(require,module,exports){"use strict";module.exports=ReplaceSupers;var traverse=require("../../traverse");var t=require("../../types");function ReplaceSupers(opts){this.topLevelThisReference=null;this.methodNode=opts.methodNode;this.className=opts.className;this.superName=opts.superName;this.isLoose=opts.isLoose;this.scope=opts.scope;this.file=opts.file}ReplaceSupers.prototype.superProperty=function(property,isStatic,isComputed,thisExpression){return t.callExpression(this.file.addHelper("get"),[t.callExpression(t.memberExpression(t.identifier("Object"),t.identifier("getPrototypeOf")),[isStatic?this.className:t.memberExpression(this.className,t.identifier("prototype"))]),isComputed?property:t.literal(property.name),thisExpression])};ReplaceSupers.prototype.looseSuperProperty=function(methodNode,id,parent){var methodName=methodNode.key;var superName=this.superName||t.identifier("Function");if(parent.property===id){return}else if(t.isCallExpression(parent,{callee:id})){parent.arguments.unshift(t.thisExpression());if(methodName.name==="constructor"){return t.memberExpression(superName,t.identifier("call"))}else{id=superName;if(!methodNode.static){id=t.memberExpression(id,t.identifier("prototype"))}id=t.memberExpression(id,methodName,methodNode.computed);return t.memberExpression(id,t.identifier("call"))}}else if(t.isMemberExpression(parent)&&!methodNode.static){return t.memberExpression(superName,t.identifier("prototype"))}else{return superName}};ReplaceSupers.prototype.replace=function(){this.traverseLevel(this.methodNode.value,true)};var visitor={enter:function(node,parent,scope,context,state){var topLevel=state.topLevel;var self=state.self;if(t.isFunction(node)&&!t.isArrowFunctionExpression(node)){self.traverseLevel(node,false);return context.skip()}if(t.isProperty(node,{method:true})||t.isMethodDefinition(node)){return context.skip()}var getThisReference=topLevel?t.thisExpression:self.getThisReference;var callback=self.specHandle;if(self.isLoose)callback=self.looseHandle;return callback.call(self,getThisReference,node,parent)}};ReplaceSupers.prototype.traverseLevel=function(node,topLevel){var state={self:this,topLevel:topLevel};traverse(node,visitor,this.scope,state)};ReplaceSupers.prototype.getThisReference=function(){if(this.topLevelThisReference){return this.topLevelThisReference}else{var ref=this.topLevelThisReference=this.file.generateUidIdentifier("this");this.methodNode.value.body.body.unshift(t.variableDeclaration("var",[t.variableDeclarator(this.topLevelThisReference,t.thisExpression())]));return ref}};ReplaceSupers.prototype.looseHandle=function(getThisReference,node,parent){if(t.isIdentifier(node,{name:"super"})){return this.looseSuperProperty(this.methodNode,node,parent)}else if(t.isCallExpression(node)){var callee=node.callee;if(!t.isMemberExpression(callee))return;if(callee.object.name!=="super")return;t.appendToMemberExpression(callee,t.identifier("call"));node.arguments.unshift(getThisReference())}};ReplaceSupers.prototype.specHandle=function(getThisReference,node,parent){var methodNode=this.methodNode;var property;var computed;var args;if(t.isIdentifier(node,{name:"super"})){if(!(t.isMemberExpression(parent)&&!parent.computed&&parent.property===node)){throw this.file.errorWithNode(node,"illegal use of bare super")}}else if(t.isCallExpression(node)){var callee=node.callee;if(t.isIdentifier(callee,{name:"super"})){property=methodNode.key;computed=methodNode.computed;args=node.arguments;if(methodNode.key.name!=="constructor"){var methodName=methodNode.key.name||"METHOD_NAME";throw this.file.errorWithNode(node,"Direct super call is illegal in non-constructor, use super."+methodName+"() instead")}}else{if(!t.isMemberExpression(callee))return;if(callee.object.name!=="super")return;property=callee.property;computed=callee.computed;args=node.arguments}}else if(t.isMemberExpression(node)){if(!t.isIdentifier(node.object,{name:"super"}))return;property=node.property;computed=node.computed}if(!property)return;var thisReference=getThisReference();var superProperty=this.superProperty(property,methodNode.static,computed,thisReference);if(args){if(args.length===1&&t.isSpreadElement(args[0])){return t.callExpression(t.memberExpression(superProperty,t.identifier("apply")),[thisReference,args[0].argument])}else{return t.callExpression(t.memberExpression(superProperty,t.identifier("call")),[thisReference].concat(args))}}else{return superProperty}}},{"../../traverse":97,"../../types":101}],35:[function(require,module,exports){"use strict";var t=require("../../types");exports.has=function(node){var first=node.body[0];return t.isExpressionStatement(first)&&t.isLiteral(first.expression,{value:"use strict"})};exports.wrap=function(node,callback){var useStrictNode;if(exports.has(node)){useStrictNode=node.body.shift()}callback();if(useStrictNode){node.body.unshift(useStrictNode)}}},{"../../types":101}],36:[function(require,module,exports){"use strict";module.exports=DefaultFormatter;var traverse=require("../../traverse");var object=require("../../helpers/object");var util=require("../../util");var t=require("../../types");var _=require("lodash");function DefaultFormatter(file){this.file=file;this.ids=object();this.hasNonDefaultExports=false;this.hasLocalExports=false;this.hasLocalImports=false;this.localImportOccurences=object();this.localExports=object();this.localImports=object();this.getLocalExports();this.getLocalImports();this.remapAssignments()}DefaultFormatter.prototype.doDefaultExportInterop=function(node){return node.default&&!this.noInteropRequire&&!this.hasNonDefaultExports};DefaultFormatter.prototype.bumpImportOccurences=function(node){var source=node.source.value;var occurs=this.localImportOccurences;occurs[source]=occurs[source]||0;occurs[source]+=node.specifiers.length};var exportsVisitor={enter:function(node,parent,scope,context,formatter){var declar=node&&node.declaration;if(t.isExportDeclaration(node)){formatter.hasLocalImports=true;if(declar&&t.isStatement(declar)){_.extend(formatter.localExports,t.getIds(declar,true))}if(!node.default){formatter.hasNonDefaultExports=true}if(node.source){formatter.bumpImportOccurences(node)}}}};DefaultFormatter.prototype.getLocalExports=function(){traverse(this.file.ast,exportsVisitor,this.file.scope,this)};var importsVisitor={enter:function(node,parent,scope,context,formatter){if(t.isImportDeclaration(node)){formatter.hasLocalImports=true;_.extend(formatter.localImports,t.getIds(node,true));formatter.bumpImportOccurences(node)}}};DefaultFormatter.prototype.getLocalImports=function(){traverse(this.file.ast,importsVisitor,this.file.scope,this)};var remapVisitor={enter:function(node,parent,scope,context,formatter){if(t.isUpdateExpression(node)&&formatter.isLocalReference(node.argument,scope)){context.skip();var assign=t.assignmentExpression(node.operator[0]+"=",node.argument,t.literal(1));var remapped=formatter.remapExportAssignment(assign);if(t.isExpressionStatement(parent)||node.prefix){return remapped}var nodes=[];nodes.push(remapped);var operator;if(node.operator==="--"){operator="+"}else{operator="-"}nodes.push(t.binaryExpression(operator,node.argument,t.literal(1)));return t.sequenceExpression(nodes)}if(t.isAssignmentExpression(node)&&formatter.isLocalReference(node.left,scope)){context.skip();return formatter.remapExportAssignment(node)}}};DefaultFormatter.prototype.remapAssignments=function(){if(this.hasLocalImports){traverse(this.file.ast,remapVisitor,this.file.scope,this)}};DefaultFormatter.prototype.isLocalReference=function(node){var localImports=this.localImports;return t.isIdentifier(node)&&localImports[node.name]&&localImports[node.name]!==node};DefaultFormatter.prototype.checkLocalReference=function(node){var file=this.file;if(this.isLocalReference(node)){throw file.errorWithNode(node,"Illegal assignment of module import")}};DefaultFormatter.prototype.remapExportAssignment=function(node){return t.assignmentExpression("=",node.left,t.assignmentExpression(node.operator,t.memberExpression(t.identifier("exports"),node.left),node.right))};DefaultFormatter.prototype.isLocalReference=function(node,scope){var localExports=this.localExports;var name=node.name;return t.isIdentifier(node)&&localExports[name]&&localExports[name]===scope.get(name,true)};DefaultFormatter.prototype.getModuleName=function(){var opts=this.file.opts;var filenameRelative=opts.filenameRelative;var moduleName="";if(opts.moduleRoot){moduleName=opts.moduleRoot+"/"}if(!opts.filenameRelative){return moduleName+opts.filename.replace(/^\//,"")}if(opts.sourceRoot){var sourceRootRegEx=new RegExp("^"+opts.sourceRoot+"/?");filenameRelative=filenameRelative.replace(sourceRootRegEx,"")}if(!opts.keepModuleIdExtensions){filenameRelative=filenameRelative.replace(/\.(.*?)$/,"")}moduleName+=filenameRelative;moduleName=moduleName.replace(/\\/g,"/");return moduleName};DefaultFormatter.prototype._pushStatement=function(ref,nodes){if(t.isClass(ref)||t.isFunction(ref)){if(ref.id){nodes.push(t.toStatement(ref));ref=ref.id}}return ref};DefaultFormatter.prototype._hoistExport=function(declar,assign,priority){if(t.isFunctionDeclaration(declar)){assign._blockHoist=priority||2}return assign};DefaultFormatter.prototype.getExternalReference=function(node,nodes){var ids=this.ids;var id=node.source.value;if(ids[id]){return ids[id]}else{return this.ids[id]=this._getExternalReference(node,nodes)}};DefaultFormatter.prototype.exportSpecifier=function(specifier,node,nodes){var inherits=false;if(node.specifiers.length===1)inherits=node;if(node.source){var ref=this.getExternalReference(node,nodes);if(t.isExportBatchSpecifier(specifier)){nodes.push(this.buildExportsWildcard(ref,node))}else{if(t.isSpecifierDefault(specifier)&&!this.noInteropRequire){ref=t.callExpression(this.file.addHelper("interop-require"),[ref])}else{ref=t.memberExpression(ref,t.getSpecifierId(specifier))}nodes.push(this.buildExportsAssignment(t.getSpecifierName(specifier),ref,node))}}else{nodes.push(this.buildExportsAssignment(t.getSpecifierName(specifier),specifier.id,node))}};DefaultFormatter.prototype.buildExportsWildcard=function(objectIdentifier){return t.expressionStatement(t.callExpression(this.file.addHelper("defaults"),[t.identifier("exports"),t.callExpression(this.file.addHelper("interop-require-wildcard"),[objectIdentifier])]))};DefaultFormatter.prototype.buildExportsAssignment=function(id,init){return util.template("exports-assign",{VALUE:init,KEY:id},true)};DefaultFormatter.prototype.exportDeclaration=function(node,nodes){var declar=node.declaration;var id=declar.id;if(node.default){id=t.identifier("default")}var assign;if(t.isVariableDeclaration(declar)){for(var i=0;i<declar.declarations.length;i++){var decl=declar.declarations[i];decl.init=this.buildExportsAssignment(decl.id,decl.init,node).expression;var newDeclar=t.variableDeclaration(declar.kind,[decl]);if(i===0)t.inherits(newDeclar,declar);nodes.push(newDeclar)}}else{var ref=declar;if(t.isFunctionDeclaration(declar)||t.isClassDeclaration(declar)){ref=declar.id;nodes.push(declar)}assign=this.buildExportsAssignment(id,ref,node);nodes.push(assign);this._hoistExport(declar,assign)}}},{"../../helpers/object":25,"../../traverse":97,"../../types":101,"../../util":104,lodash:164}],37:[function(require,module,exports){"use strict";var util=require("../../util");module.exports=function(Parent){var Constructor=function(){this.noInteropRequire=true;Parent.apply(this,arguments)};util.inherits(Constructor,Parent);return Constructor}},{"../../util":104}],38:[function(require,module,exports){"use strict";module.exports=require("./_strict")(require("./amd"))},{"./_strict":37,"./amd":39}],39:[function(require,module,exports){"use strict";module.exports=AMDFormatter;var DefaultFormatter=require("./_default");var CommonFormatter=require("./common");var util=require("../../util");var t=require("../../types");var _=require("lodash");function AMDFormatter(){CommonFormatter.apply(this,arguments)}util.inherits(AMDFormatter,DefaultFormatter);AMDFormatter.prototype.buildDependencyLiterals=function(){var names=[];for(var name in this.ids){names.push(t.literal(name))}return names};AMDFormatter.prototype.transform=function(ast){var program=ast.program;var body=program.body;var names=[t.literal("exports")];
if(this.passModuleArg)names.push(t.literal("module"));names=names.concat(this.buildDependencyLiterals());names=t.arrayExpression(names);var params=_.values(this.ids);if(this.passModuleArg)params.unshift(t.identifier("module"));params.unshift(t.identifier("exports"));var container=t.functionExpression(null,params,t.blockStatement(body));var defineArgs=[names,container];var moduleName=this.getModuleName();if(moduleName)defineArgs.unshift(t.literal(moduleName));var call=t.callExpression(t.identifier("define"),defineArgs);program.body=[t.expressionStatement(call)]};AMDFormatter.prototype.getModuleName=function(){if(this.file.opts.moduleIds){return DefaultFormatter.prototype.getModuleName.apply(this,arguments)}else{return null}};AMDFormatter.prototype._getExternalReference=function(node){return this.file.generateUidIdentifier(node.source.value)};AMDFormatter.prototype.importDeclaration=function(node){this.getExternalReference(node)};AMDFormatter.prototype.importSpecifier=function(specifier,node,nodes){var key=t.getSpecifierName(specifier);var ref=this.getExternalReference(node);if(_.contains(this.file.dynamicImported,node)){this.ids[node.source.value]=key;return}else if(t.isImportBatchSpecifier(specifier)){}else if(t.isSpecifierDefault(specifier)&&!this.noInteropRequire){ref=t.callExpression(this.file.addHelper("interop-require"),[ref])}else{ref=t.memberExpression(ref,t.getSpecifierId(specifier),false)}nodes.push(t.variableDeclaration("var",[t.variableDeclarator(key,ref)]))};AMDFormatter.prototype.exportDeclaration=function(node){if(this.doDefaultExportInterop(node)){this.passModuleArg=true}CommonFormatter.prototype.exportDeclaration.apply(this,arguments)}},{"../../types":101,"../../util":104,"./_default":36,"./common":41,lodash:164}],40:[function(require,module,exports){"use strict";module.exports=require("./_strict")(require("./common"))},{"./_strict":37,"./common":41}],41:[function(require,module,exports){"use strict";module.exports=CommonJSFormatter;var DefaultFormatter=require("./_default");var util=require("../../util");var t=require("../../types");var _=require("lodash");function CommonJSFormatter(file){DefaultFormatter.apply(this,arguments);if(this.hasNonDefaultExports){file.ast.program.body.push(util.template("exports-module-declaration",true))}}util.inherits(CommonJSFormatter,DefaultFormatter);CommonJSFormatter.prototype.importSpecifier=function(specifier,node,nodes){var variableName=t.getSpecifierName(specifier);var ref=this.getExternalReference(node,nodes);if(t.isSpecifierDefault(specifier)){if(!_.contains(this.file.dynamicImported,node)){ref=t.callExpression(this.file.addHelper("interop-require"),[ref])}nodes.push(t.variableDeclaration("var",[t.variableDeclarator(variableName,ref)]))}else{if(specifier.type==="ImportBatchSpecifier"){nodes.push(t.variableDeclaration("var",[t.variableDeclarator(variableName,t.callExpression(this.file.addHelper("interop-require-wildcard"),[ref]))]))}else{nodes.push(t.variableDeclaration("var",[t.variableDeclarator(variableName,t.memberExpression(ref,t.getSpecifierId(specifier)))]))}}};CommonJSFormatter.prototype.importDeclaration=function(node,nodes){nodes.push(util.template("require",{MODULE_NAME:node.source},true))};CommonJSFormatter.prototype.exportDeclaration=function(node,nodes){if(this.doDefaultExportInterop(node)){var declar=node.declaration;var assign=util.template("exports-default-assign",{VALUE:this._pushStatement(declar,nodes)},true);if(t.isFunctionDeclaration(declar)){assign._blockHoist=3}nodes.push(assign);return}DefaultFormatter.prototype.exportDeclaration.apply(this,arguments)};CommonJSFormatter.prototype._getExternalReference=function(node,nodes){var source=node.source.value;var call=t.callExpression(t.identifier("require"),[node.source]);if(this.localImportOccurences[source]>1){var uid=this.file.generateUidIdentifier(source);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(uid,call)]));return uid}else{return call}}},{"../../types":101,"../../util":104,"./_default":36,lodash:164}],42:[function(require,module,exports){"use strict";module.exports=IgnoreFormatter;var t=require("../../types");function IgnoreFormatter(){}IgnoreFormatter.prototype.exportDeclaration=function(node,nodes){var declar=t.toStatement(node.declaration,true);if(declar)nodes.push(t.inherits(declar,node))};IgnoreFormatter.prototype.importDeclaration=IgnoreFormatter.prototype.importSpecifier=IgnoreFormatter.prototype.exportSpecifier=function(){}},{"../../types":101}],43:[function(require,module,exports){module.exports={commonStrict:require("./common-strict"),amdStrict:require("./amd-strict"),umdStrict:require("./umd-strict"),common:require("./common"),system:require("./system"),ignore:require("./ignore"),amd:require("./amd"),umd:require("./umd")}},{"./amd":39,"./amd-strict":38,"./common":41,"./common-strict":40,"./ignore":42,"./system":44,"./umd":46,"./umd-strict":45}],44:[function(require,module,exports){"use strict";module.exports=SystemFormatter;var DefaultFormatter=require("./_default");var AMDFormatter=require("./amd");var useStrict=require("../helpers/use-strict");var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var _=require("lodash");function SystemFormatter(file){this.exportIdentifier=file.generateUidIdentifier("export");this.noInteropRequire=true;DefaultFormatter.apply(this,arguments)}util.inherits(SystemFormatter,AMDFormatter);SystemFormatter.prototype._addImportSource=function(node,exportNode){node._importSource=exportNode.source&&exportNode.source.value;return node};SystemFormatter.prototype.buildExportsWildcard=function(objectIdentifier,node){var leftIdentifier=this.file.generateUidIdentifier("key");var valIdentifier=t.memberExpression(objectIdentifier,leftIdentifier,true);var left=t.variableDeclaration("var",[t.variableDeclarator(leftIdentifier)]);var right=objectIdentifier;var block=t.blockStatement([t.expressionStatement(this.buildExportCall(leftIdentifier,valIdentifier))]);return this._addImportSource(t.forInStatement(left,right,block),node)};SystemFormatter.prototype.buildExportsAssignment=function(id,init,node){var call=this.buildExportCall(t.literal(id.name),init,true);return this._addImportSource(call,node)};SystemFormatter.prototype.remapExportAssignment=function(node){return this.buildExportCall(t.literal(node.left.name),node)};SystemFormatter.prototype.buildExportCall=function(id,init,isStatement){var call=t.callExpression(this.exportIdentifier,[id,init]);if(isStatement){return t.expressionStatement(call)}else{return call}};SystemFormatter.prototype.importSpecifier=function(specifier,node,nodes){AMDFormatter.prototype.importSpecifier.apply(this,arguments);this._addImportSource(_.last(nodes),node)};var runnerSettersVisitor={enter:function(node,parent,scope,context,state){if(node._importSource===state.source){if(t.isVariableDeclaration(node)){_.each(node.declarations,function(declar){state.hoistDeclarators.push(t.variableDeclarator(declar.id));state.nodes.push(t.expressionStatement(t.assignmentExpression("=",declar.id,declar.init)))})}else{state.nodes.push(node)}context.remove()}}};SystemFormatter.prototype.buildRunnerSetters=function(block,hoistDeclarators){var scope=this.file.scope;return t.arrayExpression(_.map(this.ids,function(uid,source){var state={source:source,nodes:[],hoistDeclarators:hoistDeclarators};traverse(block,runnerSettersVisitor,scope,state);return t.functionExpression(null,[uid],t.blockStatement(state.nodes))}))};var hoistVariablesVisitor={enter:function(node,parent,scope,context,hoistDeclarators){if(t.isFunction(node)){return context.skip()}if(t.isVariableDeclaration(node)){if(node.kind!=="var"&&!t.isProgram(parent)){return}if(node._blockHoist)return;var nodes=[];for(var i=0;i<node.declarations.length;i++){var declar=node.declarations[i];hoistDeclarators.push(t.variableDeclarator(declar.id));if(declar.init){var assign=t.expressionStatement(t.assignmentExpression("=",declar.id,declar.init));nodes.push(assign)}}if(t.isFor(parent)){if(parent.left===node){return node.declarations[0].id}if(parent.init===node){return t.toSequenceExpression(nodes,scope)}}return nodes}}};var hoistFunctionsVisitor={enter:function(node,parent,scope,context,handlerBody){if(t.isFunction(node))context.skip();if(t.isFunctionDeclaration(node)||node._blockHoist){handlerBody.push(node);context.remove()}}};SystemFormatter.prototype.transform=function(ast){var program=ast.program;var hoistDeclarators=[];var moduleName=this.getModuleName();var moduleNameLiteral=t.literal(moduleName);var block=t.blockStatement(program.body);var runner=util.template("system",{MODULE_NAME:moduleNameLiteral,MODULE_DEPENDENCIES:t.arrayExpression(this.buildDependencyLiterals()),EXPORT_IDENTIFIER:this.exportIdentifier,SETTERS:this.buildRunnerSetters(block,hoistDeclarators),EXECUTE:t.functionExpression(null,[],block)},true);var handlerBody=runner.expression.arguments[2].body.body;if(!moduleName)runner.expression.arguments.shift();var returnStatement=handlerBody.pop();traverse(block,hoistVariablesVisitor,this.file.scope,hoistDeclarators);if(hoistDeclarators.length){var hoistDeclar=t.variableDeclaration("var",hoistDeclarators);hoistDeclar._blockHoist=true;handlerBody.unshift(hoistDeclar)}traverse(block,hoistFunctionsVisitor,this.file.scope,handlerBody);handlerBody.push(returnStatement);if(useStrict.has(block)){handlerBody.unshift(block.body.shift())}program.body=[runner]}},{"../../traverse":97,"../../types":101,"../../util":104,"../helpers/use-strict":35,"./_default":36,"./amd":39,lodash:164}],45:[function(require,module,exports){"use strict";module.exports=require("./_strict")(require("./umd"))},{"./_strict":37,"./umd":46}],46:[function(require,module,exports){"use strict";module.exports=UMDFormatter;var AMDFormatter=require("./amd");var util=require("../../util");var t=require("../../types");var _=require("lodash");function UMDFormatter(){AMDFormatter.apply(this,arguments)}util.inherits(UMDFormatter,AMDFormatter);UMDFormatter.prototype.transform=function(ast){var program=ast.program;var body=program.body;var names=[];for(var name in this.ids){names.push(t.literal(name))}var ids=_.values(this.ids);var args=[t.identifier("exports")];if(this.passModuleArg)args.push(t.identifier("module"));args=args.concat(ids);var factory=t.functionExpression(null,args,t.blockStatement(body));var defineArgs=[t.literal("exports")];if(this.passModuleArg)defineArgs.push(t.literal("module"));defineArgs=defineArgs.concat(names);defineArgs=[t.arrayExpression(defineArgs)];var testExports=util.template("test-exports");var testModule=util.template("test-module");var commonTests=this.passModuleArg?t.logicalExpression("&&",testExports,testModule):testExports;var commonArgs=[t.identifier("exports")];if(this.passModuleArg)commonArgs.push(t.identifier("module"));commonArgs=commonArgs.concat(names.map(function(name){return t.callExpression(t.identifier("require"),[name])}));var moduleName=this.getModuleName();if(moduleName)defineArgs.unshift(t.literal(moduleName));var runner=util.template("umd-runner-body",{AMD_ARGUMENTS:defineArgs,COMMON_TEST:commonTests,COMMON_ARGUMENTS:commonArgs});var call=t.callExpression(runner,[factory]);program.body=[t.expressionStatement(call)]}},{"../../types":101,"../../util":104,"./amd":39,lodash:164}],47:[function(require,module,exports){"use strict";module.exports=transform;var Transformer=require("./transformer");var object=require("../helpers/object");var File=require("../file");var util=require("../util");var _=require("lodash");function transform(code,opts){var file=new File(opts);return file.parse(code)}transform.fromAst=function(ast,code,opts){ast=util.normaliseAst(ast);var file=new File(opts);file.addCode(code);file.transform(ast);return file.generate()};transform._ensureTransformerNames=function(type,rawKeys){var keys=[];for(var i=0;i<rawKeys.length;i++){var key=rawKeys[i];var deprecatedKey=transform.deprecatedTransformerMap[key];if(deprecatedKey){console.error("The transformer "+key+" has been renamed to "+deprecatedKey+" in v3.0.0 - backwards compatibilty will be removed 4.0.0");rawKeys.push(deprecatedKey)}else if(transform.transformers[key]){keys.push(key)}else if(transform.namespaces[key]){keys=keys.concat(transform.namespaces[key])}else{throw new ReferenceError("Unknown transformer "+key+" specified in "+type+" - "+"transformer key names have been changed in 3.0.0 see "+"the changelog for more info "+"https://github.com/6to5/6to5/blob/master/CHANGELOG.md#300")}}return keys};transform.transformers=object();transform.namespaces=object();transform.deprecatedTransformerMap=require("./transformers/deprecated");transform.moduleFormatters=require("./modules");var rawTransformers=require("./transformers");_.each(rawTransformers,function(transformer,key){var namespace=key.split(".")[0];transform.namespaces[namespace]=transform.namespaces[namespace]||[];transform.namespaces[namespace].push(key);transform.transformers[key]=new Transformer(key,transformer)})},{"../file":2,"../helpers/object":25,"../util":104,"./modules":43,"./transformer":49,"./transformers":71,"./transformers/deprecated":50,lodash:164}],48:[function(require,module,exports){module.exports=TransformerPass;var traverse=require("../traverse");var _=require("lodash");function TransformerPass(file,transformer){this.transformer=transformer;this.handlers=transformer.handlers;this.file=file}TransformerPass.prototype.astRun=function(key){var handlers=this.handlers;var file=this.file;if(handlers.ast&&handlers.ast[key]){handlers.ast[key](file.ast,file)}};TransformerPass.prototype.canRun=function(){var transformer=this.transformer;var opts=this.file.opts;var key=transformer.key;if(key[0]==="_")return true;var blacklist=opts.blacklist;if(blacklist.length&&_.contains(blacklist,key))return false;var whitelist=opts.whitelist;if(whitelist.length&&!_.contains(whitelist,key))return false;if(transformer.optional&&!_.contains(opts.optional,key))return false;if(transformer.experimental&&!opts.experimental)return false;return true};var transformVisitor={enter:function(node,parent,scope,context,state){var fns=state.handlers[node.type];if(!fns)return;return fns.enter(node,parent,scope,context,state.file,state.pass)},exit:function(node,parent,scope,context,state){var fns=state.handlers[node.type];if(!fns)return;return fns.exit(node,parent,scope,context,state.file,state.pass)}};TransformerPass.prototype.transform=function(){var file=this.file;this.astRun("before");var state={file:file,handlers:this.handlers,pass:this};traverse(file.ast,transformVisitor,file.scope,state);this.astRun("after")}},{"../traverse":97,lodash:164}],49:[function(require,module,exports){"use strict";module.exports=Transformer;var TransformerPass=require("./transformer-pass");var t=require("../types");var _=require("lodash");function Transformer(key,transformer,opts){this.manipulateOptions=transformer.manipulateOptions;this.experimental=!!transformer.experimental;this.secondPass=!!transformer.secondPass;this.optional=!!transformer.optional;this.handlers=this.normalise(transformer);this.opts=opts||{};this.key=key}Transformer.prototype.normalise=function(transformer){var self=this;if(_.isFunction(transformer)){transformer={ast:transformer}}_.each(transformer,function(fns,type){if(type[0]==="_"){self[type]=fns;return}if(_.isFunction(fns))fns={enter:fns};if(!_.isObject(fns))return;if(!fns.enter)fns.enter=_.noop;if(!fns.exit)fns.exit=_.noop;transformer[type]=fns;var aliases=t.FLIPPED_ALIAS_KEYS[type];if(aliases){_.each(aliases,function(alias){transformer[alias]=fns})}});return transformer};Transformer.prototype.buildPass=function(file){return new TransformerPass(file,this)}},{"../types":101,"./transformer-pass":48,lodash:164}],50:[function(require,module,exports){module.exports={specNoForInOfAssignment:"validation.noForInOfAssignment",specSetters:"validation.setters",specBlockScopedFunctions:"spec.blockScopedFunctions",malletOperator:"playground.malletOperator",methodBinding:"playground.methodBinding",memoizationOperator:"playground.memoizationOperator",objectGetterMemoization:"playground.objectGetterMemoization",modules:"es6.modules",propertyNameShorthand:"es6.properties.shorthand",arrayComprehension:"es7.comprehensions",generatorComprehension:"es7.comprehensions",arrowFunctions:"es6.arrowFunctions",classes:"es6.classes",objectSpread:"es7.objectSpread",exponentiationOperator:"es7.exponentiationOperator",spread:"es6.spread",templateLiterals:"es6.templateLiterals",propertyMethodAssignment:"es6.properties.shorthand",computedPropertyNames:"es6.properties.computed",defaultParameters:"es6.parameters.default",restParameters:"es6.parameters.rest",destructuring:"es6.destructuring",forOf:"es6.forOf",unicodeRegex:"es6.unicodeRegex",abstractReferences:"es7.abstractReferences",constants:"es6.constants",letScoping:"es6.letScoping",blockScopingTDZ:"es6.blockScopingTDZ",generators:"regenerator",protoToAssign:"spec.protoToAssign",typeofSymbol:"spec.typeofSymbol",coreAliasing:"selfContained",undefinedToVoid:"spec.undefinedToVoid",undeclaredVariableCheck:"validation.undeclaredVariableCheck",specPropertyLiterals:"minification.propertyLiterals",specMemberExpressionLiterals:"minification.memberExpressionLiterals"}},{}],51:[function(require,module,exports){"use strict";var util=require("../../../util");var t=require("../../../types");exports.ObjectExpression=function(node){var mutatorMap={};var hasAny=false;node.properties=node.properties.filter(function(prop){if(prop.kind==="get"||prop.kind==="set"){hasAny=true;util.pushMutatorMap(mutatorMap,prop.key,prop.kind,prop.computed,prop.value);return false}else{return true}});if(!hasAny)return;return t.callExpression(t.memberExpression(t.identifier("Object"),t.identifier("defineProperties")),[node,util.buildDefineProperties(mutatorMap)])}},{"../../../types":101,"../../../util":104}],52:[function(require,module,exports){"use strict";var t=require("../../../types");exports.ArrowFunctionExpression=function(node){t.ensureBlock(node);node._aliasFunction="arrow";node.expression=false;node.type="FunctionExpression";return node}},{"../../../types":101}],53:[function(require,module,exports){"use strict";var traverse=require("../../../traverse");var t=require("../../../types");var visitor={enter:function(node,parent,scope,context,state){if(!t.isReferencedIdentifier(node,parent))return;var declared=state.letRefs[node.name];if(!declared)return;if(scope.get(node.name,true)!==declared)return;var declaredLoc=declared.loc;var referenceLoc=node.loc;if(!declaredLoc||!referenceLoc)return;var before=referenceLoc.start.line<declaredLoc.start.line;if(referenceLoc.start.line===declaredLoc.start.line){before=referenceLoc.start.col<declaredLoc.start.col}if(before){throw state.file.errorWithNode(node,"Temporal dead zone - accessing a variable before it's initialized")}}};exports.optional=true;exports.Loop=exports.Program=exports.BlockStatement=function(node,parent,scope,context,file){var letRefs=node._letReferences;if(!letRefs)return;var state={letRefs:letRefs,file:file};traverse(node,visitor,scope,state)}},{"../../../traverse":97,"../../../types":101}],54:[function(require,module,exports){"use strict";var traverse=require("../../../traverse");var object=require("../../../helpers/object");var util=require("../../../util");var t=require("../../../types");var _=require("lodash");var isLet=function(node,parent){if(!t.isVariableDeclaration(node))return false;if(node._let)return true;if(node.kind!=="let")return false;if(!t.isFor(parent)||t.isFor(parent)&&parent.left!==node){for(var i=0;i<node.declarations.length;i++){var declar=node.declarations[i];declar.init=declar.init||t.identifier("undefined")}}node._let=true;node.kind="var";return true};var isVar=function(node,parent){return t.isVariableDeclaration(node,{kind:"var"})&&!isLet(node,parent)};var standardiseLets=function(declars){for(var i=0;i<declars.length;i++){delete declars[i]._let}};exports.VariableDeclaration=function(node,parent){isLet(node,parent)};exports.Loop=function(node,parent,scope,context,file){var init=node.left||node.init;if(isLet(init,node)){t.ensureBlock(node);node.body._letDeclarators=[init]}if(t.isLabeledStatement(parent)){node.label=parent.label}var letScoping=new LetScoping(node,node.body,parent,scope,file);letScoping.run();if(node.label&&!t.isLabeledStatement(parent)){return t.labeledStatement(node.label,node)}};exports.Program=exports.BlockStatement=function(block,parent,scope,context,file){if(!t.isLoop(parent)){var letScoping=new LetScoping(false,block,parent,scope,file);letScoping.run()}};function LetScoping(loopParent,block,parent,scope,file){this.loopParent=loopParent;this.parent=parent;this.scope=scope;this.block=block;this.file=file;this.outsideLetReferences=object();this.hasLetReferences=false;this.letReferences=block._letReferences=object();this.body=[]}LetScoping.prototype.run=function(){var block=this.block;if(block._letDone)return;block._letDone=true;var needsClosure=this.getLetReferences();if(t.isFunction(this.parent)||t.isProgram(this.block))return;if(!this.hasLetReferences)return;if(needsClosure){this.needsClosure()}else{this.remap()}};function replace(node,parent,scope,context,remaps){if(!t.isReferencedIdentifier(node,parent))return;var remap=remaps[node.name];if(!remap)return;var own=scope.get(node.name,true);if(own===remap.node){node.name=remap.uid}else{if(context)context.skip()}}var replaceVisitor={enter:replace};function traverseReplace(node,parent,scope,remaps){replace(node,parent,scope,null,remaps);traverse(node,replaceVisitor,scope,remaps)}LetScoping.prototype.remap=function(){var hasRemaps=false;var letRefs=this.letReferences;var scope=this.scope;var remaps=object();for(var key in letRefs){var ref=letRefs[key];if(scope.parentHas(key)){var uid=scope.generateUidIdentifier(ref.name).name;ref.name=uid;hasRemaps=true;remaps[key]=remaps[uid]={node:ref,uid:uid}}}if(!hasRemaps)return;var loopParent=this.loopParent;if(loopParent){traverseReplace(loopParent.right,loopParent,scope,remaps);traverseReplace(loopParent.test,loopParent,scope,remaps);traverseReplace(loopParent.update,loopParent,scope,remaps)}traverse(this.block,replaceVisitor,scope,remaps)};LetScoping.prototype.needsClosure=function(){var block=this.block;this.has=this.checkLoop();this.hoistVarDeclarations();var params=_.values(this.outsideLetReferences);var fn=t.functionExpression(null,params,t.blockStatement(block.body));fn._aliasFunction=true;block.body=this.body;var call=t.callExpression(fn,params);var ret=this.scope.generateUidIdentifier("ret");var hasYield=traverse.hasType(fn.body,this.scope,"YieldExpression",t.FUNCTION_TYPES);if(hasYield){fn.generator=true;call=t.yieldExpression(call,true)}var hasAsync=traverse.hasType(fn.body,this.scope,"AwaitExpression",t.FUNCTION_TYPES);if(hasAsync){fn.async=true;call=t.awaitExpression(call,true)}this.build(ret,call)};var letReferenceFunctionVisitor={enter:function(node,parent,scope,context,state){if(!t.isReferencedIdentifier(node,parent))return;if(scope.hasOwn(node.name,true))return;if(!state.letReferences[node.name])return;state.closurify=true}};var letReferenceBlockVisitor={enter:function(node,parent,scope,context,state){if(t.isFunction(node)){traverse(node,letReferenceFunctionVisitor,scope,state);return context.skip()}}};LetScoping.prototype.getLetReferences=function(){var block=this.block;var declarators=block._letDeclarators||[];var declar;for(var i=0;i<declarators.length;i++){declar=declarators[i];_.extend(this.outsideLetReferences,t.getIds(declar,true))}if(block.body){for(i=0;i<block.body.length;i++){declar=block.body[i];if(isLet(declar,block)){declarators=declarators.concat(declar.declarations)}}}for(i=0;i<declarators.length;i++){declar=declarators[i];var keys=t.getIds(declar,true);_.extend(this.letReferences,keys);this.hasLetReferences=true}if(!this.hasLetReferences)return;standardiseLets(declarators);var state={letReferences:this.letReferences,closurify:false};traverse(this.block,letReferenceBlockVisitor,this.scope,state);return state.closurify};var loopVisitor={enter:function(node,parent,scope,context,state){var replace;if(t.isFunction(node)||t.isLoop(node)){return context.skip()}if(node&&!node.label&&state.isLoop){if(t.isBreakStatement(node)){if(t.isSwitchCase(parent))return;state.hasBreak=true;replace=t.returnStatement(t.literal("break"))}else if(t.isContinueStatement(node)){state.hasContinue=true;replace=t.returnStatement(t.literal("continue"))}}if(t.isReturnStatement(node)){state.hasReturn=true;replace=t.returnStatement(t.objectExpression([t.property("init",t.identifier("v"),node.argument||t.identifier("undefined"))]))}if(replace)return t.inherits(replace,node)}};LetScoping.prototype.checkLoop=function(){var state={hasContinue:false,hasReturn:false,hasBreak:false,isLoop:!!this.loopParent};traverse(this.block,loopVisitor,this.scope,state);return state};var hoistVarDeclarationsVisitor={enter:function(node,parent,scope,context,self){if(t.isForStatement(node)){if(isVar(node.init,node)){node.init=t.sequenceExpression(self.pushDeclar(node.init))}}else if(t.isFor(node)){if(isVar(node.left,node)){node.left=node.left.declarations[0].id}}else if(isVar(node,parent)){return self.pushDeclar(node).map(t.expressionStatement)}else if(t.isFunction(node)){return context.skip()}}};LetScoping.prototype.hoistVarDeclarations=function(){traverse(this.block,hoistVarDeclarationsVisitor,this.scope,this)};LetScoping.prototype.pushDeclar=function(node){this.body.push(t.variableDeclaration(node.kind,node.declarations.map(function(declar){return t.variableDeclarator(declar.id)})));var replace=[];for(var i=0;i<node.declarations.length;i++){var declar=node.declarations[i];if(!declar.init)continue;var expr=t.assignmentExpression("=",declar.id,declar.init);replace.push(t.inherits(expr,declar))}return replace};LetScoping.prototype.build=function(ret,call){var has=this.has;if(has.hasReturn||has.hasBreak||has.hasContinue){this.buildHas(ret,call)}else{this.body.push(t.expressionStatement(call))}};LetScoping.prototype.buildHas=function(ret,call){var body=this.body;body.push(t.variableDeclaration("var",[t.variableDeclarator(ret,call)]));var loopParent=this.loopParent;var retCheck;var has=this.has;var cases=[];if(has.hasReturn){retCheck=util.template("let-scoping-return",{RETURN:ret})}if(has.hasBreak||has.hasContinue){if(!loopParent){throw new Error("Has no loop parent but we're trying to reassign breaks "+"and continues, something is going wrong here.")}var label=loopParent.label=loopParent.label||this.scope.generateUidIdentifier("loop");if(has.hasBreak){cases.push(t.switchCase(t.literal("break"),[t.breakStatement(label)]))}if(has.hasContinue){cases.push(t.switchCase(t.literal("continue"),[t.continueStatement(label)]))}if(has.hasReturn){cases.push(t.switchCase(null,[retCheck]))}if(cases.length===1){var single=cases[0];body.push(t.ifStatement(t.binaryExpression("===",ret,single.test),single.consequent[0]))}else{body.push(t.switchStatement(ret,cases))}}else{if(has.hasReturn)body.push(retCheck)}}},{"../../../helpers/object":25,"../../../traverse":97,"../../../types":101,"../../../util":104,lodash:164}],55:[function(require,module,exports){"use strict";var ReplaceSupers=require("../../helpers/replace-supers");var nameMethod=require("../../helpers/name-method");var util=require("../../../util");var t=require("../../../types");exports.ClassDeclaration=function(node,parent,scope,context,file){return new Class(node,file,scope,true).run()};exports.ClassExpression=function(node,parent,scope,context,file){if(!node.id){if(t.isProperty(parent)&&parent.value===node&&!parent.computed&&t.isIdentifier(parent.key)){node.id=parent.key}if(t.isVariableDeclarator(parent)&&t.isIdentifier(parent.id)){node.id=parent.id}}return new Class(node,file,scope,false).run()};function Class(node,file,scope,isStatement){this.isStatement=isStatement;this.scope=scope;this.node=node;this.file=file;this.hasInstanceMutators=false;this.hasStaticMutators=false;this.instanceMutatorMap={};this.staticMutatorMap={};this.hasConstructor=false;this.className=node.id||scope.generateUidIdentifier("class");this.superName=node.superClass;this.isLoose=file.isLoose("es6.classes")}Class.prototype.run=function(){var superName=this.superName;var className=this.className;var file=this.file;var body=this.body=[];var constructor;if(this.node.id){constructor=t.functionDeclaration(className,[],t.blockStatement([]));body.push(constructor)}else{constructor=t.functionExpression(null,[],t.blockStatement([]));body.push(t.variableDeclaration("var",[t.variableDeclarator(className,constructor)]))}this.constructor=constructor;var closureParams=[];var closureArgs=[];if(superName){closureArgs.push(superName);if(!t.isIdentifier(superName)){var superRef=this.scope.generateUidBasedOnNode(superName,this.file);superName=superRef}closureParams.push(superName);this.superName=superName;body.push(t.expressionStatement(t.callExpression(file.addHelper("inherits"),[className,superName])))}this.buildBody();t.inheritsComments(body[0],this.node);var init;if(body.length===1){init=t.toExpression(constructor)}else{body.push(t.returnStatement(className));init=t.callExpression(t.functionExpression(null,closureParams,t.blockStatement(body)),closureArgs)}if(this.isStatement){return t.variableDeclaration("let",[t.variableDeclarator(className,init)])}else{return init}};Class.prototype.buildBody=function(){var constructor=this.constructor;var className=this.className;var superName=this.superName;var classBody=this.node.body.body;var body=this.body;for(var i=0;i<classBody.length;i++){var node=classBody[i];if(t.isMethodDefinition(node)){var replaceSupers=new ReplaceSupers({methodNode:node,className:this.className,superName:this.superName,isLoose:this.isLoose,scope:this.scope,file:this.file});replaceSupers.replace();if(node.key.name==="constructor"){this.pushConstructor(node)}else{this.pushMethod(node)}}else if(t.isPrivateDeclaration(node)){this.closure=true;body.unshift(node)}}if(!this.hasConstructor&&superName&&!t.isFalsyExpression(superName)){var defaultConstructorTemplate="class-super-constructor-call";if(this.isLoose)defaultConstructorTemplate+="-loose";constructor.body.body.push(util.template(defaultConstructorTemplate,{CLASS_NAME:className,SUPER_NAME:this.superName},true))}var instanceProps;var staticProps;if(this.hasInstanceMutators){instanceProps=util.buildDefineProperties(this.instanceMutatorMap)}if(this.hasStaticMutators){staticProps=util.buildDefineProperties(this.staticMutatorMap)}if(instanceProps||staticProps){staticProps=staticProps||t.literal(null);var args=[className,staticProps];if(instanceProps)args.push(instanceProps);body.push(t.expressionStatement(t.callExpression(this.file.addHelper("prototype-properties"),args)))}};Class.prototype.pushMethod=function(node){var methodName=node.key;var kind=node.kind;if(kind===""){nameMethod.property(node,this.file,this.scope);if(this.isLoose){var className=this.className;if(!node.static)className=t.memberExpression(className,t.identifier("prototype"));methodName=t.memberExpression(className,methodName,node.computed);var expr=t.expressionStatement(t.assignmentExpression("=",methodName,node.value));t.inheritsComments(expr,node);this.body.push(expr);return}kind="value"}var mutatorMap=this.instanceMutatorMap;if(node.static){this.hasStaticMutators=true;mutatorMap=this.staticMutatorMap}else{this.hasInstanceMutators=true}util.pushMutatorMap(mutatorMap,methodName,kind,node.computed,node)};Class.prototype.pushConstructor=function(method){if(method.kind){throw this.file.errorWithNode(method,"illegal kind for constructor method")}var construct=this.constructor;var fn=method.value;this.hasConstructor=true;t.inherits(construct,fn);t.inheritsComments(construct,method);construct._ignoreUserWhitespace=true;construct.params=fn.params;construct.body=fn.body}},{"../../../types":101,"../../../util":104,"../../helpers/name-method":32,"../../helpers/replace-supers":34}],56:[function(require,module,exports){"use strict";var traverse=require("../../../traverse");var t=require("../../../types");var visitor={enter:function(node,parent,scope,context,state){if(t.isDeclaration(node)||t.isAssignmentExpression(node)){var ids=t.getIds(node,true);
for(var key in ids){var id=ids[key];var constant=state.constants[key];if(!constant)continue;if(id===constant)continue;throw state.file.errorWithNode(id,key+" is read-only")}}else if(t.isScope(node)){context.skip()}}};exports.Scope=function(node,parent,scope,context,file){traverse(node,visitor,scope,{constants:scope.getAllOfKind("const"),file:file})};exports.VariableDeclaration=function(node){if(node.kind==="const")node.kind="let"}},{"../../../traverse":97,"../../../types":101}],57:[function(require,module,exports){"use strict";var t=require("../../../types");var buildVariableAssign=function(opts,id,init){var op=opts.operator;if(t.isMemberExpression(id))op="=";var node;if(op){node=t.expressionStatement(t.assignmentExpression(op,id,init))}else{node=t.variableDeclaration(opts.kind,[t.variableDeclarator(id,init)])}node._blockHoist=opts.blockHoist;return node};var buildVariableDeclar=function(opts,id,init){var declar=t.variableDeclaration("var",[t.variableDeclarator(id,init)]);declar._blockHoist=opts.blockHoist;return declar};var push=function(opts,nodes,elem,parentId){if(t.isObjectPattern(elem)){pushObjectPattern(opts,nodes,elem,parentId)}else if(t.isArrayPattern(elem)){pushArrayPattern(opts,nodes,elem,parentId)}else if(t.isAssignmentPattern(elem)){pushAssignmentPattern(opts,nodes,elem,parentId)}else{nodes.push(buildVariableAssign(opts,elem,parentId))}};var pushAssignmentPattern=function(opts,nodes,pattern,parentId){var tempParentId=opts.scope.generateUidBasedOnNode(parentId,opts.file);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(tempParentId,parentId)]));nodes.push(buildVariableAssign(opts,pattern.left,t.conditionalExpression(t.binaryExpression("===",tempParentId,t.identifier("undefined")),pattern.right,tempParentId)))};var pushObjectPattern=function(opts,nodes,pattern,parentId){for(var i=0;i<pattern.properties.length;i++){var prop=pattern.properties[i];if(t.isSpreadProperty(prop)){var keys=[];for(var i2=0;i2<pattern.properties.length;i2++){var prop2=pattern.properties[i2];if(i2>=i)break;if(t.isSpreadProperty(prop2))continue;var key=prop2.key;if(t.isIdentifier(key)){key=t.literal(prop2.key.name)}keys.push(key)}keys=t.arrayExpression(keys);var value=t.callExpression(opts.file.addHelper("object-without-properties"),[parentId,keys]);nodes.push(buildVariableAssign(opts,prop.argument,value))}else{if(t.isLiteral(prop.key))prop.computed=true;var pattern2=prop.value;var patternId2=t.memberExpression(parentId,prop.key,prop.computed);if(t.isPattern(pattern2)){push(opts,nodes,pattern2,patternId2)}else{nodes.push(buildVariableAssign(opts,pattern2,patternId2))}}}};var pushArrayPattern=function(opts,nodes,pattern,parentId){if(!pattern.elements)return;var i;var hasRest=false;for(i=0;i<pattern.elements.length;i++){if(t.isRestElement(pattern.elements[i])){hasRest=true;break}}var toArray=opts.file.toArray(parentId,!hasRest&&pattern.elements.length);var _parentId=opts.scope.generateUidBasedOnNode(parentId,opts.file);nodes.push(buildVariableDeclar(opts,_parentId,toArray));parentId=_parentId;for(i=0;i<pattern.elements.length;i++){var elem=pattern.elements[i];if(!elem)continue;i=+i;var newPatternId;if(t.isRestElement(elem)){newPatternId=opts.file.toArray(parentId);if(i>0){newPatternId=t.callExpression(t.memberExpression(newPatternId,t.identifier("slice")),[t.literal(i)])}elem=elem.argument}else{newPatternId=t.memberExpression(parentId,t.literal(i),true)}push(opts,nodes,elem,newPatternId)}};var pushPattern=function(opts){var nodes=opts.nodes;var pattern=opts.pattern;var parentId=opts.id;var scope=opts.scope;if(!t.isArrayExpression(parentId)&&!t.isMemberExpression(parentId)&&!t.isIdentifier(parentId)){var key=scope.generateUidBasedOnNode(parentId);nodes.push(buildVariableDeclar(opts,key,parentId));parentId=key}push(opts,nodes,pattern,parentId)};exports.ForInStatement=exports.ForOfStatement=function(node,parent,scope,context,file){var declar=node.left;if(!t.isVariableDeclaration(declar))return;var pattern=declar.declarations[0].id;if(!t.isPattern(pattern))return;var key=scope.generateUidIdentifier("ref");node.left=t.variableDeclaration(declar.kind,[t.variableDeclarator(key,null)]);var nodes=[];push({kind:declar.kind,file:file,scope:scope},nodes,pattern,key);t.ensureBlock(node);var block=node.body;block.body=nodes.concat(block.body)};exports.Function=function(node,parent,scope,context,file){var nodes=[];var hasDestructuring=false;node.params=node.params.map(function(pattern,i){if(!t.isPattern(pattern))return pattern;hasDestructuring=true;var parentId=scope.generateUidIdentifier("ref");pushPattern({blockHoist:node.params.length-i,pattern:pattern,nodes:nodes,scope:scope,file:file,kind:"var",id:parentId});return parentId});if(!hasDestructuring)return;t.ensureBlock(node);var block=node.body;block.body=nodes.concat(block.body)};exports.CatchClause=function(node,parent,scope,context,file){var pattern=node.param;if(!t.isPattern(pattern))return;var ref=scope.generateUidIdentifier("ref");node.param=ref;var nodes=[];push({kind:"var",file:file,scope:scope},nodes,pattern,ref);node.body.body=nodes.concat(node.body.body)};exports.ExpressionStatement=function(node,parent,scope,context,file){var expr=node.expression;if(expr.type!=="AssignmentExpression")return;if(!t.isPattern(expr.left))return;if(file.isConsequenceExpressionStatement(node))return;var nodes=[];var ref=scope.generateUidIdentifier("ref");nodes.push(t.variableDeclaration("var",[t.variableDeclarator(ref,expr.right)]));push({operator:expr.operator,file:file,scope:scope},nodes,expr.left,ref);return nodes};exports.AssignmentExpression=function(node,parent,scope,context,file){if(!t.isPattern(node.left))return;var ref=scope.generateUidIdentifier("temp");scope.push({key:ref.name,id:ref});var nodes=[];nodes.push(t.assignmentExpression("=",ref,node.right));push({operator:node.operator,file:file,scope:scope},nodes,node.left,ref);nodes.push(ref);return t.toSequenceExpression(nodes,scope)};exports.VariableDeclaration=function(node,parent,scope,context,file){if(t.isForInStatement(parent)||t.isForOfStatement(parent))return;var nodes=[];var i;var declar;var hasPattern=false;for(i=0;i<node.declarations.length;i++){declar=node.declarations[i];if(t.isPattern(declar.id)){hasPattern=true;break}}if(!hasPattern)return;for(i=0;i<node.declarations.length;i++){declar=node.declarations[i];var patternId=declar.init;var pattern=declar.id;var opts={pattern:pattern,nodes:nodes,scope:scope,kind:node.kind,file:file,id:patternId};if(t.isPattern(pattern)&&patternId){pushPattern(opts);if(+i!==node.declarations.length-1){t.inherits(nodes[nodes.length-1],declar)}}else{nodes.push(t.inherits(buildVariableAssign(opts,declar.id,declar.init),declar))}}if(!t.isProgram(parent)&&!t.isBlockStatement(parent)){declar=null;for(i=0;i<nodes.length;i++){node=nodes[i];declar=declar||t.variableDeclaration(node.kind,[]);if(!t.isVariableDeclaration(node)&&declar.kind!==node.kind){throw file.errorWithNode(node,"Cannot use this node within the current parent")}declar.declarations=declar.declarations.concat(node.declarations)}return declar}return nodes}},{"../../../types":101}],58:[function(require,module,exports){"use strict";var util=require("../../../util");var t=require("../../../types");exports.ForOfStatement=function(node,parent,scope,context,file){var callback=spec;if(file.isLoose("es6.forOf"))callback=loose;var build=callback(node,parent,scope,context,file);var declar=build.declar;var loop=build.loop;var block=loop.body;t.inheritsComments(loop,node);t.ensureBlock(node);if(declar){if(build.shouldUnshift){block.body.unshift(declar)}else{block.body.push(declar)}}block.body=block.body.concat(node.body.body);loop._scopeInfo=node._scopeInfo;return loop};var loose=function(node,parent,scope,context,file){var left=node.left;var declar,id;if(t.isIdentifier(left)||t.isPattern(left)){id=left}else if(t.isVariableDeclaration(left)){id=left.declarations[0].id;declar=t.variableDeclaration(left.kind,[t.variableDeclarator(id)])}else{throw file.errorWithNode(left,"Unknown node type "+left.type+" in ForOfStatement")}var loop=util.template("for-of-loose",{LOOP_OBJECT:scope.generateUidIdentifier("iterator"),IS_ARRAY:scope.generateUidIdentifier("isArray"),OBJECT:node.right,INDEX:scope.generateUidIdentifier("i"),ID:id});return{shouldUnshift:true,declar:declar,loop:loop}};var spec=function(node,parent,scope,context,file){var left=node.left;var declar;var stepKey=scope.generateUidIdentifier("step");var stepValue=t.memberExpression(stepKey,t.identifier("value"));if(t.isIdentifier(left)||t.isPattern(left)){declar=t.expressionStatement(t.assignmentExpression("=",left,stepValue))}else if(t.isVariableDeclaration(left)){declar=t.variableDeclaration(left.kind,[t.variableDeclarator(left.declarations[0].id,stepValue)])}else{throw file.errorWithNode(left,"Unknown node type "+left.type+" in ForOfStatement")}var loop=util.template("for-of",{ITERATOR_KEY:scope.generateUidIdentifier("iterator"),STEP_KEY:stepKey,OBJECT:node.right});return{declar:declar,loop:loop}}},{"../../../types":101,"../../../util":104}],59:[function(require,module,exports){"use strict";var t=require("../../../types");exports.ImportDeclaration=function(node,parent,scope,context,file){var nodes=[];if(node.specifiers.length){for(var i=0;i<node.specifiers.length;i++){file.moduleFormatter.importSpecifier(node.specifiers[i],node,nodes,parent)}}else{file.moduleFormatter.importDeclaration(node,nodes,parent)}if(nodes.length===1){nodes[0]._blockHoist=node._blockHoist}return nodes};exports.ExportDeclaration=function(node,parent,scope,context,file){var nodes=[];var i;if(node.declaration){if(t.isVariableDeclaration(node.declaration)){var declar=node.declaration.declarations[0];declar.init=declar.init||t.identifier("undefined")}file.moduleFormatter.exportDeclaration(node,nodes,parent)}else if(node.specifiers){for(i=0;i<node.specifiers.length;i++){file.moduleFormatter.exportSpecifier(node.specifiers[i],node,nodes,parent)}}if(node._blockHoist){for(i=0;i<nodes.length;i++){nodes[i]._blockHoist=node._blockHoist}}return nodes}},{"../../../types":101}],60:[function(require,module,exports){"use strict";var util=require("../../../util");var t=require("../../../types");var hasDefaults=function(node){for(var i=0;i<node.params.length;i++){if(t.isAssignmentPattern(node.params[i]))return true}return false};exports.Function=function(node,parent,scope){if(!hasDefaults(node))return;t.ensureBlock(node);var iife=false;var body=[];var argsIdentifier=t.identifier("arguments");argsIdentifier._ignoreAliasFunctions=true;var lastNonDefaultParam=0;for(var i=0;i<node.params.length;i++){var param=node.params[i];if(!t.isAssignmentPattern(param)){lastNonDefaultParam=+i+1;continue}var left=param.left;var right=param.right;node.params[i]=scope.generateUidIdentifier("x");var localDeclar=scope.get(left.name,true);if(localDeclar!==left){iife=true}var defNode=util.template("default-parameter",{VARIABLE_NAME:left,DEFAULT_VALUE:right,ARGUMENT_KEY:t.literal(+i),ARGUMENTS:argsIdentifier},true);defNode._blockHoist=node.params.length-i;body.push(defNode)}node.params=node.params.slice(0,lastNonDefaultParam);if(iife){var container=t.functionExpression(null,[],node.body,node.generator);container._aliasFunction=true;body.push(t.returnStatement(t.callExpression(container,[])));node.body=t.blockStatement(body)}else{node.body.body=body.concat(node.body.body)}}},{"../../../types":101,"../../../util":104}],61:[function(require,module,exports){"use strict";var util=require("../../../util");var t=require("../../../types");var hasRest=function(node){return t.isRestElement(node.params[node.params.length-1])};exports.Function=function(node,parent,scope){if(!hasRest(node))return;var rest=node.params.pop().argument;t.ensureBlock(node);var argsId=t.identifier("arguments");argsId._ignoreAliasFunctions=true;var start=t.literal(node.params.length);var key=scope.generateUidIdentifier("key");var len=scope.generateUidIdentifier("len");var arrKey=key;var arrLen=len;if(node.params.length){arrKey=t.binaryExpression("-",key,start);arrLen=t.conditionalExpression(t.binaryExpression(">",len,start),t.binaryExpression("-",len,start),t.literal(0))}if(t.isPattern(rest)){var pattern=rest;rest=scope.generateUidIdentifier("ref");var restDeclar=t.variableDeclaration("var",[t.variableDeclarator(pattern,rest)]);restDeclar._blockHoist=node.params.length+1;node.body.body.unshift(restDeclar)}node.body.body.unshift(util.template("rest",{ARGUMENTS:argsId,ARRAY_KEY:arrKey,ARRAY_LEN:arrLen,START:start,ARRAY:rest,KEY:key,LEN:len}))}},{"../../../types":101,"../../../util":104}],62:[function(require,module,exports){"use strict";var t=require("../../../types");exports.ObjectExpression=function(node,parent,scope,context,file){var hasComputed=false;for(var i=0;i<node.properties.length;i++){hasComputed=t.isProperty(node.properties[i],{computed:true,kind:"init"});if(hasComputed)break}if(!hasComputed)return;var initProps=[];var objId=scope.generateUidBasedOnNode(parent);var body=[];var container=t.functionExpression(null,[],t.blockStatement(body));container._aliasFunction=true;var callback=spec;if(file.isLoose("es6.properties.computed"))callback=loose;var result=callback(node,body,objId,initProps,file);if(result)return result;body.unshift(t.variableDeclaration("var",[t.variableDeclarator(objId,t.objectExpression(initProps))]));body.push(t.returnStatement(objId));return t.callExpression(container,[])};var loose=function(node,body,objId){for(var i=0;i<node.properties.length;i++){var prop=node.properties[i];body.push(t.expressionStatement(t.assignmentExpression("=",t.memberExpression(objId,prop.key,prop.computed),prop.value)))}};var spec=function(node,body,objId,initProps,file){var props=node.properties;var prop,key;for(var i=0;i<props.length;i++){prop=props[i];if(prop.kind!=="init")continue;key=prop.key;if(!prop.computed&&t.isIdentifier(key)){prop.key=t.literal(key.name)}}var broken=false;for(i=0;i<props.length;i++){prop=props[i];if(prop.computed){broken=true}if(prop.kind!=="init"||!broken||t.isLiteral(t.toComputedKey(prop,prop.key),{value:"__proto__"})){initProps.push(prop);props[i]=null}}for(i=0;i<props.length;i++){prop=props[i];if(!prop)continue;key=prop.key;var bodyNode;if(prop.computed&&t.isMemberExpression(key)&&t.isIdentifier(key.object,{name:"Symbol"})){bodyNode=t.assignmentExpression("=",t.memberExpression(objId,key,true),prop.value)}else{bodyNode=t.callExpression(file.addHelper("define-property"),[objId,key,prop.value])}body.push(t.expressionStatement(bodyNode))}if(body.length===1){var first=body[0].expression;if(t.isCallExpression(first)){first.arguments[0]=t.objectExpression(initProps);return first}}}},{"../../../types":101}],63:[function(require,module,exports){"use strict";var nameMethod=require("../../helpers/name-method");var t=require("../../../types");var _=require("lodash");exports.Property=function(node,parent,scope,context,file){if(node.method){node.method=false;nameMethod.property(node,file,scope)}if(node.shorthand){node.shorthand=false;node.key=t.removeComments(_.clone(node.key))}}},{"../../../types":101,"../../helpers/name-method":32,lodash:164}],64:[function(require,module,exports){"use strict";var t=require("../../../types");var _=require("lodash");var getSpreadLiteral=function(spread,file){return file.toArray(spread.argument)};var hasSpread=function(nodes){for(var i=0;i<nodes.length;i++){if(t.isSpreadElement(nodes[i])){return true}}return false};var build=function(props,file){var nodes=[];var _props=[];var push=function(){if(!_props.length)return;nodes.push(t.arrayExpression(_props));_props=[]};for(var i=0;i<props.length;i++){var prop=props[i];if(t.isSpreadElement(prop)){push();nodes.push(getSpreadLiteral(prop,file))}else{_props.push(prop)}}push();return nodes};exports.ArrayExpression=function(node,parent,scope,context,file){var elements=node.elements;if(!hasSpread(elements))return;var nodes=build(elements,file);var first=nodes.shift();if(!t.isArrayExpression(first)){nodes.unshift(first);first=t.arrayExpression([])}return t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes)};exports.CallExpression=function(node,parent,scope,context,file){var args=node.arguments;if(!hasSpread(args))return;var contextLiteral=t.identifier("undefined");node.arguments=[];var nodes;if(args.length===1&&args[0].argument.name==="arguments"){nodes=[args[0].argument]}else{nodes=build(args,file)}var first=nodes.shift();if(nodes.length){node.arguments.push(t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes))}else{node.arguments.push(first)}var callee=node.callee;if(t.isMemberExpression(callee)){var temp=scope.generateTempBasedOnNode(callee.object);if(temp){callee.object=t.assignmentExpression("=",temp,callee.object);contextLiteral=temp}else{contextLiteral=callee.object}t.appendToMemberExpression(callee,t.identifier("apply"))}else{node.callee=t.memberExpression(node.callee,t.identifier("apply"))}node.arguments.unshift(contextLiteral)};exports.NewExpression=function(node,parent,scope,context,file){var args=node.arguments;if(!hasSpread(args))return;var nativeType=t.isIdentifier(node.callee)&&_.contains(t.NATIVE_TYPE_NAMES,node.callee.name);var nodes=build(args,file);if(nativeType){nodes.unshift(t.arrayExpression([t.literal(null)]))}var first=nodes.shift();if(nodes.length){args=t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes)}else{args=first}if(nativeType){return t.newExpression(t.callExpression(t.memberExpression(file.addHelper("bind"),t.identifier("apply")),[node.callee,args]),[])}else{return t.callExpression(file.addHelper("apply-constructor"),[node.callee,args])}}},{"../../../types":101,lodash:164}],65:[function(require,module,exports){"use strict";var t=require("../../../types");var buildBinaryExpression=function(left,right){return t.binaryExpression("+",left,right)};exports.TaggedTemplateExpression=function(node,parent,scope,context,file){var args=[];var quasi=node.quasi;var strings=[];var raw=[];for(var i=0;i<quasi.quasis.length;i++){var elem=quasi.quasis[i];strings.push(t.literal(elem.value.cooked));raw.push(t.literal(elem.value.raw))}strings=t.arrayExpression(strings);raw=t.arrayExpression(raw);var templateName="tagged-template-literal";if(file.isLoose("es6.templateLiterals"))templateName+="-loose";args.push(t.callExpression(file.addHelper(templateName),[strings,raw]));args=args.concat(quasi.expressions);return t.callExpression(node.tag,args)};exports.TemplateLiteral=function(node){var nodes=[];var i;for(i=0;i<node.quasis.length;i++){var elem=node.quasis[i];nodes.push(t.literal(elem.value.cooked));var expr=node.expressions.shift();if(expr)nodes.push(expr)}if(nodes.length>1){var last=nodes[nodes.length-1];if(t.isLiteral(last,{value:""}))nodes.pop();var root=buildBinaryExpression(nodes.shift(),nodes.shift());for(i=0;i<nodes.length;i++){root=buildBinaryExpression(root,nodes[i])}return root}else{return nodes[0]}}},{"../../../types":101}],66:[function(require,module,exports){"use strict";var rewritePattern=require("regexpu/rewrite-pattern");var _=require("lodash");exports.Literal=function(node){var regex=node.regex;if(!regex)return;var flags=regex.flags.split("");if(regex.flags.indexOf("u")<0)return;_.pull(flags,"u");regex.pattern=rewritePattern(regex.pattern,regex.flags);regex.flags=flags.join("")}},{lodash:164,"regexpu/rewrite-pattern":180}],67:[function(require,module,exports){"use strict";var util=require("../../../util");var t=require("../../../types");exports.experimental=true;var container=function(parent,call,ret,file){if(t.isExpressionStatement(parent)&&!file.isConsequenceExpressionStatement(parent)){return call}else{var exprs=[];if(t.isSequenceExpression(call)){exprs=call.expressions}else{exprs.push(call)}exprs.push(ret);return t.sequenceExpression(exprs)}};exports.AssignmentExpression=function(node,parent,scope,context,file){var left=node.left;if(!t.isVirtualPropertyExpression(left))return;var value=node.right;var temp;if(!t.isExpressionStatement(parent)){temp=scope.generateTempBasedOnNode(node.right);if(temp)value=temp}if(node.operator!=="="){value=t.binaryExpression(node.operator[0],util.template("abstract-expression-get",{PROPERTY:node.property,OBJECT:node.object}),value)}var call=util.template("abstract-expression-set",{PROPERTY:left.property,OBJECT:left.object,VALUE:value});if(temp){call=t.sequenceExpression([t.assignmentExpression("=",temp,node.right),call])}return container(parent,call,value,file)};exports.UnaryExpression=function(node,parent,scope,context,file){var arg=node.argument;if(!t.isVirtualPropertyExpression(arg))return;if(node.operator!=="delete")return;var call=util.template("abstract-expression-delete",{PROPERTY:arg.property,OBJECT:arg.object});return container(parent,call,t.literal(true),file)};exports.CallExpression=function(node,parent,scope){var callee=node.callee;if(!t.isVirtualPropertyExpression(callee))return;var temp=scope.generateTempBasedOnNode(callee.object);var call=util.template("abstract-expression-call",{PROPERTY:callee.property,OBJECT:temp||callee.object});call.arguments=call.arguments.concat(node.arguments);if(temp){return t.sequenceExpression([t.assignmentExpression("=",temp,callee.object),call])}else{return call}};exports.VirtualPropertyExpression=function(node){return util.template("abstract-expression-get",{PROPERTY:node.property,OBJECT:node.object})};exports.PrivateDeclaration=function(node){return t.variableDeclaration("const",node.declarations.map(function(id){return t.variableDeclarator(id,t.newExpression(t.identifier("WeakMap"),[]))}))}},{"../../../types":101,"../../../util":104}],68:[function(require,module,exports){"use strict";var buildComprehension=require("../../helpers/build-comprehension");var traverse=require("../../../traverse");var util=require("../../../util");var t=require("../../../types");exports.experimental=true;exports.ComprehensionExpression=function(node,parent,scope,context,file){var callback=array;if(node.generator)callback=generator;return callback(node,parent,scope,file)};var generator=function(node){var body=[];var container=t.functionExpression(null,[],t.blockStatement(body),true);container._aliasFunction=true;body.push(buildComprehension(node,function(){return t.expressionStatement(t.yieldExpression(node.body))}));return t.callExpression(container,[])};var array=function(node,parent,scope,file){var uid=scope.generateUidBasedOnNode(parent,file);var container=util.template("array-comprehension-container",{KEY:uid});container.callee._aliasFunction=true;var block=container.callee.body;var body=block.body;if(traverse.hasType(node,scope,"YieldExpression",t.FUNCTION_TYPES)){container.callee.generator=true;container=t.yieldExpression(container,true)}var returnStatement=body.pop();body.push(buildComprehension(node,function(){return util.template("array-push",{STATEMENT:node.body,KEY:uid},true)}));body.push(returnStatement);return container}},{"../../../traverse":97,"../../../types":101,"../../../util":104,"../../helpers/build-comprehension":29}],69:[function(require,module,exports){"use strict";exports.experimental=true;var build=require("../../helpers/build-binary-assignment-operator-transformer");var t=require("../../../types");var MATH_POW=t.memberExpression(t.identifier("Math"),t.identifier("pow"));build(exports,{operator:"**",build:function(left,right){return t.callExpression(MATH_POW,[left,right])}})},{"../../../types":101,"../../helpers/build-binary-assignment-operator-transformer":28}],70:[function(require,module,exports){"use strict";var t=require("../../../types");exports.experimental=true;exports.ObjectExpression=function(node,parent,scope,context,file){var hasSpread=false;var i;var prop;for(i=0;i<node.properties.length;i++){prop=node.properties[i];if(t.isSpreadProperty(prop)){hasSpread=true;break}}if(!hasSpread)return;var args=[];var props=[];var push=function(){if(!props.length)return;args.push(t.objectExpression(props));props=[]};for(i=0;i<node.properties.length;i++){prop=node.properties[i];if(t.isSpreadProperty(prop)){push();args.push(prop.argument)}else{props.push(prop)}}push();if(!t.isObjectExpression(args[0])){args.unshift(t.objectExpression([]))}return t.callExpression(file.addHelper("extends"),args)}},{"../../../types":101}],71:[function(require,module,exports){module.exports={useStrict:require("./other/use-strict"),"validation.undeclaredVariableCheck":require("./validation/undeclared-variable-check"),"validation.noForInOfAssignment":require("./validation/no-for-in-of-assignment"),"validation.setters":require("./validation/setters"),"spec.blockScopedFunctions":require("./spec/block-scoped-functions"),"playground.malletOperator":require("./playground/mallet-operator"),"playground.methodBinding":require("./playground/method-binding"),"playground.memoizationOperator":require("./playground/memoization-operator"),"playground.objectGetterMemoization":require("./playground/object-getter-memoization"),react:require("./other/react"),_modulesSplit:require("./internal/modules-split"),"es7.comprehensions":require("./es7/comprehensions"),"es6.arrowFunctions":require("./es6/arrow-functions"),"es6.classes":require("./es6/classes"),asyncToGenerator:require("./other/async-to-generator"),bluebirdCoroutines:require("./other/bluebird-coroutines"),"es7.objectSpread":require("./es7/object-spread"),"es7.exponentiationOperator":require("./es7/exponentiation-operator"),"es6.spread":require("./es6/spread"),"es6.templateLiterals":require("./es6/template-literals"),"es5.properties.mutators":require("./es5/properties.mutators"),"es6.properties.shorthand":require("./es6/properties.shorthand"),"es6.properties.computed":require("./es6/properties.computed"),"es6.forOf":require("./es6/for-of"),"es6.unicodeRegex":require("./es6/unicode-regex"),"es7.abstractReferences":require("./es7/abstract-references"),"es6.constants":require("./es6/constants"),"es6.blockScoping":require("./es6/block-scoping"),"es6.blockScopingTDZ":require("./es6/block-scoping-tdz"),regenerator:require("./other/regenerator"),"es6.parameters.default":require("./es6/parameters.default"),"es6.parameters.rest":require("./es6/parameters.rest"),"es6.destructuring":require("./es6/destructuring"),selfContained:require("./other/self-contained"),"es6.modules":require("./es6/modules"),_blockHoist:require("./internal/block-hoist"),"spec.protoToAssign":require("./spec/proto-to-assign"),_declarations:require("./internal/declarations"),_aliasFunctions:require("./internal/alias-functions"),_moduleFormatter:require("./internal/module-formatter"),"spec.typeofSymbol":require("./spec/typeof-symbol"),"spec.undefinedToVoid":require("./spec/undefined-to-void"),"minification.propertyLiterals":require("./minification/property-literals"),"minification.memberExpressionLiterals":require("./minification/member-expression-literals")}},{"./es5/properties.mutators":51,"./es6/arrow-functions":52,"./es6/block-scoping":54,"./es6/block-scoping-tdz":53,"./es6/classes":55,"./es6/constants":56,"./es6/destructuring":57,"./es6/for-of":58,"./es6/modules":59,"./es6/parameters.default":60,"./es6/parameters.rest":61,"./es6/properties.computed":62,"./es6/properties.shorthand":63,"./es6/spread":64,"./es6/template-literals":65,"./es6/unicode-regex":66,"./es7/abstract-references":67,"./es7/comprehensions":68,"./es7/exponentiation-operator":69,"./es7/object-spread":70,"./internal/alias-functions":72,"./internal/block-hoist":73,"./internal/declarations":74,"./internal/module-formatter":75,"./internal/modules-split":76,"./minification/member-expression-literals":77,"./minification/property-literals":78,"./other/async-to-generator":79,"./other/bluebird-coroutines":80,"./other/react":81,"./other/regenerator":82,"./other/self-contained":83,"./other/use-strict":84,"./playground/mallet-operator":85,"./playground/memoization-operator":86,"./playground/method-binding":87,"./playground/object-getter-memoization":88,"./spec/block-scoped-functions":89,"./spec/proto-to-assign":90,"./spec/typeof-symbol":91,"./spec/undefined-to-void":92,"./validation/no-for-in-of-assignment":93,"./validation/setters":94,"./validation/undeclared-variable-check":95}],72:[function(require,module,exports){"use strict";var traverse=require("../../../traverse");var t=require("../../../types");var functionChildrenVisitor={enter:function(node,parent,scope,context,state){if(t.isFunction(node)&&!node._aliasFunction){return context.skip()}if(node._ignoreAliasFunctions)return context.skip();var getId;if(t.isIdentifier(node)&&node.name==="arguments"){getId=state.getArgumentsId}else if(t.isThisExpression(node)){getId=state.getThisId}else{return}if(t.isReferenced(node,parent))return getId()}};var functionVisitor={enter:function(node,parent,scope,context,state){if(!node._aliasFunction){if(t.isFunction(node)){return context.skip()}else{return}}traverse(node,functionChildrenVisitor,scope,state);return context.skip()}};var go=function(getBody,node,scope){var argumentsId;var thisId;var state={getArgumentsId:function(){return argumentsId=argumentsId||scope.generateUidIdentifier("arguments")},getThisId:function(){return thisId=thisId||scope.generateUidIdentifier("this")}};traverse(node,functionVisitor,scope,state);var body;var pushDeclaration=function(id,init){body=body||getBody();body.unshift(t.variableDeclaration("var",[t.variableDeclarator(id,init)]))};if(argumentsId){pushDeclaration(argumentsId,t.identifier("arguments"))}if(thisId){pushDeclaration(thisId,t.thisExpression())}};exports.Program=function(node,parent,scope){go(function(){return node.body},node,scope)};exports.FunctionDeclaration=exports.FunctionExpression=function(node,parent,scope){go(function(){t.ensureBlock(node);return node.body.body},node,scope)}},{"../../../traverse":97,"../../../types":101}],73:[function(require,module,exports){"use strict";var useStrict=require("../../helpers/use-strict");var _=require("lodash");exports.BlockStatement=exports.Program={exit:function(node){var hasChange=false;for(var i=0;i<node.body.length;i++){var bodyNode=node.body[i];if(bodyNode&&bodyNode._blockHoist!=null)hasChange=true}if(!hasChange)return;useStrict.wrap(node,function(){var nodePriorities=_.groupBy(node.body,function(bodyNode){var priority=bodyNode._blockHoist;if(priority==null)priority=1;if(priority===true)priority=2;return priority});node.body=_.flatten(_.values(nodePriorities).reverse())})}}},{"../../helpers/use-strict":35,lodash:164}],74:[function(require,module,exports){"use strict";var useStrict=require("../../helpers/use-strict");var t=require("../../../types");exports.secondPass=true;exports.BlockStatement=exports.Program=function(node){if(!node._declarations)return;var kinds={};var kind;useStrict.wrap(node,function(){for(var i in node._declarations){var declar=node._declarations[i];kind=declar.kind||"var";var declarNode=t.variableDeclarator(declar.id,declar.init);if(!declar.init){kinds[kind]=kinds[kind]||[];kinds[kind].push(declarNode)}else{node.body.unshift(t.variableDeclaration(kind,[declarNode]))}}for(kind in kinds){node.body.unshift(t.variableDeclaration(kind,kinds[kind]))}});node._declarations=null}},{"../../../types":101,"../../helpers/use-strict":35}],75:[function(require,module,exports){"use strict";var useStrict=require("../../helpers/use-strict");exports.ast={exit:function(ast,file){if(!file.transformers["es6.modules"].canRun())return;useStrict.wrap(ast.program,function(){ast.program.body=file.dynamicImports.concat(ast.program.body)});if(file.moduleFormatter.transform){file.moduleFormatter.transform(ast)}}}},{"../../helpers/use-strict":35}],76:[function(require,module,exports){"use strict";var t=require("../../../types");exports.ExportDeclaration=function(node,parent,scope){var declar=node.declaration;if(node.default){if(t.isClassDeclaration(declar)){node.declaration=declar.id;return[declar,node]}else if(t.isClassExpression(declar)){var temp=scope.generateUidIdentifier("default");declar=t.variableDeclaration("var",[t.variableDeclarator(temp,declar)]);node.declaration=temp;return[declar,node]}}else{if(t.isFunctionDeclaration(declar)){node.specifiers=[t.importSpecifier(declar.id,declar.id)];node.declaration=null;
node._blockHoist=2;return[declar,node]}}}},{"../../../types":101}],77:[function(require,module,exports){"use strict";var t=require("../../../types");exports.MemberExpression=function(node){var prop=node.property;if(node.computed&&t.isLiteral(prop)&&t.isValidIdentifier(prop.value)){node.property=t.identifier(prop.value);node.computed=false}else if(!node.computed&&t.isIdentifier(prop)&&!t.isValidIdentifier(prop.name)){node.property=t.literal(prop.name);node.computed=true}}},{"../../../types":101}],78:[function(require,module,exports){"use strict";var t=require("../../../types");exports.Property=function(node){var key=node.key;if(t.isLiteral(key)&&t.isValidIdentifier(key.value)){node.key=t.identifier(key.value);node.computed=false}else if(!node.computed&&t.isIdentifier(key)&&!t.isValidIdentifier(key.name)){node.key=t.literal(key.name)}}},{"../../../types":101}],79:[function(require,module,exports){"use strict";var remapAsyncToGenerator=require("../../helpers/remap-async-to-generator");var bluebirdCoroutines=require("./bluebird-coroutines");exports.optional=true;exports.manipulateOptions=bluebirdCoroutines.manipulateOptions;exports.Function=function(node,parent,scope,context,file){if(!node.async||node.generator)return;return remapAsyncToGenerator(node,file.addHelper("async-to-generator"),scope)}},{"../../helpers/remap-async-to-generator":33,"./bluebird-coroutines":80}],80:[function(require,module,exports){"use strict";var remapAsyncToGenerator=require("../../helpers/remap-async-to-generator");var t=require("../../../types");exports.manipulateOptions=function(opts){opts.experimental=true;opts.blacklist.push("regenerator")};exports.optional=true;exports.Function=function(node,parent,scope,context,file){if(!node.async||node.generator)return;return remapAsyncToGenerator(node,t.memberExpression(file.addImport("bluebird"),t.identifier("coroutine")),scope)}},{"../../../types":101,"../../helpers/remap-async-to-generator":33}],81:[function(require,module,exports){"use strict";var esutils=require("esutils");var t=require("../../../types");exports.JSXIdentifier=function(node){if(esutils.keyword.isIdentifierName(node.name)){node.type="Identifier"}else{return t.literal(node.name)}};exports.JSXNamespacedName=function(node,parent,scope,context,file){throw file.errorWithNode(node,"Namespace tags are not supported. ReactJSX is not XML.")};exports.JSXMemberExpression={exit:function(node){node.computed=t.isLiteral(node.property);node.type="MemberExpression"}};exports.JSXExpressionContainer=function(node){return node.expression};exports.JSXAttribute={exit:function(node){var value=node.value||t.literal(true);return t.inherits(t.property("init",node.name,value),node)}};var isCompatTag=function(tagName){return/^[a-z]|\-/.test(tagName)};exports.JSXOpeningElement={exit:function(node,parent,scope,context,file){var reactCompat=file.opts.reactCompat;var tagExpr=node.name;var args=[];var tagName;if(t.isIdentifier(tagExpr)){tagName=tagExpr.name}else if(t.isLiteral(tagExpr)){tagName=tagExpr.value}if(!reactCompat){if(tagName&&isCompatTag(tagName)){args.push(t.literal(tagName))}else{args.push(tagExpr)}}var attribs=node.attributes;if(attribs.length){attribs=buildJSXOpeningElementAttributes(attribs,file)}else{attribs=t.literal(null)}args.push(attribs);if(reactCompat){if(tagName&&isCompatTag(tagName)){return t.callExpression(t.memberExpression(t.memberExpression(t.identifier("React"),t.identifier("DOM")),tagExpr,t.isLiteral(tagExpr)),args)}}else{tagExpr=t.memberExpression(t.identifier("React"),t.identifier("createElement"))}return t.callExpression(tagExpr,args)}};var buildJSXOpeningElementAttributes=function(attribs,file){var _props=[];var objs=[];var pushProps=function(){if(!_props.length)return;objs.push(t.objectExpression(_props));_props=[]};while(attribs.length){var prop=attribs.shift();if(t.isJSXSpreadAttribute(prop)){pushProps();objs.push(prop.argument)}else{_props.push(prop)}}pushProps();if(objs.length===1){attribs=objs[0]}else{if(!t.isObjectExpression(objs[0])){objs.unshift(t.objectExpression([]))}attribs=t.callExpression(file.addHelper("extends"),objs)}return attribs};exports.JSXElement={exit:function(node){var callExpr=node.openingElement;for(var i=0;i<node.children.length;i++){var child=node.children[i];if(t.isLiteral(child)&&typeof child.value==="string"){cleanJSXElementLiteralChild(child,callExpr.arguments);continue}else if(t.isJSXEmptyExpression(child)){continue}callExpr.arguments.push(child)}if(callExpr.arguments.length>=3){callExpr._prettyCall=true}return t.inherits(callExpr,node)}};var cleanJSXElementLiteralChild=function(child,args){var lines=child.value.split(/\r\n|\n|\r/);for(var i=0;i<lines.length;i++){var line=lines[i];var isFirstLine=i===0;var isLastLine=i===lines.length-1;var trimmedLine=line.replace(/\t/g," ");if(!isFirstLine){trimmedLine=trimmedLine.replace(/^[ ]+/,"")}if(!isLastLine){trimmedLine=trimmedLine.replace(/[ ]+$/,"")}if(trimmedLine){args.push(t.literal(trimmedLine))}}};var isCreateClass=function(call){if(!call||!t.isCallExpression(call))return false;var callee=call.callee;if(!t.isMemberExpression(callee))return false;var obj=callee.object;if(!t.isIdentifier(obj,{name:"React"}))return false;var prop=callee.property;if(!t.isIdentifier(prop,{name:"createClass"}))return false;var args=call.arguments;if(args.length!==1)return false;var first=args[0];if(!t.isObjectExpression(first))return;return true};var addDisplayName=function(id,call){if(!isCreateClass(call))return;var props=call.arguments[0].properties;var safe=true;for(var i=0;i<props.length;i++){var prop=props[i];if(t.isIdentifier(prop.key,{name:"displayName"})){safe=false;break}}if(safe){props.unshift(t.property("init",t.identifier("displayName"),t.literal(id)))}};exports.AssignmentExpression=exports.Property=exports.VariableDeclarator=function(node){var left,right;if(t.isAssignmentExpression(node)){left=node.left;right=node.right}else if(t.isProperty(node)){left=node.key;right=node.value}else if(t.isVariableDeclarator(node)){left=node.id;right=node.init}if(t.isMemberExpression(left)){left=left.property}if(t.isIdentifier(left)){addDisplayName(left.name,right)}}},{"../../../types":101,esutils:162}],82:[function(require,module,exports){"use strict";var regenerator=require("regenerator-6to5");exports.ast={before:function(ast,file){regenerator.transform(ast,{includeRuntime:file.opts.includeRegenerator&&"if used"})}}},{"regenerator-6to5":172}],83:[function(require,module,exports){"use strict";var traverse=require("../../../traverse");var util=require("../../../util");var core=require("core-js/library");var t=require("../../../types");var _=require("lodash");var coreHas=function(node){return node.name!=="_"&&_.has(core,node.name)};var ALIASABLE_CONSTRUCTORS=["Symbol","Promise","Map","WeakMap","Set","WeakSet"];var astVisitor={enter:function(node,parent,scope,context,file){var prop;if(t.isMemberExpression(node)&&t.isReferenced(node,parent)){var obj=node.object;prop=node.property;if(!t.isReferenced(obj,node))return;if(!node.computed&&coreHas(obj)&&_.has(core[obj.name],prop.name)){context.skip();return t.prependToMemberExpression(node,file.get("coreIdentifier"))}}else if(t.isReferencedIdentifier(node,parent)&&!t.isMemberExpression(parent)&&_.contains(ALIASABLE_CONSTRUCTORS,node.name)&&!scope.get(node.name,true)){return t.memberExpression(file.get("coreIdentifier"),node)}else if(t.isCallExpression(node)){if(node.arguments.length)return;var callee=node.callee;if(!t.isMemberExpression(callee))return;if(!callee.computed)return;prop=callee.property;if(!t.isIdentifier(prop.object,{name:"Symbol"}))return;if(!t.isIdentifier(prop.property,{name:"iterator"}))return;return util.template("corejs-iterator",{CORE_ID:file.get("coreIdentifier"),VALUE:callee.object})}}};exports.optional=true;exports.ast={enter:function(ast,file){file.setDynamic("runtimeIdentifier",function(){return file.addImport("6to5-runtime/helpers","to5Helpers")});file.setDynamic("coreIdentifier",function(){return file.addImport("6to5-runtime/core-js","core")});file.setDynamic("regeneratorIdentifier",function(){return file.addImport("6to5-runtime/regenerator","regeneratorRuntime")})},after:function(ast,file){traverse(ast,astVisitor,null,file)}};exports.Identifier=function(node,parent,scope,context,file){if(node.name==="regeneratorRuntime"&&t.isReferenced(node,parent)){return file.get("regeneratorIdentifier")}}},{"../../../traverse":97,"../../../types":101,"../../../util":104,"core-js/library":154,lodash:164}],84:[function(require,module,exports){"use strict";var useStrict=require("../../helpers/use-strict");var t=require("../../../types");exports.ast={exit:function(ast){if(!useStrict.has(ast.program)){ast.program.body.unshift(t.expressionStatement(t.literal("use strict")))}}};exports.FunctionDeclaration=exports.FunctionExpression=function(node,parent,scope,context){context.skip()};exports.ThisExpression=function(node,parent,scope,context,file){throw file.errorWithNode(node,"Top level `this` is not allowed",ReferenceError)}},{"../../../types":101,"../../helpers/use-strict":35}],85:[function(require,module,exports){"use strict";var build=require("../../helpers/build-conditional-assignment-operator-transformer");var t=require("../../../types");build(exports,{is:function(node,file){var is=t.isAssignmentExpression(node)&&node.operator==="||=";if(is){var left=node.left;if(!t.isMemberExpression(left)&&!t.isIdentifier(left)){throw file.errorWithNode(left,"Expected type MemeberExpression or Identifier")}return true}},build:function(node){return t.unaryExpression("!",node,true)}})},{"../../../types":101,"../../helpers/build-conditional-assignment-operator-transformer":30}],86:[function(require,module,exports){"use strict";var build=require("../../helpers/build-conditional-assignment-operator-transformer");var t=require("../../../types");build(exports,{is:function(node){var is=t.isAssignmentExpression(node)&&node.operator==="?=";if(is)t.assertMemberExpression(node.left);return is},build:function(node,file){return t.unaryExpression("!",t.callExpression(t.memberExpression(file.addHelper("has-own"),t.identifier("call")),[node.object,node.property]),true)}})},{"../../../types":101,"../../helpers/build-conditional-assignment-operator-transformer":30}],87:[function(require,module,exports){"use strict";var t=require("../../../types");exports.BindMemberExpression=function(node,parent,scope){var object=node.object;var prop=node.property;var temp=scope.generateTempBasedOnNode(node.object);if(temp)object=temp;var call=t.callExpression(t.memberExpression(t.memberExpression(object,prop),t.identifier("bind")),[object].concat(node.arguments));if(temp){return t.sequenceExpression([t.assignmentExpression("=",temp,node.object),call])}else{return call}};exports.BindFunctionExpression=function(node,parent,scope,context,file){var buildCall=function(args){var param=scope.generateUidIdentifier("val");return t.functionExpression(null,[param],t.blockStatement([t.returnStatement(t.callExpression(t.memberExpression(param,node.callee),args))]))};var temp=scope.generateTemp(file,"args");return t.sequenceExpression([t.assignmentExpression("=",temp,t.arrayExpression(node.arguments)),buildCall(node.arguments.map(function(node,i){return t.memberExpression(temp,t.literal(i),true)}))])}},{"../../../types":101}],88:[function(require,module,exports){"use strict";var traverse=require("../../../traverse");var t=require("../../../types");var visitor={enter:function(node,parent,scope,context,state){if(t.isFunction(node))return;if(t.isReturnStatement(node)&&node.argument){node.argument=t.memberExpression(t.callExpression(state.file.addHelper("define-property"),[t.thisExpression(),state.key,node.argument]),state.key,true)}}};exports.Property=exports.MethodDefinition=function(node,parent,scope,context,file){if(node.kind!=="memo")return;node.kind="get";var value=node.value;t.ensureBlock(value);var key=node.key;if(t.isIdentifier(key)&&!node.computed){key=t.literal(key.name)}var state={key:key,file:file};traverse(value,visitor,scope,state)}},{"../../../traverse":97,"../../../types":101}],89:[function(require,module,exports){"use strict";var t=require("../../../types");exports.BlockStatement=function(node,parent){if(t.isFunction(parent)||t.isExportDeclaration(parent)){return}for(var i=0;i<node.body.length;i++){var func=node.body[i];if(!t.isFunctionDeclaration(i))continue;var declar=t.variableDeclaration("let",[t.variableDeclarator(func.id,t.toExpression(func))]);declar._blockHoist=2;func.id=null;func.body[i]=declar}}},{"../../../types":101}],90:[function(require,module,exports){"use strict";var t=require("../../../types");var _=require("lodash");var isProtoKey=function(node){return t.isLiteral(t.toComputedKey(node,node.key),{value:"__proto__"})};var isProtoAssignmentExpression=function(node){var left=node.left;return t.isMemberExpression(left)&&t.isLiteral(t.toComputedKey(left,left.property),{value:"__proto__"})};var buildDefaultsCallExpression=function(expr,ref,file){return t.expressionStatement(t.callExpression(file.addHelper("defaults"),[ref,expr.right]))};exports.optional=true;exports.secondPass=true;exports.AssignmentExpression=function(node,parent,scope,context,file){if(!isProtoAssignmentExpression(node))return;var nodes=[];var left=node.left.object;var temp=scope.generateTempBasedOnNode(node.left.object);nodes.push(t.expressionStatement(t.assignmentExpression("=",temp,left)));nodes.push(buildDefaultsCallExpression(node,temp,file));if(temp)nodes.push(temp);return t.toSequenceExpression(nodes)};exports.ExpressionStatement=function(node,parent,scope,context,file){var expr=node.expression;if(!t.isAssignmentExpression(expr,{operator:"="}))return;if(isProtoAssignmentExpression(expr)){return buildDefaultsCallExpression(expr,expr.left.object,file)}};exports.ObjectExpression=function(node,parent,scope,context,file){var proto;for(var i=0;i<node.properties.length;i++){var prop=node.properties[i];if(isProtoKey(prop)){proto=prop.value;_.pull(node.properties,prop)}}if(proto){var args=[t.objectExpression([]),proto];if(node.properties.length)args.push(node);return t.callExpression(file.addHelper("extends"),args)}}},{"../../../types":101,lodash:164}],91:[function(require,module,exports){"use strict";var t=require("../../../types");exports.optional=true;exports.UnaryExpression=function(node,parent,scope,context,file){context.skip();if(node.operator==="typeof"){var call=t.callExpression(file.addHelper("typeof"),[node.argument]);if(t.isIdentifier(node.argument)){var undefLiteral=t.literal("undefined");return t.conditionalExpression(t.binaryExpression("===",t.unaryExpression("typeof",node.argument),undefLiteral),undefLiteral,call)}else{return call}}}},{"../../../types":101}],92:[function(require,module,exports){"use strict";var t=require("../../../types");exports.optional=true;exports.Identifier=function(node,parent){if(node.name==="undefined"&&t.isReferenced(node,parent)){return t.unaryExpression("void",t.literal(0),true)}}},{"../../../types":101}],93:[function(require,module,exports){"use strict";var t=require("../../../types");exports.ForInStatement=exports.ForOfStatement=function(node,parent,scope,context,file){var left=node.left;if(t.isVariableDeclaration(left)){var declar=left.declarations[0];if(declar.init)throw file.errorWithNode(declar,"No assignments allowed in for-in/of head")}}},{"../../../types":101}],94:[function(require,module,exports){"use strict";exports.MethodDefinition=exports.Property=function(node,parent,scope,context,file){if(node.kind==="set"&&node.value.params.length!==1){throw file.errorWithNode(node.value,"Setters must have only one parameter")}}},{}],95:[function(require,module,exports){"use strict";exports.optional=true;exports.Identifier=function(node,parent,scope,context,file){if(!scope.has(node.name,true)){throw file.errorWithNode(node,"Reference to undeclared variable",ReferenceError)}}},{}],96:[function(require,module,exports){module.exports=["Set","Map","WeakMap","WeakSet","Proxy","Promise","Reflect","Symbol","System","__filename","__dirname","GLOBAL","global","module","require","Buffer","console","exports","process","setTimeout","clearTimeout","setInterval","clearInterval","setImmediate","clearImmediate","Array","Boolean","Date","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","Error","eval","EvalError","Function","hasOwnProperty","isFinite","isNaN","JSON","Map","Math","Number","Object","Proxy","Promise","parseInt","parseFloat","RangeError","ReferenceError","RegExp","Set","String","SyntaxError","TypeError","URIError","WeakMap","WeakSet","arguments","NaN","window","self"]},{}],97:[function(require,module,exports){"use strict";module.exports=traverse;var Scope=require("./scope");var t=require("../types");var _=require("lodash");function TraversalContext(){this.shouldFlatten=false;this.shouldRemove=false;this.shouldSkip=false;this.shouldStop=false}TraversalContext.prototype.flatten=function(){this.shouldFlatten=true};TraversalContext.prototype.remove=function(){this.shouldRemove=true;this.shouldSkip=true};TraversalContext.prototype.skip=function(){this.shouldSkip=true};TraversalContext.prototype.stop=function(){this.shouldStop=true;this.shouldSkip=true};TraversalContext.prototype.reset=function(){this.shouldRemove=false;this.shouldSkip=false;this.shouldStop=false};function replaceNode(obj,key,node,result){var isArray=Array.isArray(result);var inheritTo=result;if(isArray)inheritTo=result[0];if(inheritTo)t.inheritsComments(inheritTo,node);obj[key]=result;if(isArray&&_.contains(t.STATEMENT_OR_BLOCK_KEYS,key)&&!t.isBlockStatement(obj)){t.ensureBlock(obj,key)}if(isArray){return true}}TraversalContext.prototype.enterNode=function(obj,key,node,enter,parent,scope,state){var result=enter(node,parent,scope,this,state);var flatten=false;if(result){flatten=replaceNode(obj,key,node,result);node=result;if(flatten){this.shouldFlatten=true}}if(this.shouldRemove){obj[key]=null;this.shouldFlatten=true}return node};TraversalContext.prototype.exitNode=function(obj,key,node,exit,parent,scope,state){var result=exit(node,parent,scope,this,state);var flatten=false;if(result){flatten=replaceNode(obj,key,node,result);node=result;if(flatten){this.shouldFlatten=true}}return node};TraversalContext.prototype.visitNode=function(obj,key,opts,scope,parent,state){this.reset();var node=obj[key];if(opts.blacklist&&opts.blacklist.indexOf(node.type)>-1){return}var ourScope=scope;if(t.isScope(node)){ourScope=new Scope(node,scope)}node=this.enterNode(obj,key,node,opts.enter,parent,ourScope,state);if(this.shouldSkip){return this.shouldStop}if(Array.isArray(node)){for(var i=0;i<node.length;i++){traverseNode(node[i],opts,ourScope,state)}}else{traverseNode(node,opts,ourScope,state);this.exitNode(obj,key,node,opts.exit,parent,ourScope,state)}return this.shouldStop};TraversalContext.prototype.visit=function(node,key,opts,scope,state){var nodes=node[key];if(!nodes)return;if(!Array.isArray(nodes)){return this.visitNode(node,key,opts,scope,node,state)}if(nodes.length===0){return}for(var i=0;i<nodes.length;i++){if(nodes[i]&&this.visitNode(nodes,i,opts,scope,node,state)){return true}}if(this.shouldFlatten){node[key]=_.flatten(node[key]);if(key==="body"){node[key]=_.compact(node[key])}}};function traverseNode(node,opts,scope,state){var keys=t.VISITOR_KEYS[node.type];if(!keys)return;var context=new TraversalContext;for(var i=0;i<keys.length;i++){if(context.visit(node,keys[i],opts,scope,state)){return}}}function traverse(parent,opts,scope,state){if(!parent)return;if(!scope){if(parent.type!=="Program"&&parent.type!=="File"){throw new Error("Must pass a scope unless traversing a Program/File got a "+parent.type+" node")}}if(!opts)opts={};if(!opts.enter)opts.enter=_.noop;if(!opts.exit)opts.exit=_.noop;if(Array.isArray(parent)){for(var i=0;i<parent.length;i++){traverseNode(parent[i],opts,scope,state)}}else{traverseNode(parent,opts,scope,state)}}function clearNode(node){node._declarations=null;node.extendedRange=null;node._scopeInfo=null;node.tokens=null;node.range=null;node.start=null;node.end=null;node.loc=null;node.raw=null;if(Array.isArray(node.trailingComments)){clearComments(node.trailingComments)}if(Array.isArray(node.leadingComments)){clearComments(node.leadingComments)}}var clearVisitor={enter:clearNode};function clearComments(comments){for(var i=0;i<comments.length;i++){clearNode(comments[i])}}traverse.removeProperties=function(tree){clearNode(tree);traverse(tree,clearVisitor);return tree};function hasBlacklistedType(node,parent,scope,context,state){if(node.type===state.type){state.has=true;context.skip()}}traverse.hasType=function(tree,scope,type,blacklistTypes){if(_.contains(blacklistTypes,tree.type))return false;if(tree.type===type)return true;var state={has:false,type:type};traverse(tree,{blacklist:blacklistTypes,enter:hasBlacklistedType},scope,state);return state.has}},{"../types":101,"./scope":98,lodash:164}],98:[function(require,module,exports){"use strict";module.exports=Scope;var traverse=require("./index");var object=require("../helpers/object");var t=require("../types");var _=require("lodash");var FOR_KEYS=["left","init"];function Scope(block,parent,file){this.parent=parent;this.block=block;this.file=parent?parent.file:file;var info=this.getInfo();this.references=info.references;this.declarations=info.declarations;this.declarationKinds=info.declarationKinds}Scope.defaultDeclarations=require("./global-keys");Scope.prototype._add=function(node,references,throwOnDuplicate){if(!node)return;var ids=t.getIds(node,true);for(var key in ids){var id=ids[key];if(throwOnDuplicate&&references[key]){throw this.file.errorWithNode(id,"Duplicate declaration",TypeError)}references[key]=id}};Scope.prototype.generateTemp=function(file,name){var id=file.generateUidIdentifier(name||"temp",this);this.push({key:id.name,id:id});return id};Scope.prototype.generateUidIdentifier=function(name){return this.file.generateUidIdentifier(name,this)};Scope.prototype.generateUidBasedOnNode=function(parent){var node=parent;if(t.isAssignmentExpression(parent)){node=parent.left}else if(t.isVariableDeclarator(parent)){node=parent.id}else if(t.isProperty(node)){node=node.key}var parts=[];var add=function(node){if(t.isMemberExpression(node)){add(node.object);add(node.property)}else if(t.isIdentifier(node)){parts.push(node.name)}else if(t.isLiteral(node)){parts.push(node.value)}else if(t.isCallExpression(node)){add(node.callee)}};add(node);var id=parts.join("$");id=id.replace(/^_/,"")||"ref";return this.file.generateUidIdentifier(id,this)};Scope.prototype.generateTempBasedOnNode=function(node){if(t.isIdentifier(node)&&this.has(node.name,true)){return null}var id=this.generateUidBasedOnNode(node);this.push({key:id.name,id:id});return id};var functionVariableVisitor={enter:function(node,parent,scope,context,state){if(t.isFor(node)){_.each(FOR_KEYS,function(key){var declar=node[key];if(t.isVar(declar))state.add(declar)})}if(t.isFunction(node))return context.skip();if(state.blockId&&node===state.blockId)return;if(t.isDeclaration(node)&&!t.isBlockScoped(node)){state.add(node)}}};var programReferenceVisitor={enter:function(node,parent,scope,context,add){if(t.isReferencedIdentifier(node,parent)&&!scope.has(node.name)){add(node,true)}}};var blockVariableVisitor={enter:function(node,parent,scope,context,add){if(t.isBlockScoped(node)){add(node,false,true);context.stop()}else if(t.isScope(node)){context.skip()}}};Scope.prototype.getInfo=function(){var parent=this.parent;var block=this.block;var self=this;if(block._scopeInfo)return block._scopeInfo;var info=block._scopeInfo={};var references=info.references=object();var declarations=info.declarations=object();var declarationKinds=info.declarationKinds={};var add=function(node,reference,throwOnDuplicate){self._add(node,references);if(!reference){self._add(node,declarations,throwOnDuplicate);self._add(node,declarationKinds[node.kind]=declarationKinds[node.kind]||object())}};if(parent&&t.isBlockStatement(block)&&t.isFor(parent.block)){return info}if(t.isFor(block)){_.each(FOR_KEYS,function(key){var node=block[key];if(t.isBlockScoped(node))add(node,false,true)});if(t.isBlockStatement(block.body)){block=block.body}}if(t.isBlockStatement(block)||t.isProgram(block)){traverse(block,blockVariableVisitor,this,add)}if(t.isCatchClause(block)){add(block.param)}if(t.isComprehensionExpression(block)){add(block)}if(t.isProgram(block)||t.isFunction(block)){traverse(block,functionVariableVisitor,this,{blockId:block.id,add:add})}if(t.isProgram(block)){traverse(block,programReferenceVisitor,this,add)}if(t.isFunction(block)){_.each(block.params,function(param){add(param)})}return info};Scope.prototype.push=function(opts){var block=this.block;if(t.isFor(block)||t.isCatchClause(block)||t.isFunction(block)){t.ensureBlock(block);block=block.body}if(t.isBlockStatement(block)||t.isProgram(block)){block._declarations=block._declarations||{};block._declarations[opts.key]={kind:opts.kind,id:opts.id,init:opts.init}}else{throw new TypeError("cannot add a declaration here in node type "+block.type)}};Scope.prototype.add=function(node){var scope=this.getFunctionParent();scope._add(node,scope.references)};Scope.prototype.getFunctionParent=function(){var scope=this;while(scope.parent&&!t.isFunction(scope.block)){scope=scope.parent}return scope};Scope.prototype.getAllOfKind=function(kind){var ids=object();var scope=this;do{_.defaults(ids,scope.declarationKinds[kind]);scope=scope.parent}while(scope);return ids};Scope.prototype.get=function(id,decl){return id&&(this.getOwn(id,decl)||this.parentGet(id,decl))};Scope.prototype.getOwn=function(id,decl){var refs=this.references;if(decl)refs=this.declarations;return _.has(refs,id)&&refs[id]};Scope.prototype.parentGet=function(id,decl){return this.parent&&this.parent.get(id,decl)};Scope.prototype.has=function(id,decl){return id&&(this.hasOwn(id,decl)||this.parentHas(id,decl))||_.contains(Scope.defaultDeclarations,id)};Scope.prototype.hasOwn=function(id,decl){return!!this.getOwn(id,decl)};Scope.prototype.parentHas=function(id,decl){return this.parent&&this.parent.has(id,decl)}},{"../helpers/object":25,"../types":101,"./global-keys":96,"./index":97,lodash:164}],99:[function(require,module,exports){module.exports={ExpressionStatement:["Statement"],BreakStatement:["Statement"],ContinueStatement:["Statement"],DebuggerStatement:["Statement"],DoWhileStatement:["Statement","Loop","While"],IfStatement:["Statement"],ReturnStatement:["Statement"],SwitchStatement:["Statement"],ThrowStatement:["Statement"],TryStatement:["Statement"],WhileStatement:["Statement","Loop","While"],WithStatement:["Statement"],EmptyStatement:["Statement"],LabeledStatement:["Statement"],VariableDeclaration:["Statement","Declaration"],ExportDeclaration:["Statement","Declaration"],ImportDeclaration:["Statement","Declaration"],PrivateDeclaration:["Statement","Declaration"],ArrowFunctionExpression:["Scope","Function","Expression"],FunctionDeclaration:["Statement","Declaration","Scope","Function"],FunctionExpression:["Scope","Function","Expression"],BlockStatement:["Statement","Scope"],Program:["Scope"],CatchClause:["Scope"],LogicalExpression:["Binary","Expression"],BinaryExpression:["Binary","Expression"],UnaryExpression:["UnaryLike","Expression"],SpreadProperty:["UnaryLike"],SpreadElement:["UnaryLike"],ClassDeclaration:["Statement","Declaration","Class"],ClassExpression:["Class","Expression"],ForOfStatement:["Statement","For","Scope","Loop"],ForInStatement:["Statement","For","Scope","Loop"],ForStatement:["Statement","For","Scope","Loop"],ObjectPattern:["Pattern"],ArrayPattern:["Pattern"],AssignmentPattern:["Pattern"],Property:["UserWhitespacable"],JSXElement:["UserWhitespacable","Expression"],ArrayExpression:["Expression"],AssignmentExpression:["Expression"],AwaitExpression:["Expression"],BindFunctionExpression:["Expression"],BindMemberExpression:["Expression"],CallExpression:["Expression"],ComprehensionExpression:["Expression","Scope"],ConditionalExpression:["Expression"],Identifier:["Expression"],Literal:["Expression"],MemberExpression:["Expression"],NewExpression:["Expression"],ObjectExpression:["Expression"],SequenceExpression:["Expression"],TaggedTemplateExpression:["Expression"],ThisExpression:["Expression"],UpdateExpression:["Expression"],VirtualPropertyExpression:["Expression"],JSXEmptyExpression:["Expression"],JSXMemberExpression:["Expression"],YieldExpression:["Expression"]}},{}],100:[function(require,module,exports){module.exports={ArrayExpression:["elements"],ArrowFunctionExpression:["params","body"],AssignmentExpression:["operator","left","right"],BinaryExpression:["operator","left","right"],BlockStatement:["body"],CallExpression:["callee","arguments"],ConditionalExpression:["test","consequent","alternate"],ExpressionStatement:["expression"],File:["program","comments","tokens"],FunctionExpression:["id","params","body","generator"],FunctionDeclaration:["id","params","body","generator"],Identifier:["name"],IfStatement:["test","consequent","alternate"],ImportDeclaration:["specifiers","source"],ImportSpecifier:["id","name"],Literal:["value"],LogicalExpression:["operator","left","right"],MemberExpression:["object","property","computed"],MethodDefinition:["key","value","computed","kind"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],Program:["body"],Property:["kind","key","value","computed"],ReturnStatement:["argument"],SequenceExpression:["expressions"],ThrowExpression:["argument"],UnaryExpression:["operator","argument","prefix"],VariableDeclaration:["kind","declarations"],VariableDeclarator:["id","init"],WithStatement:["object","body"],YieldExpression:["argument","delegate"]}},{}],101:[function(require,module,exports){"use strict";var toFastProperties=require("../helpers/to-fast-properties");var esutils=require("esutils");var Node=require("./node");var _=require("lodash");var t=exports;t.NATIVE_TYPE_NAMES=["Array","Object","Number","Boolean","Date","Array","String"];function registerType(type,skipAliasCheck){var is=t["is"+type]=function(node,opts){return t.is(type,node,opts,skipAliasCheck)};t["assert"+type]=function(node,opts){opts=opts||{};if(!is(node,opts)){throw new Error("Expected type "+JSON.stringify(type)+" with option "+JSON.stringify(opts))}}}t.STATEMENT_OR_BLOCK_KEYS=["consequent","body"];t.VISITOR_KEYS=require("./visitor-keys");t.ALIAS_KEYS=require("./alias-keys");t.FLIPPED_ALIAS_KEYS={};_.each(t.VISITOR_KEYS,function(keys,type){registerType(type,true)});_.each(t.ALIAS_KEYS,function(aliases,type){_.each(aliases,function(alias){var types=t.FLIPPED_ALIAS_KEYS[alias]=t.FLIPPED_ALIAS_KEYS[alias]||[];types.push(type)})});_.each(t.FLIPPED_ALIAS_KEYS,function(types,type){t[type.toUpperCase()+"_TYPES"]=types;registerType(type,false)});t.is=function(type,node,opts,skipAliasCheck){if(!node)return;var typeMatches=type===node.type;if(!typeMatches&&!skipAliasCheck){var aliases=t.FLIPPED_ALIAS_KEYS[type];if(typeof aliases!=="undefined"){typeMatches=aliases.indexOf(node.type)>-1}}if(!typeMatches){return false}if(typeof opts!=="undefined"){return t.shallowEqual(node,opts)}return true};t.BUILDER_KEYS=_.defaults(require("./builder-keys"),t.VISITOR_KEYS);_.each(t.BUILDER_KEYS,function(keys,type){t[type[0].toLowerCase()+type.slice(1)]=function(){var args=arguments;var node=new Node;node.start=null;node.type=type;_.each(keys,function(key,i){node[key]=args[i]});return node}});t.toComputedKey=function(node,key){if(!node.computed){if(t.isIdentifier(key))key=t.literal(key.name)}return key};t.isFalsyExpression=function(node){if(t.isLiteral(node)){return!node.value}else if(t.isIdentifier(node)){return node.name==="undefined"}return false};t.toSequenceExpression=function(nodes,scope){var exprs=[];_.each(nodes,function(node){if(t.isExpression(node)){exprs.push(node)}if(t.isExpressionStatement(node)){exprs.push(node.expression)}else if(t.isVariableDeclaration(node)){_.each(node.declarations,function(declar){scope.push({kind:node.kind,key:declar.id.name,id:declar.id});exprs.push(t.assignmentExpression("=",declar.id,declar.init))})}});if(exprs.length===1){return exprs[0]}else{return t.sequenceExpression(exprs)
}};t.shallowEqual=function(actual,expected){var keys=Object.keys(expected);var key;for(var i=0;i<keys.length;i++){key=keys[i];if(actual[key]!==expected[key])return false}return true};t.appendToMemberExpression=function(member,append,computed){member.object=t.memberExpression(member.object,member.property,member.computed);member.property=append;member.computed=!!computed;return member};t.prependToMemberExpression=function(member,append){member.object=t.memberExpression(append,member.object);return member};t.isReferenced=function(node,parent){if(t.isProperty(parent)&&parent.key===node&&!parent.computed)return false;if(t.isFunction(parent)){if(_.contains(parent.params,node))return false;for(var i=0;i<parent.params.length;i++){var param=parent.params[i];if(param===node){return false}else if(t.isRestElement(param)&¶m.argument===node){return false}}}if(t.isMethodDefinition(parent)&&parent.key===node&&!parent.computed){return false}if(t.isCatchClause(parent)&&parent.param===node)return false;if(t.isVariableDeclarator(parent)&&parent.id===node)return false;var isMemberExpression=t.isMemberExpression(parent);var isComputedProperty=isMemberExpression&&parent.property===node&&parent.computed;var isObject=isMemberExpression&&parent.object===node;if(!isMemberExpression||isComputedProperty||isObject)return true;return false};t.isReferencedIdentifier=function(node,parent){return t.isIdentifier(node)&&t.isReferenced(node,parent)};t.isValidIdentifier=function(name){return _.isString(name)&&esutils.keyword.isIdentifierName(name)&&!esutils.keyword.isReservedWordES6(name,true)};t.toIdentifier=function(name){if(t.isIdentifier(name))return name.name;name=name+"";name=name.replace(/[^a-zA-Z0-9$_]/g,"-");name=name.replace(/^[-0-9]+/,"");name=name.replace(/[-_\s]+(.)?/g,function(match,c){return c?c.toUpperCase():""});name=name.replace(/^\_/,"");if(!t.isValidIdentifier(name)){name="_"+name}return name||"_"};t.ensureBlock=function(node,key){key=key||"body";node[key]=t.toBlock(node[key],node)};t.toStatement=function(node,ignore){if(t.isStatement(node)){return node}var mustHaveId=false;var newType;if(t.isClass(node)){mustHaveId=true;newType="ClassDeclaration"}else if(t.isFunction(node)){mustHaveId=true;newType="FunctionDeclaration"}else if(t.isAssignmentExpression(node)){return t.expressionStatement(node)}if(mustHaveId&&!node.id){newType=false}if(!newType){if(ignore){return false}else{throw new Error("cannot turn "+node.type+" to a statement")}}node.type=newType;return node};exports.toExpression=function(node){if(t.isExpressionStatement(node)){node=node.expression}if(t.isClass(node)){node.type="ClassExpression"}else if(t.isFunction(node)){node.type="FunctionExpression"}if(t.isExpression(node)){return node}else{throw new Error("cannot turn "+node.type+" to an expression")}};t.toBlock=function(node,parent){if(t.isBlockStatement(node)){return node}if(t.isEmptyStatement(node)){node=[]}if(!Array.isArray(node)){if(!t.isStatement(node)){if(t.isFunction(parent)){node=t.returnStatement(node)}else{node=t.expressionStatement(node)}}node=[node]}return t.blockStatement(node)};t.getIds=function(node,map,ignoreTypes){ignoreTypes=ignoreTypes||[];var search=[].concat(node);var ids={};while(search.length){var id=search.shift();if(!id)continue;if(_.contains(ignoreTypes,id.type))continue;var nodeKeys=t.getIds.nodes[id.type];var arrKeys=t.getIds.arrays[id.type];var i,key;if(t.isIdentifier(id)){ids[id.name]=id}else if(nodeKeys){for(i=0;i<nodeKeys.length;i++){key=nodeKeys[i];if(id[key]){search.push(id[key]);break}}}else if(arrKeys){for(i=0;i<arrKeys.length;i++){key=arrKeys[i];search=search.concat(id[key]||[])}}}if(!map)ids=_.keys(ids);return ids};t.getIds.nodes={AssignmentExpression:["left"],ImportBatchSpecifier:["name"],ImportSpecifier:["name","id"],ExportSpecifier:["name","id"],VariableDeclarator:["id"],FunctionDeclaration:["id"],ClassDeclaration:["id"],MemeberExpression:["object"],SpreadElement:["argument"],RestElement:["argument"],Property:["value"],ComprehensionBlock:["left"],AssignmentPattern:["left"]};t.getIds.arrays={PrivateDeclaration:["declarations"],ComprehensionExpression:["blocks"],ExportDeclaration:["specifiers","declaration"],ImportDeclaration:["specifiers"],VariableDeclaration:["declarations"],ArrayPattern:["elements"],ObjectPattern:["properties"]};t.isLet=function(node){return t.isVariableDeclaration(node)&&(node.kind!=="var"||node._let)};t.isBlockScoped=function(node){return t.isFunctionDeclaration(node)||t.isLet(node)};t.isVar=function(node){return t.isVariableDeclaration(node,{kind:"var"})&&!node._let};t.COMMENT_KEYS=["leadingComments","trailingComments"];t.removeComments=function(child){_.each(t.COMMENT_KEYS,function(key){delete child[key]});return child};t.inheritsComments=function(child,parent){_.each(t.COMMENT_KEYS,function(key){child[key]=_.uniq(_.compact([].concat(child[key],parent[key])))});return child};t.inherits=function(child,parent){child.range=parent.range;child.start=parent.start;child.loc=parent.loc;child.end=parent.end;t.inheritsComments(child,parent);return child};t.getLastStatements=function(node){var nodes=[];var add=function(node){nodes=nodes.concat(t.getLastStatements(node))};if(t.isIfStatement(node)){add(node.consequent);add(node.alternate)}else if(t.isFor(node)||t.isWhile(node)){add(node.body)}else if(t.isProgram(node)||t.isBlockStatement(node)){add(node.body[node.body.length-1])}else if(node){nodes.push(node)}return nodes};t.getSpecifierName=function(specifier){return specifier.name||specifier.id};t.getSpecifierId=function(specifier){if(specifier.default){return t.identifier("default")}else{return specifier.id}};t.isSpecifierDefault=function(specifier){return specifier.default||t.isIdentifier(specifier.id)&&specifier.id.name==="default"};toFastProperties(t);toFastProperties(t.VISITOR_KEYS)},{"../helpers/to-fast-properties":26,"./alias-keys":99,"./builder-keys":100,"./node":102,"./visitor-keys":103,esutils:162,lodash:164}],102:[function(require,module,exports){"use strict";module.exports=Node;var acorn=require("acorn-6to5");var oldNode=acorn.Node;acorn.Node=Node;function Node(){oldNode.apply(this)}},{"acorn-6to5":105}],103:[function(require,module,exports){module.exports={ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],AssignmentExpression:["left","right"],AssignmentPattern:["left","right"],AwaitExpression:["argument"],BinaryExpression:["left","right"],BindFunctionExpression:["callee","arguments"],BindMemberExpression:["object","property","arguments"],BlockStatement:["body"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ComprehensionBlock:["left","right","body"],ComprehensionExpression:["filter","blocks","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],File:["program"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],ForStatement:["init","test","update","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportBatchSpecifier:["id"],ImportDeclaration:["specifiers","source"],ImportSpecifier:["id","name"],LabeledStatement:["label","body"],Literal:[],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],PrivateDeclaration:["declarations"],Program:["body"],Property:["key","value"],RestElement:["argument"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SpreadProperty:["argument"],SwitchCase:["test","consequent"],SwitchStatement:["discriminant","cases"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],VirtualPropertyExpression:["object","property"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"],AnyTypeAnnotation:[],ArrayTypeAnnotation:[],BooleanTypeAnnotation:[],ClassProperty:["key"],DeclareClass:[],DeclareFunction:[],DeclareModule:[],DeclareVariable:[],FunctionTypeAnnotation:[],FunctionTypeParam:[],GenericTypeAnnotation:[],InterfaceExtends:[],InterfaceDeclaration:[],IntersectionTypeAnnotation:[],NullableTypeAnnotation:[],NumberTypeAnnotation:[],StringLiteralTypeAnnotation:[],StringTypeAnnotation:[],TupleTypeAnnotation:[],TypeofTypeAnnotation:[],TypeAlias:[],TypeAnnotation:[],TypeParameterDeclaration:[],TypeParameterInstantiation:[],ObjectTypeAnnotation:[],ObjectTypeCallProperty:[],ObjectTypeIndexer:[],ObjectTypeProperty:[],QualifiedTypeIdentifier:[],UnionTypeAnnotation:[],VoidTypeAnnotation:[],JSXAttribute:["name","value"],JSXClosingElement:["name"],JSXElement:["openingElement","closingElement","children"],JSXEmptyExpression:[],JSXExpressionContainer:["expression"],JSXIdentifier:[],JSXMemberExpression:["object","property"],JSXNamespacedName:["namespace","name"],JSXOpeningElement:["name","attributes"],JSXSpreadAttribute:["argument"]}},{}],104:[function(require,module,exports){(function(Buffer,__dirname){"use strict";require("./patch");var estraverse=require("estraverse");var codeFrame=require("./helpers/code-frame");var traverse=require("./traverse");var acorn=require("acorn-6to5");var path=require("path");var util=require("util");var fs=require("fs");var t=require("./types");var _=require("lodash");exports.inherits=util.inherits;exports.canCompile=function(filename,altExts){var exts=altExts||exports.canCompile.EXTENSIONS;var ext=path.extname(filename);return _.contains(exts,ext)};exports.canCompile.EXTENSIONS=[".js",".jsx",".es6",".es"];exports.isInteger=function(i){return _.isNumber(i)&&i%1===0};exports.resolve=function(loc){try{return require.resolve(loc)}catch(err){return null}};exports.trimRight=function(str){return str.replace(/[\n\s]+$/g,"")};exports.list=function(val){return val?val.split(","):[]};exports.regexify=function(val){if(!val)return new RegExp(/.^/);if(Array.isArray(val))val=val.join("|");if(_.isString(val))return new RegExp(val);if(_.isRegExp(val))return val;throw new TypeError("illegal type for regexify")};exports.arrayify=function(val){if(!val)return[];if(_.isString(val))return exports.list(val);if(Array.isArray(val))return val;throw new TypeError("illegal type for arrayify")};exports.isAbsolute=function(loc){if(!loc)return false;if(loc[0]==="/")return true;if(loc[1]===":"&&loc[2]==="\\")return true;return false};exports.sourceMapToComment=function(map){var json=JSON.stringify(map);var base64=new Buffer(json).toString("base64");return"//# sourceMappingURL=data:application/json;base64,"+base64};exports.pushMutatorMap=function(mutatorMap,key,kind,computed,method){var alias;if(t.isIdentifier(key)){alias=key.name;if(computed)alias="computed:"+alias}else if(t.isLiteral(key)){alias=String(key.value)}else{alias=JSON.stringify(traverse.removeProperties(_.cloneDeep(key)))}var map;if(_.has(mutatorMap,alias)){map=mutatorMap[alias]}else{map={}}mutatorMap[alias]=map;map._key=key;if(computed){map._computed=true}map[kind]=method};exports.buildDefineProperties=function(mutatorMap){var objExpr=t.objectExpression([]);_.each(mutatorMap,function(map){var mapNode=t.objectExpression([]);var propNode=t.property("init",map._key,mapNode,map._computed);if(!map.get&&!map.set){map.writable=t.literal(true)}map.enumerable=t.literal(true);map.configurable=t.literal(true);_.each(map,function(node,key){if(key[0]==="_")return;node=_.clone(node);var inheritNode=node;if(t.isMethodDefinition(node))node=node.value;var prop=t.property("init",t.identifier(key),node);t.inheritsComments(prop,inheritNode);t.removeComments(inheritNode);mapNode.properties.push(prop)});objExpr.properties.push(propNode)});return objExpr};var templateVisitor={enter:function(node,parent,scope,context,nodes){if(t.isIdentifier(node)&&_.has(nodes,node.name)){return nodes[node.name]}}};exports.template=function(name,nodes,keepExpression){var template=exports.templates[name];if(!template)throw new ReferenceError("unknown template "+name);if(nodes===true){keepExpression=true;nodes=null}template=_.cloneDeep(template);if(!_.isEmpty(nodes)){traverse(template,templateVisitor,null,nodes)}var node=template.body[0];if(!keepExpression&&t.isExpressionStatement(node)){return node.expression}else{return node}};exports.repeat=function(width,cha){cha=cha||" ";var result="";for(var i=0;i<width;i++){result+=cha}return result};exports.normaliseAst=function(ast,comments,tokens){if(ast&&ast.type==="Program"){return t.file(ast,comments||[],tokens||[])}else{throw new Error("Not a valid ast?")}};exports.parse=function(opts,code,callback){try{var comments=[];var tokens=[];var ast=acorn.parse(code,{allowImportExportEverywhere:opts.allowImportExportEverywhere,allowReturnOutsideFunction:true,ecmaVersion:opts.experimental?7:6,playground:opts.playground,strictMode:true,onComment:comments,locations:true,onToken:tokens,ranges:true});estraverse.attachComments(ast,comments,tokens);ast=exports.normaliseAst(ast,comments,tokens);if(callback){return callback(ast)}else{return ast}}catch(err){if(!err._6to5){err._6to5=true;var message=opts.filename+": "+err.message;var loc=err.loc;if(loc){var frame=codeFrame(code,loc.line,loc.column+1);message+=frame}if(err.stack)err.stack=err.stack.replace(err.message,message);err.message=message}throw err}};exports.parseTemplate=function(loc,code){var ast=exports.parse({filename:loc},code).program;return traverse.removeProperties(ast)};var loadTemplates=function(){var templates={};var templatesLoc=__dirname+"/transformation/templates";if(!fs.existsSync(templatesLoc)){throw new Error("no templates directory - this is most likely the "+"result of a broken `npm publish`. Please report to "+"https://github.com/6to5/6to5/issues")}_.each(fs.readdirSync(templatesLoc),function(name){if(name[0]===".")return;var key=path.basename(name,path.extname(name));var loc=templatesLoc+"/"+name;var code=fs.readFileSync(loc,"utf8");templates[key]=exports.parseTemplate(loc,code)});return templates};try{exports.templates=require("../../templates.json")}catch(err){if(err.code!=="MODULE_NOT_FOUND")throw err;exports.templates=loadTemplates()}}).call(this,require("buffer").Buffer,"/lib/6to5")},{"../../templates.json":194,"./helpers/code-frame":24,"./patch":27,"./traverse":97,"./types":101,"acorn-6to5":105,buffer:122,estraverse:158,fs:120,lodash:164,path:129,util:145}],105:[function(require,module,exports){(function(root,mod){if(typeof exports=="object"&&typeof module=="object")return mod(exports);if(typeof define=="function"&&define.amd)return define(["exports"],mod);mod(root.acorn||(root.acorn={}))})(this,function(exports){"use strict";exports.version="0.11.1";var options,input,inputLen,sourceFile;exports.parse=function(inpt,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState();var startPos=options.locations?[tokPos,curPosition()]:tokPos;initParserState();return parseTopLevel(options.program||startNodeAt(startPos))};var defaultOptions=exports.defaultOptions={playground:false,ecmaVersion:5,strictSemicolons:false,allowTrailingCommas:true,forbidReserved:false,allowReturnOutsideFunction:false,allowImportExportEverywhere:false,allowHashBang:false,locations:false,onToken:null,onComment:null,ranges:false,program:null,sourceFile:null,directSourceFile:null,preserveParens:false};exports.parseExpressionAt=function(inpt,pos,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState(pos);initParserState();return parseExpression()};var isArray=function(obj){return Object.prototype.toString.call(obj)==="[object Array]"};function setOptions(opts){options={};for(var opt in defaultOptions)options[opt]=opts&&has(opts,opt)?opts[opt]:defaultOptions[opt];sourceFile=options.sourceFile||null;if(isArray(options.onToken)){var tokens=options.onToken;options.onToken=function(token){tokens.push(token)}}if(isArray(options.onComment)){var comments=options.onComment;options.onComment=function(block,text,start,end,startLoc,endLoc){var comment={type:block?"Block":"Line",value:text,start:start,end:end};if(options.locations){comment.loc=new SourceLocation;comment.loc.start=startLoc;comment.loc.end=endLoc}if(options.ranges)comment.range=[start,end];comments.push(comment)}}if(options.strictMode){strict=true}if(options.ecmaVersion>=6){isKeyword=isEcma6Keyword}else{isKeyword=isEcma5AndLessKeyword}}var getLineInfo=exports.getLineInfo=function(input,offset){for(var line=1,cur=0;;){lineBreak.lastIndex=cur;var match=lineBreak.exec(input);if(match&&match.index<offset){++line;cur=match.index+match[0].length}else break}return{line:line,column:offset-cur}};function Token(){this.type=tokType;this.value=tokVal;this.start=tokStart;this.end=tokEnd;if(options.locations){this.loc=new SourceLocation;this.loc.end=tokEndLoc}if(options.ranges)this.range=[tokStart,tokEnd]}exports.Token=Token;exports.tokenize=function(inpt,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState();skipSpace();function getToken(){lastEnd=tokEnd;readToken();return new Token}getToken.jumpTo=function(pos,exprAllowed){tokPos=pos;if(options.locations){tokCurLine=1;tokLineStart=lineBreak.lastIndex=0;var match;while((match=lineBreak.exec(input))&&match.index<pos){++tokCurLine;tokLineStart=match.index+match[0].length}}tokExprAllowed=!!exprAllowed;skipSpace()};getToken.current=function(){return new Token};if(typeof Symbol!=="undefined"){getToken[Symbol.iterator]=function(){return{next:function(){var token=getToken();return{done:token.type===_eof,value:token}}}}}getToken.options=options;return getToken};var tokPos;var tokStart,tokEnd;var tokStartLoc,tokEndLoc;var tokType,tokVal;var tokContext,tokExprAllowed;var tokCurLine,tokLineStart;var lastStart,lastEnd,lastEndLoc;var inFunction,inGenerator,inAsync,labels,strict,inXJSChild,inXJSTag,inType;function initParserState(){lastStart=lastEnd=tokPos;if(options.locations)lastEndLoc=curPosition();inFunction=inGenerator=inAsync=false;labels=[];skipSpace();readToken()}function raise(pos,message){var loc=getLineInfo(input,pos);message+=" ("+loc.line+":"+loc.column+")";var err=new SyntaxError(message);err.pos=pos;err.loc=loc;err.raisedAt=tokPos;throw err}var empty=[];var _num={type:"num"},_regexp={type:"regexp"},_string={type:"string"};var _name={type:"name"},_eof={type:"eof"};var _jsxName={type:"jsxName"};var _xjsName={type:"xjsName"},_xjsText={type:"xjsText"};var _break={keyword:"break"},_case={keyword:"case",beforeExpr:true},_catch={keyword:"catch"};var _continue={keyword:"continue"},_debugger={keyword:"debugger"},_default={keyword:"default"};var _do={keyword:"do",isLoop:true},_else={keyword:"else",beforeExpr:true};var _finally={keyword:"finally"},_for={keyword:"for",isLoop:true},_function={keyword:"function"};var _if={keyword:"if"},_return={keyword:"return",beforeExpr:true},_switch={keyword:"switch"};var _throw={keyword:"throw",beforeExpr:true},_try={keyword:"try"},_var={keyword:"var"};var _let={keyword:"let"},_const={keyword:"const"};var _while={keyword:"while",isLoop:true},_with={keyword:"with"},_new={keyword:"new",beforeExpr:true};var _this={keyword:"this"};var _class={keyword:"class"},_extends={keyword:"extends",beforeExpr:true};var _export={keyword:"export"},_import={keyword:"import"};var _yield={keyword:"yield",beforeExpr:true};var _null={keyword:"null",atomValue:null},_true={keyword:"true",atomValue:true};var _false={keyword:"false",atomValue:false};var _in={keyword:"in",binop:7,beforeExpr:true};var keywordTypes={"break":_break,"case":_case,"catch":_catch,"continue":_continue,"debugger":_debugger,"default":_default,"do":_do,"else":_else,"finally":_finally,"for":_for,"function":_function,"if":_if,"return":_return,"switch":_switch,"throw":_throw,"try":_try,"var":_var,let:_let,"const":_const,"while":_while,"with":_with,"null":_null,"true":_true,"false":_false,"new":_new,"in":_in,"instanceof":{keyword:"instanceof",binop:7,beforeExpr:true},"this":_this,"typeof":{keyword:"typeof",prefix:true,beforeExpr:true},"void":{keyword:"void",prefix:true,beforeExpr:true},"delete":{keyword:"delete",prefix:true,beforeExpr:true},"class":_class,"extends":_extends,"export":_export,"import":_import,"yield":_yield};var _bracketL={type:"[",beforeExpr:true},_bracketR={type:"]"},_braceL={type:"{",beforeExpr:true};var _braceR={type:"}"},_parenL={type:"(",beforeExpr:true},_parenR={type:")"};var _comma={type:",",beforeExpr:true},_semi={type:";",beforeExpr:true};var _colon={type:":",beforeExpr:true},_dot={type:"."},_question={type:"?",beforeExpr:true};var _arrow={type:"=>",beforeExpr:true},_template={type:"template"};var _ellipsis={type:"...",beforeExpr:true};var _backQuote={type:"`"},_dollarBraceL={type:"${",beforeExpr:true};var _jsxText={type:"jsxText"};var _paamayimNekudotayim={type:"::",beforeExpr:true};var _at={type:"@"};var _hash={type:"#"};var _slash={binop:10,beforeExpr:true},_eq={isAssign:true,beforeExpr:true};var _assign={isAssign:true,beforeExpr:true};var _incDec={postfix:true,prefix:true,isUpdate:true},_prefix={prefix:true,beforeExpr:true};var _logicalOR={binop:1,beforeExpr:true};var _logicalAND={binop:2,beforeExpr:true};var _bitwiseOR={binop:3,beforeExpr:true};var _bitwiseXOR={binop:4,beforeExpr:true};var _bitwiseAND={binop:5,beforeExpr:true};var _equality={binop:6,beforeExpr:true};var _relational={binop:7,beforeExpr:true};var _bitShift={binop:8,beforeExpr:true};var _plusMin={binop:9,prefix:true,beforeExpr:true};var _modulo={binop:10,beforeExpr:true};var _star={binop:10,beforeExpr:true};var _exponent={binop:11,beforeExpr:true,rightAssociative:true};var _jsxTagStart={type:"jsxTagStart"},_jsxTagEnd={type:"jsxTagEnd"};exports.tokTypes={bracketL:_bracketL,bracketR:_bracketR,braceL:_braceL,braceR:_braceR,parenL:_parenL,parenR:_parenR,comma:_comma,semi:_semi,colon:_colon,dot:_dot,ellipsis:_ellipsis,question:_question,slash:_slash,eq:_eq,name:_name,eof:_eof,num:_num,regexp:_regexp,string:_string,paamayimNekudotayim:_paamayimNekudotayim,exponent:_exponent,at:_at,hash:_hash,arrow:_arrow,template:_template,star:_star,assign:_assign,backQuote:_backQuote,dollarBraceL:_dollarBraceL};for(var kw in keywordTypes)exports.tokTypes["_"+kw]=keywordTypes[kw];var isReservedWord3=function anonymous(str){switch(str.length){case 6:switch(str){case"double":case"export":case"import":case"native":case"public":case"static":case"throws":return true}return false;case 4:switch(str){case"byte":case"char":case"enum":case"goto":case"long":return true}return false;case 5:switch(str){case"class":case"final":case"float":case"short":case"super":return true}return false;case 7:switch(str){case"boolean":case"extends":case"package":case"private":return true}return false;case 9:switch(str){case"interface":case"protected":case"transient":return true}return false;case 8:switch(str){case"abstract":case"volatile":return true}return false;case 10:return str==="implements";case 3:return str==="int";case 12:return str==="synchronized"}};var isReservedWord5=function anonymous(str){switch(str.length){case 5:switch(str){case"class":case"super":case"const":return true}return false;case 6:switch(str){case"export":case"import":return true}return false;case 4:return str==="enum";case 7:return str==="extends"}};var isStrictReservedWord=function anonymous(str){switch(str.length){case 9:switch(str){case"interface":case"protected":return true}return false;case 7:switch(str){case"package":case"private":return true}return false;case 6:switch(str){case"public":case"static":return true}return false;case 10:return str==="implements";case 3:return str==="let";case 5:return str==="yield"}};var isStrictBadIdWord=function anonymous(str){switch(str){case"eval":case"arguments":return true}return false};var ecma5AndLessKeywords="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";var isEcma5AndLessKeyword=function anonymous(str){switch(str.length){case 4:switch(str){case"case":case"else":case"with":case"null":case"true":case"void":case"this":return true}return false;case 5:switch(str){case"break":case"catch":case"throw":case"while":case"false":return true}return false;case 3:switch(str){case"for":case"try":case"var":case"new":return true}return false;case 6:switch(str){case"return":case"switch":case"typeof":case"delete":return true}return false;case 8:switch(str){case"continue":case"debugger":case"function":return true}return false;case 2:switch(str){case"do":case"if":case"in":return true}return false;case 7:switch(str){case"default":case"finally":return true}return false;case 10:return str==="instanceof"}};var ecma6AndLessKeywords=ecma5AndLessKeywords+" let const class extends export import yield";var isEcma6Keyword=function anonymous(str){switch(str.length){case 5:switch(str){case"break":case"catch":case"throw":case"while":case"false":case"const":case"class":case"yield":return true}return false;case 4:switch(str){case"case":case"else":case"with":case"null":case"true":case"void":case"this":return true}return false;case 6:switch(str){case"return":case"switch":case"typeof":case"delete":case"export":case"import":return true}return false;case 3:switch(str){case"for":case"try":case"var":case"new":case"let":return true}return false;case 8:switch(str){case"continue":case"debugger":case"function":return true}return false;case 7:switch(str){case"default":case"finally":case"extends":return true}return false;case 2:switch(str){case"do":case"if":case"in":return true}return false;case 10:return str==="instanceof"}};var isKeyword=isEcma5AndLessKeyword;var nonASCIIwhitespace=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var nonASCIIidentifierStartChars="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢲऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var nonASCIIidentifierChars="̀-ͯ҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣤ-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏ᦰ-ᧀᧈᧉ᧐-᧙ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷼-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-꣄꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︭︳︴﹍-﹏0-9_";var nonASCIIidentifierStart=new RegExp("["+nonASCIIidentifierStartChars+"]");var nonASCIIidentifier=new RegExp("["+nonASCIIidentifierStartChars+nonASCIIidentifierChars+"]");var decimalNumber=/^\d+$/;var hexNumber=/^[\da-fA-F]+$/;var newline=/[\n\r\u2028\u2029]/;function isNewLine(code){return code===10||code===13||code===8232||code==8233}var lineBreak=/\r\n|[\n\r\u2028\u2029]/g;var isIdentifierStart=exports.isIdentifierStart=function(code){if(code<65)return code===36;if(code<91)return true;if(code<97)return code===95;if(code<123)return true;return code>=170&&nonASCIIidentifierStart.test(String.fromCharCode(code))};var isIdentifierChar=exports.isIdentifierChar=function(code){if(code<48)return code===36;if(code<58)return true;if(code<65)return false;if(code<91)return true;if(code<97)return code===95;if(code<123)return true;return code>=170&&nonASCIIidentifier.test(String.fromCharCode(code))};function Position(line,col){this.line=line;this.column=col}Position.prototype.offset=function(n){return new Position(this.line,this.column+n)};function curPosition(){return new Position(tokCurLine,tokPos-tokLineStart)}function initTokenState(pos){if(pos){tokPos=pos;tokLineStart=Math.max(0,input.lastIndexOf("\n",pos));tokCurLine=input.slice(0,tokLineStart).split(newline).length}else{tokCurLine=1;tokPos=tokLineStart=0}tokType=_eof;tokContext=[b_stat];tokExprAllowed=true;inType=strict=false;if(tokPos===0&&options.allowHashBang&&input.slice(0,2)==="#!"){skipLineComment(2)}}var b_stat={token:"{",isExpr:false},b_expr={token:"{",isExpr:true},b_tmpl={token:"${",isExpr:true};var p_stat={token:"(",isExpr:false},p_expr={token:"(",isExpr:true};var q_tmpl={token:"`",isExpr:true},f_expr={token:"function",isExpr:true};var j_oTag={token:"<tag",isExpr:false},j_cTag={token:"</tag",isExpr:false},j_expr={token:"<tag>...</tag>",isExpr:true};function curTokContext(){return tokContext[tokContext.length-1]}function braceIsBlock(prevType){var parent;if(prevType===_colon&&(parent=curTokContext()).token=="{")return!parent.isExpr;if(prevType===_return)return newline.test(input.slice(lastEnd,tokStart));if(prevType===_else||prevType===_semi||prevType===_eof)return true;if(prevType==_braceL)return curTokContext()===b_stat;return!tokExprAllowed}function finishToken(type,val){tokEnd=tokPos;if(options.locations)tokEndLoc=curPosition();var prevType=tokType,preserveSpace=false;tokType=type;tokVal=val;if(type===_parenR||type===_braceR){var out=tokContext.pop();if(out===b_tmpl){preserveSpace=tokExprAllowed=true}else if(out===b_stat&&curTokContext()===f_expr){tokContext.pop();tokExprAllowed=false}else{tokExprAllowed=!(out&&out.isExpr)}}else if(type===_braceL){switch(curTokContext()){case j_oTag:tokContext.push(b_expr);break;case j_expr:tokContext.push(b_tmpl);break;default:tokContext.push(braceIsBlock(prevType)?b_stat:b_expr)}tokExprAllowed=true}else if(type===_dollarBraceL){tokContext.push(b_tmpl);tokExprAllowed=true}else if(type==_parenL){var statementParens=prevType===_if||prevType===_for||prevType===_with||prevType===_while;tokContext.push(statementParens?p_stat:p_expr);tokExprAllowed=true}else if(type==_incDec){}else if(type.keyword&&prevType==_dot){tokExprAllowed=false}else if(type==_function){if(curTokContext()!==b_stat){tokContext.push(f_expr)}tokExprAllowed=false}else if(type===_backQuote){if(curTokContext()===q_tmpl){tokContext.pop()}else{tokContext.push(q_tmpl);preserveSpace=true}tokExprAllowed=false}else if(type===_jsxTagStart){tokContext.push(j_expr);tokContext.push(j_oTag);tokExprAllowed=false}else if(type===_jsxTagEnd){var out=tokContext.pop();if(out===j_oTag&&prevType===_slash||out===j_cTag){tokContext.pop();preserveSpace=tokExprAllowed=curTokContext()===j_expr}else{preserveSpace=tokExprAllowed=true}}else if(type===_jsxText){preserveSpace=tokExprAllowed=true}else if(type===_slash&&prevType===_jsxTagStart){tokContext.length-=2;tokContext.push(j_cTag);tokExprAllowed=false}else{tokExprAllowed=type.beforeExpr}if(!preserveSpace)skipSpace()}function skipBlockComment(){var startLoc=options.onComment&&options.locations&&curPosition();var start=tokPos,end=input.indexOf("*/",tokPos+=2);if(end===-1)raise(tokPos-2,"Unterminated comment");tokPos=end+2;if(options.locations){lineBreak.lastIndex=start;
var match;while((match=lineBreak.exec(input))&&match.index<tokPos){++tokCurLine;tokLineStart=match.index+match[0].length}}if(options.onComment)options.onComment(true,input.slice(start+2,end),start,tokPos,startLoc,options.locations&&curPosition())}function skipLineComment(startSkip){var start=tokPos;var startLoc=options.onComment&&options.locations&&curPosition();var ch=input.charCodeAt(tokPos+=startSkip);while(tokPos<inputLen&&ch!==10&&ch!==13&&ch!==8232&&ch!==8233){++tokPos;ch=input.charCodeAt(tokPos)}if(options.onComment)options.onComment(false,input.slice(start+startSkip,tokPos),start,tokPos,startLoc,options.locations&&curPosition())}function skipSpace(){while(tokPos<inputLen){var ch=input.charCodeAt(tokPos);if(ch===32){++tokPos}else if(ch===13){++tokPos;var next=input.charCodeAt(tokPos);if(next===10){++tokPos}if(options.locations){++tokCurLine;tokLineStart=tokPos}}else if(ch===10||ch===8232||ch===8233){++tokPos;if(options.locations){++tokCurLine;tokLineStart=tokPos}}else if(ch>8&&ch<14){++tokPos}else if(ch===47){var next=input.charCodeAt(tokPos+1);if(next===42){skipBlockComment()}else if(next===47){skipLineComment(2)}else break}else if(ch===160){++tokPos}else if(ch>=5760&&nonASCIIwhitespace.test(String.fromCharCode(ch))){++tokPos}else{break}}}function readToken_dot(){var next=input.charCodeAt(tokPos+1);if(next>=48&&next<=57)return readNumber(true);var next2=input.charCodeAt(tokPos+2);if(options.playground&&next===63){tokPos+=2;return finishToken(_dotQuestion)}else if(options.ecmaVersion>=6&&next===46&&next2===46){tokPos+=3;return finishToken(_ellipsis)}else{++tokPos;return finishToken(_dot)}}function readToken_slash(){var next=input.charCodeAt(tokPos+1);if(tokExprAllowed){++tokPos;return readRegexp()}if(next===61)return finishOp(_assign,2);return finishOp(_slash,1)}function readToken_modulo(){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_assign,2);return finishOp(_modulo,1)}function readToken_mult(){var type=_star;var width=1;var next=input.charCodeAt(tokPos+1);if(options.ecmaVersion>=7&&next===42){width++;next=input.charCodeAt(tokPos+2);type=_exponent}if(next===61){width++;type=_assign}return finishOp(type,width)}function readToken_pipe_amp(code){var next=input.charCodeAt(tokPos+1);if(next===code){if(options.playground&&input.charCodeAt(tokPos+2)===61)return finishOp(_assign,3);return finishOp(code===124?_logicalOR:_logicalAND,2)}if(next===61)return finishOp(_assign,2);return finishOp(code===124?_bitwiseOR:_bitwiseAND,1)}function readToken_caret(){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_assign,2);return finishOp(_bitwiseXOR,1)}function readToken_plus_min(code){var next=input.charCodeAt(tokPos+1);if(next===code){if(next==45&&input.charCodeAt(tokPos+2)==62&&newline.test(input.slice(lastEnd,tokPos))){skipLineComment(3);skipSpace();return readToken()}return finishOp(_incDec,2)}if(next===61)return finishOp(_assign,2);return finishOp(_plusMin,1)}function readToken_lt_gt(code){var next=input.charCodeAt(tokPos+1);var size=1;if(!inType&&next===code){size=code===62&&input.charCodeAt(tokPos+2)===62?3:2;if(input.charCodeAt(tokPos+size)===61)return finishOp(_assign,size+1);return finishOp(_bitShift,size)}if(next==33&&code==60&&input.charCodeAt(tokPos+2)==45&&input.charCodeAt(tokPos+3)==45){skipLineComment(4);skipSpace();return readToken()}if(!inType){if(tokExprAllowed&&code===60){++tokPos;return finishToken(_jsxTagStart)}if(code===62){var context=curTokContext();if(context===j_oTag||context===j_cTag){++tokPos;return finishToken(_jsxTagEnd)}}}if(next===61)size=input.charCodeAt(tokPos+2)===61?3:2;return finishOp(_relational,size)}function readToken_eq_excl(code){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_equality,input.charCodeAt(tokPos+2)===61?3:2);if(code===61&&next===62&&options.ecmaVersion>=6){tokPos+=2;return finishToken(_arrow)}return finishOp(code===61?_eq:_prefix,1)}function getTemplateToken(code){if(tokType===_string){if(code===96){++tokPos;return finishToken(_bquote)}else if(code===36&&input.charCodeAt(tokPos+1)===123){tokPos+=2;return finishToken(_dollarBraceL)}}return readTmplString()}function getTokenFromCode(code){switch(code){case 46:return readToken_dot();case 40:++tokPos;return finishToken(_parenL);case 41:++tokPos;return finishToken(_parenR);case 59:++tokPos;return finishToken(_semi);case 44:++tokPos;return finishToken(_comma);case 91:++tokPos;return finishToken(_bracketL);case 93:++tokPos;return finishToken(_bracketR);case 123:++tokPos;return finishToken(_braceL);case 125:++tokPos;return finishToken(_braceR);case 63:++tokPos;return finishToken(_question);case 64:if(options.playground){++tokPos;return finishToken(_at)}case 35:if(options.playground){++tokPos;return finishToken(_hash)}case 58:++tokPos;if(options.ecmaVersion>=7){var next=input.charCodeAt(tokPos);if(next===58){++tokPos;return finishToken(_paamayimNekudotayim)}}return finishToken(_colon);case 96:if(options.ecmaVersion>=6){++tokPos;return finishToken(_backQuote)}else{return false}case 48:var next=input.charCodeAt(tokPos+1);if(next===120||next===88)return readRadixNumber(16);if(options.ecmaVersion>=6){if(next===111||next===79)return readRadixNumber(8);if(next===98||next===66)return readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return readNumber(false);case 34:case 39:return inXJSTag?readXJSStringLiteral():readString(code);case 47:return readToken_slash();case 37:return readToken_modulo();case 42:return readToken_mult();case 124:case 38:return readToken_pipe_amp(code);case 94:return readToken_caret();case 43:case 45:return readToken_plus_min(code);case 60:case 62:return readToken_lt_gt(code);case 61:case 33:return readToken_eq_excl(code);case 126:return finishOp(_prefix,1)}return false}function readToken(){tokStart=tokPos;if(options.locations)tokStartLoc=curPosition();if(tokPos>=inputLen)return finishToken(_eof);var context=curTokContext();if(context===q_tmpl){return readTmplToken()}if(context===j_expr){return readJSXToken()}var code=input.charCodeAt(tokPos);if(context===j_oTag||context===j_cTag){if(isIdentifierStart(code))return readJSXWord()}else if(context===j_expr){return readJSXToken()}else{if(isIdentifierStart(code)||code===92)return readWord()}var tok=getTokenFromCode(code);if(tok===false){var ch=String.fromCharCode(code);if(ch==="\\"||nonASCIIidentifierStart.test(ch))return readWord();raise(tokPos,"Unexpected character '"+ch+"'")}return tok}function finishOp(type,size,shouldSkipSpace){var str=input.slice(tokPos,tokPos+size);tokPos+=size;finishToken(type,str,shouldSkipSpace)}var regexpUnicodeSupport=false;try{new RegExp("","u");regexpUnicodeSupport=true}catch(e){}function readRegexp(){var content="",escaped,inClass,start=tokPos;for(;;){if(tokPos>=inputLen)raise(start,"Unterminated regular expression");var ch=nextChar();if(newline.test(ch))raise(start,"Unterminated regular expression");if(!escaped){if(ch==="[")inClass=true;else if(ch==="]"&&inClass)inClass=false;else if(ch==="/"&&!inClass)break;escaped=ch==="\\"}else escaped=false;++tokPos}var content=input.slice(start,tokPos);++tokPos;var mods=readWord1();var tmp=content;if(mods){var validFlags=/^[gmsiy]*$/;if(options.ecmaVersion>=6)validFlags=/^[gmsiyu]*$/;if(!validFlags.test(mods))raise(start,"Invalid regular expression flag");if(mods.indexOf("u")>=0&&!regexpUnicodeSupport){tmp=tmp.replace(/\\u\{([0-9a-fA-F]{5,6})\}/g,"x").replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"x")}}try{new RegExp(tmp)}catch(e){if(e instanceof SyntaxError)raise(start,"Error parsing regular expression: "+e.message);raise(e)}try{var value=new RegExp(content,mods)}catch(err){value=null}return finishToken(_regexp,{pattern:content,flags:mods,value:value})}function readInt(radix,len){var start=tokPos,total=0;for(var i=0,e=len==null?Infinity:len;i<e;++i){var code=input.charCodeAt(tokPos),val;if(code>=97)val=code-97+10;else if(code>=65)val=code-65+10;else if(code>=48&&code<=57)val=code-48;else val=Infinity;if(val>=radix)break;++tokPos;total=total*radix+val}if(tokPos===start||len!=null&&tokPos-start!==len)return null;return total}function readRadixNumber(radix){tokPos+=2;var val=readInt(radix);if(val==null)raise(tokStart+2,"Expected number in radix "+radix);if(isIdentifierStart(input.charCodeAt(tokPos)))raise(tokPos,"Identifier directly after number");return finishToken(_num,val)}function readNumber(startsWithDot){var start=tokPos,isFloat=false,octal=input.charCodeAt(tokPos)===48;if(!startsWithDot&&readInt(10)===null)raise(start,"Invalid number");if(input.charCodeAt(tokPos)===46){++tokPos;readInt(10);isFloat=true}var next=input.charCodeAt(tokPos);if(next===69||next===101){next=input.charCodeAt(++tokPos);if(next===43||next===45)++tokPos;if(readInt(10)===null)raise(start,"Invalid number");isFloat=true}if(isIdentifierStart(input.charCodeAt(tokPos)))raise(tokPos,"Identifier directly after number");var str=input.slice(start,tokPos),val;if(isFloat)val=parseFloat(str);else if(!octal||str.length===1)val=parseInt(str,10);else if(/[89]/.test(str)||strict)raise(start,"Invalid number");else val=parseInt(str,8);return finishToken(_num,val)}function readCodePoint(){var ch=input.charCodeAt(tokPos),code;if(ch===123){if(options.ecmaVersion<6)unexpected();++tokPos;code=readHexChar(input.indexOf("}",tokPos)-tokPos);++tokPos;if(code>1114111)unexpected()}else{code=readHexChar(4)}if(code<=65535){return String.fromCharCode(code)}var cu1=(code-65536>>10)+55296;var cu2=(code-65536&1023)+56320;return String.fromCharCode(cu1,cu2)}function readString(quote){var isJSX=curTokContext()===j_oTag;var out="",chunkStart=++tokPos;for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated string constant");var ch=input.charCodeAt(tokPos);if(ch===quote)break;if(ch===92&&!isJSX){out+=input.slice(chunkStart,tokPos);out+=readEscapedChar();chunkStart=tokPos}else if(ch===38&&isJSX){out+=input.slice(chunkStart,tokPos);out+=readJSXEntity();chunkStart=tokPos}else{if(isNewLine(ch))raise(tokStart,"Unterminated string constant");++tokPos}}out+=input.slice(chunkStart,tokPos++);return finishToken(_string,out)}function readTmplToken(){var out="",chunkStart=tokPos;for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated template");var ch=input.charCodeAt(tokPos);if(ch===96||ch===36&&input.charCodeAt(tokPos+1)===123){if(tokPos===tokStart&&tokType===_template){if(ch===36){tokPos+=2;return finishToken(_dollarBraceL)}else{++tokPos;return finishToken(_backQuote)}}out+=input.slice(chunkStart,tokPos);return finishToken(_template,out)}if(ch===92){out+=input.slice(chunkStart,tokPos);out+=readEscapedChar();chunkStart=tokPos}else if(isNewLine(ch)){out+=input.slice(chunkStart,tokPos);++tokPos;if(ch===13&&input.charCodeAt(tokPos)===10){++tokPos;out+="\n"}else{out+=String.fromCharCode(ch)}if(options.locations){++tokCurLine;tokLineStart=tokPos}chunkStart=tokPos}else{++tokPos}}}var XHTMLEntities={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"",zwj:"",lrm:"",rlm:"",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪","int":"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"};function readJSXEntity(){var str="",count=0,entity;var ch=input[tokPos];if(ch!=="&")raise(tokPos,"Entity must start with an ampersand");var startPos=++tokPos;while(tokPos<inputLen&&count++<10){ch=input[tokPos++];if(ch===";"){if(str[0]==="#"){if(str[1]==="x"){str=str.substr(2);if(hexNumber.test(str)){entity=String.fromCharCode(parseInt(str,16))}}else{str=str.substr(1);if(decimalNumber.test(str)){entity=String.fromCharCode(parseInt(str,10))}}}else{entity=XHTMLEntities[str]}break}str+=ch}if(!entity){tokPos=startPos;return"&"}return entity}function readJSXToken(){var out="",start=tokPos;for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated JSX contents");var ch=input.charCodeAt(tokPos);switch(ch){case 123:case 60:if(tokPos===start){return getTokenFromCode(ch)}return finishToken(_jsxText,out);case 38:out+=readJSXEntity();break;default:++tokPos;if(isNewLine(ch)){if(ch===13&&input.charCodeAt(tokPos)===10){++tokPos;ch=10}if(options.locations){++tokCurLine;tokLineStart=tokPos}}out+=String.fromCharCode(ch)}}}function readEscapedChar(){var ch=input.charCodeAt(++tokPos);var octal=/^[0-7]+/.exec(input.slice(tokPos,tokPos+3));if(octal)octal=octal[0];while(octal&&parseInt(octal,8)>255)octal=octal.slice(0,-1);if(octal==="0")octal=null;++tokPos;if(octal){if(strict)raise(tokPos-2,"Octal literal in strict mode");tokPos+=octal.length-1;return String.fromCharCode(parseInt(octal,8))}else{switch(ch){case 110:return"\n";case 114:return"\r";case 120:return String.fromCharCode(readHexChar(2));case 117:return readCodePoint();case 116:return" ";case 98:return"\b";case 118:return"";case 102:return"\f";case 48:return"\x00";case 13:if(input.charCodeAt(tokPos)===10)++tokPos;case 10:if(options.locations){tokLineStart=tokPos;++tokCurLine}return"";default:return String.fromCharCode(ch)}}}var XHTMLEntities={quot:'"',amp:"&",apos:"'",lt:"<",gt:">",nbsp:" ",iexcl:"¡",cent:"¢",pound:"£",curren:"¤",yen:"¥",brvbar:"¦",sect:"§",uml:"¨",copy:"©",ordf:"ª",laquo:"«",not:"¬",shy:"",reg:"®",macr:"¯",deg:"°",plusmn:"±",sup2:"²",sup3:"³",acute:"´",micro:"µ",para:"¶",middot:"·",cedil:"¸",sup1:"¹",ordm:"º",raquo:"»",frac14:"¼",frac12:"½",frac34:"¾",iquest:"¿",Agrave:"À",Aacute:"Á",Acirc:"Â",Atilde:"Ã",Auml:"Ä",Aring:"Å",AElig:"Æ",Ccedil:"Ç",Egrave:"È",Eacute:"É",Ecirc:"Ê",Euml:"Ë",Igrave:"Ì",Iacute:"Í",Icirc:"Î",Iuml:"Ï",ETH:"Ð",Ntilde:"Ñ",Ograve:"Ò",Oacute:"Ó",Ocirc:"Ô",Otilde:"Õ",Ouml:"Ö",times:"×",Oslash:"Ø",Ugrave:"Ù",Uacute:"Ú",Ucirc:"Û",Uuml:"Ü",Yacute:"Ý",THORN:"Þ",szlig:"ß",agrave:"à",aacute:"á",acirc:"â",atilde:"ã",auml:"ä",aring:"å",aelig:"æ",ccedil:"ç",egrave:"è",eacute:"é",ecirc:"ê",euml:"ë",igrave:"ì",iacute:"í",icirc:"î",iuml:"ï",eth:"ð",ntilde:"ñ",ograve:"ò",oacute:"ó",ocirc:"ô",otilde:"õ",ouml:"ö",divide:"÷",oslash:"ø",ugrave:"ù",uacute:"ú",ucirc:"û",uuml:"ü",yacute:"ý",thorn:"þ",yuml:"ÿ",OElig:"Œ",oelig:"œ",Scaron:"Š",scaron:"š",Yuml:"Ÿ",fnof:"ƒ",circ:"ˆ",tilde:"˜",Alpha:"Α",Beta:"Β",Gamma:"Γ",Delta:"Δ",Epsilon:"Ε",Zeta:"Ζ",Eta:"Η",Theta:"Θ",Iota:"Ι",Kappa:"Κ",Lambda:"Λ",Mu:"Μ",Nu:"Ν",Xi:"Ξ",Omicron:"Ο",Pi:"Π",Rho:"Ρ",Sigma:"Σ",Tau:"Τ",Upsilon:"Υ",Phi:"Φ",Chi:"Χ",Psi:"Ψ",Omega:"Ω",alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",omicron:"ο",pi:"π",rho:"ρ",sigmaf:"ς",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",chi:"χ",psi:"ψ",omega:"ω",thetasym:"ϑ",upsih:"ϒ",piv:"ϖ",ensp:" ",emsp:" ",thinsp:" ",zwnj:"",zwj:"",lrm:"",rlm:"",ndash:"–",mdash:"—",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",dagger:"†",Dagger:"‡",bull:"•",hellip:"…",permil:"‰",prime:"′",Prime:"″",lsaquo:"‹",rsaquo:"›",oline:"‾",frasl:"⁄",euro:"€",image:"ℑ",weierp:"℘",real:"ℜ",trade:"™",alefsym:"ℵ",larr:"←",uarr:"↑",rarr:"→",darr:"↓",harr:"↔",crarr:"↵",lArr:"⇐",uArr:"⇑",rArr:"⇒",dArr:"⇓",hArr:"⇔",forall:"∀",part:"∂",exist:"∃",empty:"∅",nabla:"∇",isin:"∈",notin:"∉",ni:"∋",prod:"∏",sum:"∑",minus:"−",lowast:"∗",radic:"√",prop:"∝",infin:"∞",ang:"∠",and:"∧",or:"∨",cap:"∩",cup:"∪","int":"∫",there4:"∴",sim:"∼",cong:"≅",asymp:"≈",ne:"≠",equiv:"≡",le:"≤",ge:"≥",sub:"⊂",sup:"⊃",nsub:"⊄",sube:"⊆",supe:"⊇",oplus:"⊕",otimes:"⊗",perp:"⊥",sdot:"⋅",lceil:"⌈",rceil:"⌉",lfloor:"⌊",rfloor:"⌋",lang:"〈",rang:"〉",loz:"◊",spades:"♠",clubs:"♣",hearts:"♥",diams:"♦"};function readXJSEntity(){var str="",count=0,entity;var ch=nextChar();if(ch!=="&")raise(tokPos,"Entity must start with an ampersand");var startPos=++tokPos;while(tokPos<inputLen&&count++<10){ch=nextChar();tokPos++;if(ch===";"){if(str[0]==="#"){if(str[1]==="x"){str=str.substr(2);if(hexNumber.test(str)){entity=String.fromCharCode(parseInt(str,16))}}else{str=str.substr(1);if(decimalNumber.test(str)){entity=String.fromCharCode(parseInt(str,10))}}}else{entity=XHTMLEntities[str]}break}str+=ch}if(!entity){tokPos=startPos;return"&"}return entity}function readXJSText(stopChars){var str="";while(tokPos<inputLen){var ch=nextChar();if(stopChars.indexOf(ch)!==-1){break}if(ch==="&"){str+=readXJSEntity()}else{++tokPos;if(ch==="\r"&&nextChar()==="\n"){str+=ch;++tokPos;ch="\n"}if(ch==="\n"&&options.locations){tokLineStart=tokPos;++tokCurLine}str+=ch}}return finishToken(_xjsText,str)}function readXJSStringLiteral(){var quote=input.charCodeAt(tokPos);if(quote!==34&"e!==39){raise("String literal must starts with a quote")}++tokPos;readXJSText([String.fromCharCode(quote)]);if(quote!==input.charCodeAt(tokPos)){unexpected()}++tokPos;return finishToken(tokType,tokVal)}function readHexChar(len){var n=readInt(16,len);if(n===null)raise(tokStart,"Bad character escape sequence");return n}var containsEsc;function readWord1(){containsEsc=false;var word="",first=true,chunkStart=tokPos;for(;;){var ch=input.charCodeAt(tokPos);if(isIdentifierChar(ch)){++tokPos}else if(ch===92){containsEsc=true;word+=input.slice(chunkStart,tokPos);if(input.charCodeAt(++tokPos)!=117)raise(tokPos,"Expecting Unicode escape sequence \\uXXXX");++tokPos;var esc=readHexChar(4);var escStr=String.fromCharCode(esc);if(!escStr)raise(tokPos-1,"Invalid Unicode escape");if(!(first?isIdentifierStart(esc):isIdentifierChar(esc)))raise(tokPos-4,"Invalid Unicode escape");word+=escStr;chunkStart=tokPos}else{break}first=false}return word+input.slice(chunkStart,tokPos)}function readWord(){var word=readWord1();var type=inXJSTag?_xjsName:_name;if(!containsEsc&&isKeyword(word))type=keywordTypes[word];return finishToken(type,word)}function readJSXWord(){var ch,start=tokPos;do{ch=input.charCodeAt(++tokPos)}while(isIdentifierChar(ch)||ch===45);return finishToken(_jsxName,input.slice(start,tokPos))}function next(){if(options.onToken)options.onToken(new Token);lastStart=tokStart;lastEnd=tokEnd;lastEndLoc=tokEndLoc;readToken()}function setStrict(strct){strict=strct;if(tokType!==_num&&tokType!==_string)return;tokPos=tokStart;if(options.locations){while(tokPos<tokLineStart){tokLineStart=input.lastIndexOf("\n",tokLineStart-2)+1;--tokCurLine}}skipSpace();readToken()}function Node(){this.type=null;this.start=tokStart;this.end=null}exports.Node=Node;function SourceLocation(){this.start=tokStartLoc;this.end=null;if(sourceFile!==null)this.source=sourceFile}function startNode(){var node=new exports.Node;if(options.locations)node.loc=new SourceLocation;if(options.directSourceFile)node.sourceFile=options.directSourceFile;if(options.ranges)node.range=[tokStart,0];return node}function storeCurrentPos(){return options.locations?[tokStart,tokStartLoc]:tokStart}function startNodeAt(pos){var node=new exports.Node,start=pos;if(options.locations){node.loc=new SourceLocation;node.loc.start=start[1];start=pos[0]}node.start=start;if(options.directSourceFile)node.sourceFile=options.directSourceFile;if(options.ranges)node.range=[start,0];return node}function finishNode(node,type){node.type=type;node.end=lastEnd;if(options.locations)node.loc.end=lastEndLoc;if(options.ranges)node.range[1]=lastEnd;return node}function finishNodeAt(node,type,pos){if(options.locations){node.loc.end=pos[1];pos=pos[0]}node.type=type;node.end=pos;if(options.ranges)node.range[1]=pos;return node}function isUseStrict(stmt){return options.ecmaVersion>=5&&stmt.type==="ExpressionStatement"&&stmt.expression.type==="Literal"&&stmt.expression.value==="use strict"}function eat(type){if(tokType===type){next();return true}else{return false}}function isContextual(name){return tokType===_name&&tokVal===name}function eatContextual(name){return tokVal===name&&eat(_name)}function expectContextual(name){if(!eatContextual(name))unexpected()}function canInsertSemicolon(){return!options.strictSemicolons&&(tokType===_eof||tokType===_braceR||newline.test(input.slice(lastEnd,tokStart)))}function semicolon(){if(!eat(_semi)&&!canInsertSemicolon())unexpected()}function expect(type){eat(type)||unexpected()}function nextChar(){return input.charAt(tokPos)}function unexpected(pos){raise(pos!=null?pos:tokStart,"Unexpected token")}function has(obj,propName){return Object.prototype.hasOwnProperty.call(obj,propName)}function toAssignable(node){if(options.ecmaVersion>=6&&node){switch(node.type){case"Identifier":case"MemberExpression":case"VirtualPropertyExpression":case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":break;case"ObjectExpression":node.type="ObjectPattern";for(var i=0;i<node.properties.length;i++){var prop=node.properties[i];if(prop.kind!=="init")raise(prop.key.start,"Object pattern can't contain getter or setter");toAssignable(prop.value)}break;case"ArrayExpression":node.type="ArrayPattern";toAssignableList(node.elements);break;case"AssignmentExpression":if(node.operator==="="){node.type="AssignmentPattern"}else{raise(node.left.end,"Only '=' operator can be used for specifying default value.")}break;default:raise(node.start,"Assigning to rvalue")}}return node}function toAssignableList(exprList){if(exprList.length){for(var i=0;i<exprList.length-1;i++){toAssignable(exprList[i])}var last=exprList[exprList.length-1];switch(last.type){case"RestElement":break;case"SpreadElement":last.type="RestElement";var arg=last.argument;toAssignable(arg);if(arg.type!=="Identifier"&&arg.type!=="ArrayPattern")unexpected(arg.start);break;default:toAssignable(last)}}return exprList}function parseSpread(refShorthandDefaultPos){var node=startNode();next();node.argument=parseMaybeAssign(refShorthandDefaultPos);return finishNode(node,"SpreadElement")}function parseRest(){var node=startNode();next();node.argument=tokType===_name||tokType===_bracketL?parseAssignableAtom():unexpected();return finishNode(node,"RestElement")}function parseAssignableAtom(){if(options.ecmaVersion<6)return parseIdent();switch(tokType){case _name:return parseIdent();case _bracketL:var node=startNode();next();node.elements=parseAssignableList(_bracketR,true);return finishNode(node,"ArrayPattern");case _braceL:return parseObj(true);default:unexpected()}}function parseAssignableList(close,allowEmpty){var elts=[],first=true;while(!eat(close)){first?first=false:expect(_comma);if(tokType===_ellipsis){elts.push(parseAssignableListItemTypes(parseRest()));expect(close);break}var elem;if(allowEmpty&&tokType===_comma){elem=null}else{var left=parseAssignableAtom();parseAssignableListItemTypes(left);elem=parseMaybeDefault(null,left)}elts.push(elem)}return elts}function parseAssignableListItemTypes(param){if(eat(_question)){param.optional=true}if(tokType===_colon){param.typeAnnotation=parseTypeAnnotation()}finishNode(param,param.type);return param}function parseMaybeDefault(startPos,left){left=left||parseAssignableAtom();if(!eat(_eq))return left;var node=startPos?startNodeAt(startPos):startNode();node.operator="=";node.left=left;node.right=parseMaybeAssign();return finishNode(node,"AssignmentPattern")}function checkFunctionParam(param,nameHash){switch(param.type){case"Identifier":if(isStrictReservedWord(param.name)||isStrictBadIdWord(param.name))raise(param.start,"Defining '"+param.name+"' in strict mode");if(has(nameHash,param.name))raise(param.start,"Argument name clash in strict mode");nameHash[param.name]=true;break;case"ObjectPattern":for(var i=0;i<param.properties.length;i++)checkFunctionParam(param.properties[i].value,nameHash);break;case"ArrayPattern":for(var i=0;i<param.elements.length;i++){var elem=param.elements[i];if(elem)checkFunctionParam(elem,nameHash)}break;case"RestElement":return checkFunctionParam(param.argument,nameHash)}}function checkPropClash(prop,propHash){if(options.ecmaVersion>=6)return;var key=prop.key,name;switch(key.type){case"Identifier":name=key.name;break;case"Literal":name=String(key.value);break;default:return}var kind=prop.kind||"init",other;if(has(propHash,name)){other=propHash[name];var isGetSet=kind!=="init";if((strict||isGetSet)&&other[kind]||!(isGetSet^other.init))raise(key.start,"Redefinition of property")}else{other=propHash[name]={init:false,get:false,set:false}}other[kind]=true}function checkLVal(expr,isBinding){switch(expr.type){case"Identifier":if(strict&&(isStrictBadIdWord(expr.name)||isStrictReservedWord(expr.name)))raise(expr.start,(isBinding?"Binding ":"Assigning to ")+expr.name+" in strict mode");break;case"MemberExpression":if(isBinding)raise(expr.start,"Binding to member expression");break;case"ObjectPattern":for(var i=0;i<expr.properties.length;i++){var prop=expr.properties[i];if(prop.type==="Property")prop=prop.value;checkLVal(prop,isBinding)}break;case"ArrayPattern":for(var i=0;i<expr.elements.length;i++){var elem=expr.elements[i];if(elem)checkLVal(elem,isBinding)}break;case"AssignmentPattern":checkLVal(expr.left);break;case"SpreadProperty":case"VirtualPropertyExpression":break;case"RestElement":checkLVal(expr.argument);break;default:raise(expr.start,"Assigning to rvalue")}}function parseTopLevel(node){var first=true;if(!node.body)node.body=[];while(tokType!==_eof){var stmt=parseStatement(true,true);node.body.push(stmt);if(first&&isUseStrict(stmt))setStrict(true);first=false}next();return finishNode(node,"Program")}var loopLabel={kind:"loop"},switchLabel={kind:"switch"};function parseStatement(declaration,topLevel){var starttype=tokType,node=startNode();switch(starttype){case _break:case _continue:return parseBreakContinueStatement(node,starttype.keyword);case _debugger:return parseDebuggerStatement(node);case _do:return parseDoStatement(node);case _for:return parseForStatement(node);case _function:if(!declaration&&options.ecmaVersion>=6)unexpected();return parseFunctionStatement(node);case _class:if(!declaration)unexpected();return parseClass(node,true);case _if:return parseIfStatement(node);case _return:return parseReturnStatement(node);case _switch:return parseSwitchStatement(node);case _throw:return parseThrowStatement(node);case _try:return parseTryStatement(node);case _let:case _const:if(!declaration)unexpected();case _var:return parseVarStatement(node,starttype.keyword);case _while:return parseWhileStatement(node);case _with:return parseWithStatement(node);case _braceL:return parseBlock();case _semi:return parseEmptyStatement(node);case _export:case _import:if(!topLevel&&!options.allowImportExportEverywhere)raise(tokStart,"'import' and 'export' may only appear at the top level");return starttype===_import?parseImport(node):parseExport(node);default:var maybeName=tokVal,expr=parseExpression();if(options.ecmaVersion>=7&&starttype===_name&&maybeName==="async"&&tokType===_function&&!canInsertSemicolon()){next();var func=parseFunctionStatement(node);func.async=true;return func}if(starttype===_name&&expr.type==="Identifier"){if(eat(_colon)){return parseLabeledStatement(node,maybeName,expr)}if(options.ecmaVersion>=7&&expr.name==="private"&&tokType===_name){return parsePrivate(node)}else if(expr.name==="declare"){if(tokType===_class||tokType===_name||tokType===_function||tokType===_var){return parseDeclare(node)}}else if(tokType===_name){if(expr.name==="interface"){return parseInterface(node)}else if(expr.name==="type"){return parseTypeAlias(node)}}}if(expr.type==="FunctionExpression"&&expr.async){if(expr.id){expr.type="FunctionDeclaration";return expr}else{unexpected(expr.start+"async function ".length)}}return parseExpressionStatement(node,expr)}}function parseBreakContinueStatement(node,keyword){var isBreak=keyword=="break";next();if(eat(_semi)||canInsertSemicolon())node.label=null;else if(tokType!==_name)unexpected();else{node.label=parseIdent();semicolon()}for(var i=0;i<labels.length;++i){var lab=labels[i];if(node.label==null||lab.name===node.label.name){if(lab.kind!=null&&(isBreak||lab.kind==="loop"))break;if(node.label&&isBreak)break}}if(i===labels.length)raise(node.start,"Unsyntactic "+keyword);return finishNode(node,isBreak?"BreakStatement":"ContinueStatement")}function parseDebuggerStatement(node){next();semicolon();return finishNode(node,"DebuggerStatement")}function parseDoStatement(node){next();labels.push(loopLabel);node.body=parseStatement(false);labels.pop();expect(_while);node.test=parseParenExpression();if(options.ecmaVersion>=6)eat(_semi);else semicolon();return finishNode(node,"DoWhileStatement")}function parseForStatement(node){next();labels.push(loopLabel);expect(_parenL);if(tokType===_semi)return parseFor(node,null);if(tokType===_var||tokType===_let){var init=startNode(),varKind=tokType.keyword,isLet=tokType===_let;next();parseVar(init,true,varKind);finishNode(init,"VariableDeclaration");if((tokType===_in||options.ecmaVersion>=6&&isContextual("of"))&&init.declarations.length===1&&!(isLet&&init.declarations[0].init))return parseForIn(node,init);return parseFor(node,init)}var refShorthandDefaultPos={start:0};var init=parseExpression(true,refShorthandDefaultPos);if(tokType===_in||options.ecmaVersion>=6&&isContextual("of")){toAssignable(init);checkLVal(init);return parseForIn(node,init)}else if(refShorthandDefaultPos.start){unexpected(refShorthandDefaultPos.start)}return parseFor(node,init)}function parseFunctionStatement(node){next();return parseFunction(node,true,false)}function parseIfStatement(node){next();node.test=parseParenExpression();node.consequent=parseStatement(false);node.alternate=eat(_else)?parseStatement(false):null;return finishNode(node,"IfStatement")}function parseReturnStatement(node){if(!inFunction&&!options.allowReturnOutsideFunction)raise(tokStart,"'return' outside of function");next();if(eat(_semi)||canInsertSemicolon())node.argument=null;else{node.argument=parseExpression();semicolon()}return finishNode(node,"ReturnStatement")}function parseSwitchStatement(node){next();node.discriminant=parseParenExpression();node.cases=[];expect(_braceL);labels.push(switchLabel);for(var cur,sawDefault;tokType!=_braceR;){if(tokType===_case||tokType===_default){var isCase=tokType===_case;if(cur)finishNode(cur,"SwitchCase");node.cases.push(cur=startNode());cur.consequent=[];next();if(isCase)cur.test=parseExpression();else{if(sawDefault)raise(lastStart,"Multiple default clauses");sawDefault=true;cur.test=null}expect(_colon)}else{if(!cur)unexpected(); | arr.writeInt16BE=BP.writeInt16BE;arr.writeInt32LE=BP.writeInt32LE;arr.writeInt32BE=BP.writeInt32BE;arr.writeFloatLE=BP.writeFloatLE;arr.writeFloatBE=BP.writeFloatBE;arr.writeDoubleLE=BP.writeDoubleLE;arr.writeDoubleBE=BP.writeDoubleBE;arr.fill=BP.fill;arr.inspect=BP.inspect;arr.toArrayBuffer=BP.toArrayBuffer;return arr};var INVALID_BASE64_RE=/[^+\/0-9A-z\-]/g;function base64clean(str){str=stringtrim(str).replace(INVALID_BASE64_RE,"");if(str.length<2)return"";while(str.length%4!==0){str=str+"="}return str}function stringtrim(str){if(str.trim)return str.trim();return str.replace(/^\s+|\s+$/g,"")}function isArrayish(subject){return isArray(subject)||Buffer.isBuffer(subject)||subject&&typeof subject==="object"&&typeof subject.length==="number"}function toHex(n){if(n<16)return"0"+n.toString(16);return n.toString(16)}function utf8ToBytes(string,units){var codePoint,length=string.length;var leadSurrogate=null;units=units||Infinity;var bytes=[];var i=0;for(;i<length;i++){codePoint=string.charCodeAt(i);if(codePoint>55295&&codePoint<57344){if(leadSurrogate){if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}else{codePoint=leadSurrogate-55296<<10|codePoint-56320|65536;leadSurrogate=null}}else{if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}else{leadSurrogate=codePoint;continue}}}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=null}if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<2097152){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){byteArray.push(str.charCodeAt(i)&255)}return byteArray}function utf16leToBytes(str,units){var c,hi,lo;var byteArray=[];for(var i=0;i<str.length;i++){if((units-=2)<0)break;c=str.charCodeAt(i);hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length,unitSize){if(unitSize)length-=length%unitSize;for(var i=0;i<length;i++){if(i+offset>=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function decodeUtf8Char(str){try{return decodeURIComponent(str)}catch(err){return String.fromCharCode(65533)}}},{"base64-js":123,ieee754:124,"is-array":125}],123:[function(require,module,exports){var lookup="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";(function(exports){"use strict";var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var PLUS="+".charCodeAt(0);var SLASH="/".charCodeAt(0);var NUMBER="0".charCodeAt(0);var LOWER="a".charCodeAt(0);var UPPER="A".charCodeAt(0);var PLUS_URL_SAFE="-".charCodeAt(0);var SLASH_URL_SAFE="_".charCodeAt(0);function decode(elt){var code=elt.charCodeAt(0);if(code===PLUS||code===PLUS_URL_SAFE)return 62;if(code===SLASH||code===SLASH_URL_SAFE)return 63;if(code<NUMBER)return-1;if(code<NUMBER+10)return code-NUMBER+26+26;if(code<UPPER+26)return code-UPPER;if(code<LOWER+26)return code-LOWER+26}function b64ToByteArray(b64){var i,j,l,tmp,placeHolders,arr;if(b64.length%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}var len=b64.length;placeHolders="="===b64.charAt(len-2)?2:"="===b64.charAt(len-1)?1:0;arr=new Arr(b64.length*3/4-placeHolders);l=placeHolders>0?b64.length-4:b64.length;var L=0;function push(v){arr[L++]=v}for(i=0,j=0;i<l;i+=4,j+=3){tmp=decode(b64.charAt(i))<<18|decode(b64.charAt(i+1))<<12|decode(b64.charAt(i+2))<<6|decode(b64.charAt(i+3));push((tmp&16711680)>>16);push((tmp&65280)>>8);push(tmp&255)}if(placeHolders===2){tmp=decode(b64.charAt(i))<<2|decode(b64.charAt(i+1))>>4;push(tmp&255)}else if(placeHolders===1){tmp=decode(b64.charAt(i))<<10|decode(b64.charAt(i+1))<<4|decode(b64.charAt(i+2))>>2;push(tmp>>8&255);push(tmp&255)}return arr}function uint8ToBase64(uint8){var i,extraBytes=uint8.length%3,output="",temp,length;function encode(num){return lookup.charAt(num)}function tripletToBase64(num){return encode(num>>18&63)+encode(num>>12&63)+encode(num>>6&63)+encode(num&63)}for(i=0,length=uint8.length-extraBytes;i<length;i+=3){temp=(uint8[i]<<16)+(uint8[i+1]<<8)+uint8[i+2];output+=tripletToBase64(temp)}switch(extraBytes){case 1:temp=uint8[uint8.length-1];output+=encode(temp>>2);output+=encode(temp<<4&63);output+="==";break;case 2:temp=(uint8[uint8.length-2]<<8)+uint8[uint8.length-1];output+=encode(temp>>10);output+=encode(temp>>4&63);output+=encode(temp<<2&63);output+="=";break}return output}exports.toByteArray=b64ToByteArray;exports.fromByteArray=uint8ToBase64})(typeof exports==="undefined"?this.base64js={}:exports)},{}],124:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8);m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8);if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8);e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=s*128}},{}],125:[function(require,module,exports){var isArray=Array.isArray;var str=Object.prototype.toString;module.exports=isArray||function(val){return!!val&&"[object Array]"==str.call(val)}},{}],126:[function(require,module,exports){function EventEmitter(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;EventEmitter.defaultMaxListeners=10;EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||n<0||isNaN(n))throw TypeError("n must be a positive number");this._maxListeners=n;return this};EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(!this._events)this._events={};if(type==="error"){if(!this._events.error||isObject(this._events.error)&&!this._events.error.length){er=arguments[1];if(er instanceof Error){throw er}throw TypeError('Uncaught, unspecified "error" event.')}}handler=this._events[type];if(isUndefined(handler))return false;if(isFunction(handler)){switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];handler.apply(this,args)}}else if(isObject(handler)){len=arguments.length;args=new Array(len-1);for(i=1;i<len;i++)args[i-1]=arguments[i];listeners=handler.slice();len=listeners.length;for(i=0;i<len;i++)listeners[i].apply(this,args)}return true};EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events)this._events={};if(this._events.newListener)this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener);if(!this._events[type])this._events[type]=listener;else if(isObject(this._events[type]))this._events[type].push(listener);else this._events[type]=[this._events[type],listener];if(isObject(this._events[type])&&!this._events[type].warned){var m;if(!isUndefined(this._maxListeners)){m=this._maxListeners}else{m=EventEmitter.defaultMaxListeners}if(m&&m>0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-->0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else{while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.listenerCount=function(emitter,type){var ret;if(!emitter._events||!emitter._events[type])ret=0;else if(isFunction(emitter._events[type]))ret=1;else ret=emitter._events[type].length;return ret};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],127:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],128:[function(require,module,exports){module.exports=Array.isArray||function(arr){return Object.prototype.toString.call(arr)=="[object Array]"}},{}],129:[function(require,module,exports){(function(process){function normalizeArray(parts,allowAboveRoot){var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up--;up){parts.unshift("..")}}return parts}var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var splitPath=function(filename){return splitPathRe.exec(filename).slice(1)};exports.resolve=function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:process.cwd();if(typeof path!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){continue}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=path.charAt(0)==="/"}resolvedPath=normalizeArray(filter(resolvedPath.split("/"),function(p){return!!p}),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."};exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash=substr(path,-1)==="/";path=normalizeArray(filter(path.split("/"),function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path};exports.isAbsolute=function(path){return path.charAt(0)==="/"};exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p,index){if(typeof p!=="string"){throw new TypeError("Arguments to path.join must be strings")}return p}).join("/"))};exports.relative=function(from,to){from=exports.resolve(from).substr(1);to=exports.resolve(to).substr(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")};exports.sep="/";exports.delimiter=":";exports.dirname=function(path){var result=splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir};exports.basename=function(path,ext){var f=splitPath(path)[2];if(ext&&f.substr(-1*ext.length)===ext){f=f.substr(0,f.length-ext.length)}return f};exports.extname=function(path){return splitPath(path)[3]};function filter(xs,f){if(xs.filter)return xs.filter(f);var res=[];for(var i=0;i<xs.length;i++){if(f(xs[i],i,xs))res.push(xs[i])}return res}var substr="ab".substr(-1)==="b"?function(str,start,len){return str.substr(start,len)}:function(str,start,len){if(start<0)start=str.length+start;return str.substr(start,len)}}).call(this,require("_process"))},{_process:130}],130:[function(require,module,exports){var process=module.exports={};var queue=[];var draining=false;function drainQueue(){if(draining){return}draining=true;var currentQueue;var len=queue.length;while(len){currentQueue=queue;queue=[];var i=-1;while(++i<len){currentQueue[i]()}len=queue.length}draining=false}process.nextTick=function(fun){queue.push(fun);if(!draining){setTimeout(drainQueue,0)}};process.title="browser";process.browser=true;process.env={};process.argv=[];process.version="";function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")};process.umask=function(){return 0}},{}],131:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":132}],132:[function(require,module,exports){(function(process){module.exports=Duplex;var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj)keys.push(key);return keys};var util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable");var Writable=require("./_stream_writable");util.inherits(Duplex,Readable);forEach(objectKeys(Writable.prototype),function(method){if(!Duplex.prototype[method])Duplex.prototype[method]=Writable.prototype[method]});function Duplex(options){if(!(this instanceof Duplex))return new Duplex(options);Readable.call(this,options);Writable.call(this,options);if(options&&options.readable===false)this.readable=false;if(options&&options.writable===false)this.writable=false;this.allowHalfOpen=true;if(options&&options.allowHalfOpen===false)this.allowHalfOpen=false;this.once("end",onend)}function onend(){if(this.allowHalfOpen||this._writableState.ended)return;process.nextTick(this.end.bind(this))}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}}).call(this,require("_process"))},{"./_stream_readable":134,"./_stream_writable":136,_process:130,"core-util-is":137,inherits:127}],133:[function(require,module,exports){module.exports=PassThrough;var Transform=require("./_stream_transform");var util=require("core-util-is");util.inherits=require("inherits");util.inherits(PassThrough,Transform);function PassThrough(options){if(!(this instanceof PassThrough))return new PassThrough(options);Transform.call(this,options)}PassThrough.prototype._transform=function(chunk,encoding,cb){cb(null,chunk)}},{"./_stream_transform":135,"core-util-is":137,inherits:127}],134:[function(require,module,exports){(function(process){module.exports=Readable;var isArray=require("isarray");var Buffer=require("buffer").Buffer;Readable.ReadableState=ReadableState;var EE=require("events").EventEmitter;if(!EE.listenerCount)EE.listenerCount=function(emitter,type){return emitter.listeners(type).length};var Stream=require("stream");var util=require("core-util-is");util.inherits=require("inherits");var StringDecoder;util.inherits(Readable,Stream);function ReadableState(options,stream){options=options||{};var hwm=options.highWaterMark;this.highWaterMark=hwm||hwm===0?hwm:16*1024;this.highWaterMark=~~this.highWaterMark;this.buffer=[];this.length=0;this.pipes=null;this.pipesCount=0;this.flowing=false;this.ended=false;this.endEmitted=false;this.reading=false;this.calledRead=false;this.sync=true;this.needReadable=false;this.emittedReadable=false;this.readableListening=false;this.objectMode=!!options.objectMode;this.defaultEncoding=options.defaultEncoding||"utf8";this.ranOut=false;this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(options.encoding){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this.decoder=new StringDecoder(options.encoding);this.encoding=options.encoding}}function Readable(options){if(!(this instanceof Readable))return new Readable(options);this._readableState=new ReadableState(options,this);this.readable=true;Stream.call(this)}Readable.prototype.push=function(chunk,encoding){var state=this._readableState;if(typeof chunk==="string"&&!state.objectMode){encoding=encoding||state.defaultEncoding;if(encoding!==state.encoding){chunk=new Buffer(chunk,encoding);encoding=""}}return readableAddChunk(this,state,chunk,encoding,false)};Readable.prototype.unshift=function(chunk){var state=this._readableState;return readableAddChunk(this,state,chunk,"",true)};function readableAddChunk(stream,state,chunk,encoding,addToFront){var er=chunkInvalid(state,chunk);if(er){stream.emit("error",er)}else if(chunk===null||chunk===undefined){state.reading=false;if(!state.ended)onEofChunk(stream,state)}else if(state.objectMode||chunk&&chunk.length>0){if(state.ended&&!addToFront){var e=new Error("stream.push() after EOF");stream.emit("error",e)}else if(state.endEmitted&&addToFront){var e=new Error("stream.unshift() after end event");stream.emit("error",e)}else{if(state.decoder&&!addToFront&&!encoding)chunk=state.decoder.write(chunk);state.length+=state.objectMode?1:chunk.length;if(addToFront){state.buffer.unshift(chunk)}else{state.reading=false;state.buffer.push(chunk)}if(state.needReadable)emitReadable(stream);maybeReadMore(stream,state)}}else if(!addToFront){state.reading=false}return needMoreData(state)}function needMoreData(state){return!state.ended&&(state.needReadable||state.length<state.highWaterMark||state.length===0)}Readable.prototype.setEncoding=function(enc){if(!StringDecoder)StringDecoder=require("string_decoder/").StringDecoder;this._readableState.decoder=new StringDecoder(enc);this._readableState.encoding=enc};var MAX_HWM=8388608;function roundUpToNextPowerOf2(n){if(n>=MAX_HWM){n=MAX_HWM}else{n--;for(var p=1;p<32;p<<=1)n|=n>>p;n++}return n}function howMuchToRead(n,state){if(state.length===0&&state.ended)return 0;if(state.objectMode)return n===0?0:1;if(n===null||isNaN(n)){if(state.flowing&&state.buffer.length)return state.buffer[0].length;else return state.length}if(n<=0)return 0;if(n>state.highWaterMark)state.highWaterMark=roundUpToNextPowerOf2(n);if(n>state.length){if(!state.ended){state.needReadable=true;return 0}else return state.length}return n}Readable.prototype.read=function(n){var state=this._readableState;state.calledRead=true;var nOrig=n;var ret;if(typeof n!=="number"||n>0)state.emittedReadable=false;if(n===0&&state.needReadable&&(state.length>=state.highWaterMark||state.ended)){emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){ret=null;if(state.length>0&&state.decoder){ret=fromList(n,state);state.length-=ret.length}if(state.length===0)endReadable(this);return ret}var doRead=state.needReadable;if(state.length-n<=state.highWaterMark)doRead=true;if(state.ended||state.reading)doRead=false;if(doRead){state.reading=true;state.sync=true;if(state.length===0)state.needReadable=true;this._read(state.highWaterMark);state.sync=false}if(doRead&&!state.reading)n=howMuchToRead(nOrig,state);if(n>0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=true;n=0}state.length-=n;if(state.length===0&&!state.ended)state.needReadable=true;if(state.ended&&!state.endEmitted&&state.length===0)endReadable(this);return ret};function chunkInvalid(state,chunk){var er=null;if(!Buffer.isBuffer(chunk)&&"string"!==typeof chunk&&chunk!==null&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function onEofChunk(stream,state){if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;if(state.length>0)emitReadable(stream);else endReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(state.emittedReadable)return;state.emittedReadable=true;if(state.sync)process.nextTick(function(){emitReadable_(stream)});else emitReadable_(stream)}function emitReadable_(stream){stream.emit("readable")}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;process.nextTick(function(){maybeReadMore_(stream,state)})}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length<state.highWaterMark){stream.read(0);if(len===state.length)break;else len=state.length}state.readingMore=false}Readable.prototype._read=function(n){this.emit("error",new Error("not implemented"))};Readable.prototype.pipe=function(dest,pipeOpts){var src=this;var state=this._readableState;switch(state.pipesCount){case 0:state.pipes=dest;break;case 1:state.pipes=[state.pipes,dest];break;default:state.pipes.push(dest);break}state.pipesCount+=1;var doEnd=(!pipeOpts||pipeOpts.end!==false)&&dest!==process.stdout&&dest!==process.stderr;var endFn=doEnd?onend:cleanup;if(state.endEmitted)process.nextTick(endFn);else src.once("end",endFn);dest.on("unpipe",onunpipe);function onunpipe(readable){if(readable!==src)return;cleanup()}function onend(){dest.end()}var ondrain=pipeOnDrain(src);dest.on("drain",ondrain);function cleanup(){dest.removeListener("close",onclose);dest.removeListener("finish",onfinish);dest.removeListener("drain",ondrain);dest.removeListener("error",onerror);dest.removeListener("unpipe",onunpipe);src.removeListener("end",onend);src.removeListener("end",cleanup);if(!dest._writableState||dest._writableState.needDrain)ondrain()}function onerror(er){unpipe();dest.removeListener("error",onerror);if(EE.listenerCount(dest,"error")===0)dest.emit("error",er)}if(!dest._events||!dest._events.error)dest.on("error",onerror);else if(isArray(dest._events.error))dest._events.error.unshift(onerror);else dest._events.error=[onerror,dest._events.error];function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){this.on("readable",pipeOnReadable);state.flowing=true;process.nextTick(function(){flow(src)})}return dest};function pipeOnDrain(src){return function(){var dest=this;var state=src._readableState;state.awaitDrain--;if(state.awaitDrain===0)flow(src)}}function flow(src){var state=src._readableState;var chunk;state.awaitDrain=0;function write(dest,i,list){var written=dest.write(chunk);if(false===written){state.awaitDrain++}}while(state.pipesCount&&null!==(chunk=src.read())){if(state.pipesCount===1)write(state.pipes,0,null);else forEach(state.pipes,write);src.emit("data",chunk);if(state.awaitDrain>0)return}if(state.pipesCount===0){state.flowing=false;if(EE.listenerCount(src,"data")>0)emitDataEvents(src);return}state.ranOut=true}function pipeOnReadable(){if(this._readableState.ranOut){this._readableState.ranOut=false;flow(this)}}Readable.prototype.unpipe=function(dest){var state=this._readableState;if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;this.removeListener("readable",pipeOnReadable);state.flowing=false;if(dest)dest.emit("unpipe",this);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;this.removeListener("readable",pipeOnReadable);state.flowing=false;for(var i=0;i<len;i++)dests[i].emit("unpipe",this);return this}var i=indexOf(state.pipes,dest);if(i===-1)return this;state.pipes.splice(i,1);state.pipesCount-=1;if(state.pipesCount===1)state.pipes=state.pipes[0];dest.emit("unpipe",this);return this};Readable.prototype.on=function(ev,fn){var res=Stream.prototype.on.call(this,ev,fn);if(ev==="data"&&!this._readableState.flowing)emitDataEvents(this);if(ev==="readable"&&this.readable){var state=this._readableState;if(!state.readableListening){state.readableListening=true;state.emittedReadable=false;state.needReadable=true;if(!state.reading){this.read(0)}else if(state.length){emitReadable(this,state)}}}return res};Readable.prototype.addListener=Readable.prototype.on;Readable.prototype.resume=function(){emitDataEvents(this);this.read(0);this.emit("resume")};Readable.prototype.pause=function(){emitDataEvents(this,true);this.emit("pause")};function emitDataEvents(stream,startPaused){var state=stream._readableState;if(state.flowing){throw new Error("Cannot switch to old mode now.")}var paused=startPaused||false;var readable=false;stream.readable=true;stream.pipe=Stream.prototype.pipe;stream.on=stream.addListener=Stream.prototype.on;stream.on("readable",function(){readable=true;var c;while(!paused&&null!==(c=stream.read()))stream.emit("data",c);if(c===null){readable=false;stream._readableState.needReadable=true}});stream.pause=function(){paused=true;this.emit("pause")};stream.resume=function(){paused=false;if(readable)process.nextTick(function(){stream.emit("readable")});else this.read(0);this.emit("resume")};stream.emit("readable")}Readable.prototype.wrap=function(stream){var state=this._readableState;var paused=false;var self=this;stream.on("end",function(){if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length)self.push(chunk)}self.push(null)});stream.on("data",function(chunk){if(state.decoder)chunk=state.decoder.write(chunk);if(state.objectMode&&(chunk===null||chunk===undefined))return;else if(!state.objectMode&&(!chunk||!chunk.length))return;var ret=self.push(chunk);if(!ret){paused=true;stream.pause()}});for(var i in stream){if(typeof stream[i]==="function"&&typeof this[i]==="undefined"){this[i]=function(method){return function(){return stream[method].apply(stream,arguments)}}(i)}}var events=["error","close","destroy","pause","resume"];forEach(events,function(ev){stream.on(ev,self.emit.bind(self,ev))});self._read=function(n){if(paused){paused=false;stream.resume()}};return self};Readable._fromList=fromList;function fromList(n,state){var list=state.buffer;var length=state.length;var stringMode=!!state.decoder;var objectMode=!!state.objectMode;var ret;if(list.length===0)return null;if(length===0)ret=null;else if(objectMode)ret=list.shift();else if(!n||n>=length){if(stringMode)ret=list.join("");else ret=Buffer.concat(list,length);list.length=0}else{if(n<list[0].length){var buf=list[0];ret=buf.slice(0,n);list[0]=buf.slice(n)}else if(n===list[0].length){ret=list.shift()}else{if(stringMode)ret="";else ret=new Buffer(n);var c=0;for(var i=0,l=list.length;i<l&&c<n;i++){var buf=list[0];var cpy=Math.min(n-c,buf.length);if(stringMode)ret+=buf.slice(0,cpy);else buf.copy(ret,c,0,cpy);if(cpy<buf.length)list[0]=buf.slice(cpy);else list.shift();c+=cpy}}}return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error("endReadable called on non-empty stream");if(!state.endEmitted&&state.calledRead){state.ended=true;process.nextTick(function(){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}})}}function forEach(xs,f){for(var i=0,l=xs.length;i<l;i++){f(xs[i],i)}}function indexOf(xs,x){for(var i=0,l=xs.length;i<l;i++){if(xs[i]===x)return i}return-1}}).call(this,require("_process"))},{_process:130,buffer:122,"core-util-is":137,events:126,inherits:127,isarray:128,stream:142,"string_decoder/":143}],135:[function(require,module,exports){module.exports=Transform;var Duplex=require("./_stream_duplex");var util=require("core-util-is");util.inherits=require("inherits");util.inherits(Transform,Duplex);function TransformState(options,stream){this.afterTransform=function(er,data){return afterTransform(stream,er,data)};this.needTransform=false;this.transforming=false;this.writecb=null;this.writechunk=null}function afterTransform(stream,er,data){var ts=stream._transformState;ts.transforming=false;var cb=ts.writecb;if(!cb)return stream.emit("error",new Error("no writecb in Transform class"));ts.writechunk=null;ts.writecb=null;if(data!==null&&data!==undefined)stream.push(data);if(cb)cb(er);var rs=stream._readableState;rs.reading=false;if(rs.needReadable||rs.length<rs.highWaterMark){stream._read(rs.highWaterMark)}}function Transform(options){if(!(this instanceof Transform))return new Transform(options);Duplex.call(this,options);var ts=this._transformState=new TransformState(options,this);var stream=this;this._readableState.needReadable=true;this._readableState.sync=false;this.once("finish",function(){if("function"===typeof this._flush)this._flush(function(er){done(stream,er)});else done(stream)})}Transform.prototype.push=function(chunk,encoding){this._transformState.needTransform=false;return Duplex.prototype.push.call(this,chunk,encoding)};Transform.prototype._transform=function(chunk,encoding,cb){throw new Error("not implemented")};Transform.prototype._write=function(chunk,encoding,cb){var ts=this._transformState;ts.writecb=cb;ts.writechunk=chunk;ts.writeencoding=encoding;if(!ts.transforming){var rs=this._readableState;if(ts.needTransform||rs.needReadable||rs.length<rs.highWaterMark)this._read(rs.highWaterMark)
}};Transform.prototype._read=function(n){var ts=this._transformState;if(ts.writechunk!==null&&ts.writecb&&!ts.transforming){ts.transforming=true;this._transform(ts.writechunk,ts.writeencoding,ts.afterTransform)}else{ts.needTransform=true}};function done(stream,er){if(er)return stream.emit("error",er);var ws=stream._writableState;var rs=stream._readableState;var ts=stream._transformState;if(ws.length)throw new Error("calling transform done when ws.length != 0");if(ts.transforming)throw new Error("calling transform done when still transforming");return stream.push(null)}},{"./_stream_duplex":132,"core-util-is":137,inherits:127}],136:[function(require,module,exports){(function(process){module.exports=Writable;var Buffer=require("buffer").Buffer;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var Stream=require("stream");util.inherits(Writable,Stream);function WriteReq(chunk,encoding,cb){this.chunk=chunk;this.encoding=encoding;this.callback=cb}function WritableState(options,stream){options=options||{};var hwm=options.highWaterMark;this.highWaterMark=hwm||hwm===0?hwm:16*1024;this.objectMode=!!options.objectMode;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.buffer=[];this.errorEmitted=false}function Writable(options){var Duplex=require("./_stream_duplex");if(!(this instanceof Writable)&&!(this instanceof Duplex))return new Writable(options);this._writableState=new WritableState(options,this);this.writable=true;Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe. Not readable."))};function writeAfterEnd(stream,state,cb){var er=new Error("write after end");stream.emit("error",er);process.nextTick(function(){cb(er)})}function validChunk(stream,state,chunk,cb){var valid=true;if(!Buffer.isBuffer(chunk)&&"string"!==typeof chunk&&chunk!==null&&chunk!==undefined&&!state.objectMode){var er=new TypeError("Invalid non-string/buffer chunk");stream.emit("error",er);process.nextTick(function(){cb(er)});valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;if(typeof encoding==="function"){cb=encoding;encoding=null}if(Buffer.isBuffer(chunk))encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=function(){};if(state.ended)writeAfterEnd(this,state,cb);else if(validChunk(this,state,chunk,cb))ret=writeOrBuffer(this,state,chunk,encoding,cb);return ret};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=new Buffer(chunk,encoding)}return chunk}function writeOrBuffer(stream,state,chunk,encoding,cb){chunk=decodeChunk(state,chunk,encoding);if(Buffer.isBuffer(chunk))encoding="buffer";var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length<state.highWaterMark;if(!ret)state.needDrain=true;if(state.writing)state.buffer.push(new WriteReq(chunk,encoding,cb));else doWrite(stream,state,len,chunk,encoding,cb);return ret}function doWrite(stream,state,len,chunk,encoding,cb){state.writelen=len;state.writecb=cb;state.writing=true;state.sync=true;stream._write(chunk,encoding,state.onwrite);state.sync=false}function onwriteError(stream,state,sync,er,cb){if(sync)process.nextTick(function(){cb(er)});else cb(er);stream._writableState.errorEmitted=true;stream.emit("error",er)}function onwriteStateUpdate(state){state.writing=false;state.writecb=null;state.length-=state.writelen;state.writelen=0}function onwrite(stream,er){var state=stream._writableState;var sync=state.sync;var cb=state.writecb;onwriteStateUpdate(state);if(er)onwriteError(stream,state,sync,er,cb);else{var finished=needFinish(stream,state);if(!finished&&!state.bufferProcessing&&state.buffer.length)clearBuffer(stream,state);if(sync){process.nextTick(function(){afterWrite(stream,state,finished,cb)})}else{afterWrite(stream,state,finished,cb)}}}function afterWrite(stream,state,finished,cb){if(!finished)onwriteDrain(stream,state);cb();if(finished)finishMaybe(stream,state)}function onwriteDrain(stream,state){if(state.length===0&&state.needDrain){state.needDrain=false;stream.emit("drain")}}function clearBuffer(stream,state){state.bufferProcessing=true;for(var c=0;c<state.buffer.length;c++){var entry=state.buffer[c];var chunk=entry.chunk;var encoding=entry.encoding;var cb=entry.callback;var len=state.objectMode?1:chunk.length;doWrite(stream,state,len,chunk,encoding,cb);if(state.writing){c++;break}}state.bufferProcessing=false;if(c<state.buffer.length)state.buffer=state.buffer.slice(c);else state.buffer.length=0}Writable.prototype._write=function(chunk,encoding,cb){cb(new Error("not implemented"))};Writable.prototype.end=function(chunk,encoding,cb){var state=this._writableState;if(typeof chunk==="function"){cb=chunk;chunk=null;encoding=null}else if(typeof encoding==="function"){cb=encoding;encoding=null}if(typeof chunk!=="undefined"&&chunk!==null)this.write(chunk,encoding);if(!state.ending&&!state.finished)endWritable(this,state,cb)};function needFinish(stream,state){return state.ending&&state.length===0&&!state.finished&&!state.writing}function finishMaybe(stream,state){var need=needFinish(stream,state);if(need){state.finished=true;stream.emit("finish")}return need}function endWritable(stream,state,cb){state.ending=true;finishMaybe(stream,state);if(cb){if(state.finished)process.nextTick(cb);else stream.once("finish",cb)}state.ended=true}}).call(this,require("_process"))},{"./_stream_duplex":132,_process:130,buffer:122,"core-util-is":137,inherits:127,stream:142}],137:[function(require,module,exports){(function(Buffer){function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;function isBuffer(arg){return Buffer.isBuffer(arg)}exports.isBuffer=isBuffer;function objectToString(o){return Object.prototype.toString.call(o)}}).call(this,require("buffer").Buffer)},{buffer:122}],138:[function(require,module,exports){module.exports=require("./lib/_stream_passthrough.js")},{"./lib/_stream_passthrough.js":133}],139:[function(require,module,exports){var Stream=require("stream");exports=module.exports=require("./lib/_stream_readable.js");exports.Stream=Stream;exports.Readable=exports;exports.Writable=require("./lib/_stream_writable.js");exports.Duplex=require("./lib/_stream_duplex.js");exports.Transform=require("./lib/_stream_transform.js");exports.PassThrough=require("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":132,"./lib/_stream_passthrough.js":133,"./lib/_stream_readable.js":134,"./lib/_stream_transform.js":135,"./lib/_stream_writable.js":136,stream:142}],140:[function(require,module,exports){module.exports=require("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":135}],141:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":136}],142:[function(require,module,exports){module.exports=Stream;var EE=require("events").EventEmitter;var inherits=require("inherits");inherits(Stream,EE);Stream.Readable=require("readable-stream/readable.js");Stream.Writable=require("readable-stream/writable.js");Stream.Duplex=require("readable-stream/duplex.js");Stream.Transform=require("readable-stream/transform.js");Stream.PassThrough=require("readable-stream/passthrough.js");Stream.Stream=Stream;function Stream(){EE.call(this)}Stream.prototype.pipe=function(dest,options){var source=this;function ondata(chunk){if(dest.writable){if(false===dest.write(chunk)&&source.pause){source.pause()}}}source.on("data",ondata);function ondrain(){if(source.readable&&source.resume){source.resume()}}dest.on("drain",ondrain);if(!dest._isStdio&&(!options||options.end!==false)){source.on("end",onend);source.on("close",onclose)}var didOnEnd=false;function onend(){if(didOnEnd)return;didOnEnd=true;dest.end()}function onclose(){if(didOnEnd)return;didOnEnd=true;if(typeof dest.destroy==="function")dest.destroy()}function onerror(er){cleanup();if(EE.listenerCount(this,"error")===0){throw er}}source.on("error",onerror);dest.on("error",onerror);function cleanup(){source.removeListener("data",ondata);dest.removeListener("drain",ondrain);source.removeListener("end",onend);source.removeListener("close",onclose);source.removeListener("error",onerror);dest.removeListener("error",onerror);source.removeListener("end",cleanup);source.removeListener("close",cleanup);dest.removeListener("close",cleanup)}source.on("end",cleanup);source.on("close",cleanup);dest.on("close",cleanup);dest.emit("pipe",source);return dest}},{events:126,inherits:127,"readable-stream/duplex.js":131,"readable-stream/passthrough.js":138,"readable-stream/readable.js":139,"readable-stream/transform.js":140,"readable-stream/writable.js":141}],143:[function(require,module,exports){var Buffer=require("buffer").Buffer;var isBufferEncoding=Buffer.isEncoding||function(encoding){switch(encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function assertEncoding(encoding){if(encoding&&!isBufferEncoding(encoding)){throw new Error("Unknown encoding: "+encoding)}}var StringDecoder=exports.StringDecoder=function(encoding){this.encoding=(encoding||"utf8").toLowerCase().replace(/[-_]/,"");assertEncoding(encoding);switch(this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2;this.detectIncompleteChar=utf16DetectIncompleteChar;break;case"base64":this.surrogateSize=3;this.detectIncompleteChar=base64DetectIncompleteChar;break;default:this.write=passThroughWrite;return}this.charBuffer=new Buffer(6);this.charReceived=0;this.charLength=0};StringDecoder.prototype.write=function(buffer){var charStr="";while(this.charLength){var available=buffer.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:buffer.length;buffer.copy(this.charBuffer,this.charReceived,0,available);this.charReceived+=available;if(this.charReceived<this.charLength){return""}buffer=buffer.slice(available,buffer.length);charStr=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var charCode=charStr.charCodeAt(charStr.length-1);if(charCode>=55296&&charCode<=56319){this.charLength+=this.surrogateSize;charStr="";continue}this.charReceived=this.charLength=0;if(buffer.length===0){return charStr}break}this.detectIncompleteChar(buffer);var end=buffer.length;if(this.charLength){buffer.copy(this.charBuffer,0,buffer.length-this.charReceived,end);end-=this.charReceived}charStr+=buffer.toString(this.encoding,0,end);var end=charStr.length-1;var charCode=charStr.charCodeAt(end);if(charCode>=55296&&charCode<=56319){var size=this.surrogateSize;this.charLength+=size;this.charReceived+=size;this.charBuffer.copy(this.charBuffer,size,0,size);buffer.copy(this.charBuffer,0,0,size);return charStr.substring(0,end)}return charStr};StringDecoder.prototype.detectIncompleteChar=function(buffer){var i=buffer.length>=3?3:buffer.length;for(;i>0;i--){var c=buffer[buffer.length-i];if(i==1&&c>>5==6){this.charLength=2;break}if(i<=2&&c>>4==14){this.charLength=3;break}if(i<=3&&c>>3==30){this.charLength=4;break}}this.charReceived=i};StringDecoder.prototype.end=function(buffer){var res="";if(buffer&&buffer.length)res=this.write(buffer);if(this.charReceived){var cr=this.charReceived;var buf=this.charBuffer;var enc=this.encoding;res+=buf.slice(0,cr).toString(enc)}return res};function passThroughWrite(buffer){return buffer.toString(this.encoding)}function utf16DetectIncompleteChar(buffer){this.charReceived=buffer.length%2;this.charLength=this.charReceived?2:0}function base64DetectIncompleteChar(buffer){this.charReceived=buffer.length%3;this.charLength=this.charReceived?3:0}},{buffer:122}],144:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],145:[function(require,module,exports){(function(process,global){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i<arguments.length;i++){objects.push(inspect(arguments[i]))}return objects.join(" ")}var i=1;var args=arguments;var len=args.length;var str=String(f).replace(formatRegExp,function(x){if(x==="%%")return"%";if(i>=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i<len;x=args[++i]){if(isNull(x)||!isObject(x)){str+=" "+x}else{str+=" "+inspect(x)}}return str};exports.deprecate=function(fn,msg){if(isUndefined(global.process)){return function(){return exports.deprecate(fn,msg).apply(this,arguments)}}if(process.noDeprecation===true){return fn}var warned=false;function deprecated(){if(!warned){if(process.throwDeprecation){throw new Error(msg)}else if(process.traceDeprecation){console.trace(msg)}else{console.error(msg)}warned=true}return fn.apply(this,arguments)}return deprecated};var debugs={};var debugEnviron;exports.debuglog=function(set){if(isUndefined(debugEnviron))debugEnviron=process.env.NODE_DEBUG||"";set=set.toUpperCase();if(!debugs[set]){if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else{debugs[set]=function(){}}}return debugs[set]};function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};if(arguments.length>=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i<l;++i){if(hasOwnProperty(value,String(i))){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),true))}else{output.push("")}}keys.forEach(function(key){if(!key.match(/^\d+$/)){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,true))}});return output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]};if(desc.get){if(desc.set){str=ctx.stylize("[Getter/Setter]","special")}else{str=ctx.stylize("[Getter]","special")}}else{if(desc.set){str=ctx.stylize("[Setter]","special")}}if(!hasOwnProperty(visibleKeys,key)){name="["+key+"]"}if(!str){if(ctx.seen.indexOf(desc.value)<0){if(isNull(recurseTimes)){str=formatValue(ctx,desc.value,null)}else{str=formatValue(ctx,desc.value,recurseTimes-1)}if(str.indexOf("\n")>-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":144,_process:130,inherits:127}],146:[function(require,module,exports){"use strict";var escapeStringRegexp=require("escape-string-regexp");var ansiStyles=require("ansi-styles");var stripAnsi=require("strip-ansi");var hasAnsi=require("has-ansi");var supportsColor=require("supports-color");var defineProps=Object.defineProperties;var chalk=module.exports;function build(_styles){var builder=function builder(){return applyStyle.apply(builder,arguments)};builder._styles=_styles;builder.__proto__=proto;return builder}var styles=function(){var ret={};ansiStyles.grey=ansiStyles.gray;Object.keys(ansiStyles).forEach(function(key){ansiStyles[key].closeRe=new RegExp(escapeStringRegexp(ansiStyles[key].close),"g");ret[key]={get:function(){return build(this._styles.concat(key))}}});return ret}();var proto=defineProps(function chalk(){},styles);function applyStyle(){var args=arguments;var argsLen=args.length;var str=argsLen!==0&&String(arguments[0]);if(argsLen>1){for(var a=1;a<argsLen;a++){str+=" "+args[a]}}if(!chalk.enabled||!str){return str}var nestedStyles=this._styles;for(var i=0;i<nestedStyles.length;i++){var code=ansiStyles[nestedStyles[i]];str=code.open+str.replace(code.closeRe,code.open)+code.close}return str}function init(){var ret={};Object.keys(styles).forEach(function(name){ret[name]={get:function(){return build([name])}}});return ret}defineProps(chalk,init());chalk.styles=ansiStyles;chalk.hasColor=hasAnsi;chalk.stripColor=stripAnsi;chalk.supportsColor=supportsColor;if(chalk.enabled===undefined){chalk.enabled=chalk.supportsColor}},{"ansi-styles":147,"escape-string-regexp":148,"has-ansi":149,"strip-ansi":151,"supports-color":153}],147:[function(require,module,exports){"use strict";var styles=module.exports;var codes={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49]};Object.keys(codes).forEach(function(key){var val=codes[key];var style=styles[key]={};style.open="["+val[0]+"m";style.close="["+val[1]+"m"})},{}],148:[function(require,module,exports){"use strict";var matchOperatorsRe=/[|\\{}()[\]^$+*?.]/g;module.exports=function(str){if(typeof str!=="string"){throw new TypeError("Expected a string")}return str.replace(matchOperatorsRe,"\\$&")}},{}],149:[function(require,module,exports){"use strict";var ansiRegex=require("ansi-regex");var re=new RegExp(ansiRegex().source);module.exports=re.test.bind(re)},{"ansi-regex":150}],150:[function(require,module,exports){"use strict";module.exports=function(){return/\u001b\[(?:[0-9]{1,3}(?:;[0-9]{1,3})*)?[m|K]/g}},{}],151:[function(require,module,exports){"use strict";var ansiRegex=require("ansi-regex")();module.exports=function(str){return typeof str==="string"?str.replace(ansiRegex,""):str}},{"ansi-regex":152}],152:[function(require,module,exports){arguments[4][150][0].apply(exports,arguments)},{dup:150}],153:[function(require,module,exports){(function(process){"use strict";module.exports=function(){if(process.argv.indexOf("--no-color")!==-1){return false}if(process.argv.indexOf("--color")!==-1){return true}if(process.stdout&&!process.stdout.isTTY){return false}if(process.platform==="win32"){return true}if("COLORTERM"in process.env){return true}if(process.env.TERM==="dumb"){return false}if(/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)){return true}return false}()}).call(this,require("_process"))},{_process:130}],154:[function(require,module,exports){!function(global,framework,undefined){"use strict";var OBJECT="Object",FUNCTION="Function",ARRAY="Array",STRING="String",NUMBER="Number",REGEXP="RegExp",DATE="Date",MAP="Map",SET="Set",WEAKMAP="WeakMap",WEAKSET="WeakSet",SYMBOL="Symbol",PROMISE="Promise",MATH="Math",ARGUMENTS="Arguments",PROTOTYPE="prototype",CONSTRUCTOR="constructor",TO_STRING="toString",TO_STRING_TAG=TO_STRING+"Tag",TO_LOCALE="toLocaleString",HAS_OWN="hasOwnProperty",FOR_EACH="forEach",ITERATOR="iterator",FF_ITERATOR="@@"+ITERATOR,PROCESS="process",CREATE_ELEMENT="createElement",Function=global[FUNCTION],Object=global[OBJECT],Array=global[ARRAY],String=global[STRING],Number=global[NUMBER],RegExp=global[REGEXP],Date=global[DATE],Map=global[MAP],Set=global[SET],WeakMap=global[WEAKMAP],WeakSet=global[WEAKSET],Symbol=global[SYMBOL],Math=global[MATH],TypeError=global.TypeError,setTimeout=global.setTimeout,setImmediate=global.setImmediate,clearImmediate=global.clearImmediate,process=global[PROCESS],nextTick=process&&process.nextTick,document=global.document,html=document&&document.documentElement,navigator=global.navigator,define=global.define,ArrayProto=Array[PROTOTYPE],ObjectProto=Object[PROTOTYPE],FunctionProto=Function[PROTOTYPE],Infinity=1/0,DOT=".";function isObject(it){return it!=null&&(typeof it=="object"||typeof it=="function")}function isFunction(it){return typeof it=="function"}var isNative=ctx(/./.test,/\[native code\]\s*\}\s*$/,1);var buildIn={Undefined:1,Null:1,Array:1,String:1,Arguments:1,Function:1,Error:1,Boolean:1,Number:1,Date:1,RegExp:1},toString=ObjectProto[TO_STRING];function setToStringTag(it,tag,stat){if(it&&!has(it=stat?it:it[PROTOTYPE],SYMBOL_TAG))hidden(it,SYMBOL_TAG,tag)}function cof(it){return it==undefined?it===undefined?"Undefined":"Null":toString.call(it).slice(8,-1)}function classof(it){var klass=cof(it),tag;return klass==OBJECT&&(tag=it[SYMBOL_TAG])?has(buildIn,tag)?"~"+tag:tag:klass}var call=FunctionProto.call,apply=FunctionProto.apply,REFERENCE_GET;function part(){var fn=assertFunction(this),length=arguments.length,args=Array(length),i=0,_=path._,holder=false;while(length>i)if((args[i]=arguments[i++])===_)holder=true;return function(){var that=this,_length=arguments.length,i=0,j=0,_args;if(!holder&&!_length)return invoke(fn,args,that);_args=args.slice();if(holder)for(;length>i;i++)if(_args[i]===_)_args[i]=arguments[j++];while(_length>j)_args.push(arguments[j++]);return invoke(fn,_args,that)}}function ctx(fn,that,length){assertFunction(fn);if(~length&&that===undefined)return fn;switch(length){case 1:return function(a){return fn.call(that,a)};case 2:return function(a,b){return fn.call(that,a,b)};case 3:return function(a,b,c){return fn.call(that,a,b,c)}}return function(){return fn.apply(that,arguments)}}function invoke(fn,args,that){var un=that===undefined;switch(args.length|0){case 0:return un?fn():fn.call(that);case 1:return un?fn(args[0]):fn.call(that,args[0]);case 2:return un?fn(args[0],args[1]):fn.call(that,args[0],args[1]);case 3:return un?fn(args[0],args[1],args[2]):fn.call(that,args[0],args[1],args[2]);case 4:return un?fn(args[0],args[1],args[2],args[3]):fn.call(that,args[0],args[1],args[2],args[3]);case 5:return un?fn(args[0],args[1],args[2],args[3],args[4]):fn.call(that,args[0],args[1],args[2],args[3],args[4])}return fn.apply(that,args)}function construct(target,argumentsList){var instance=create((arguments.length<3?target:assertFunction(arguments[2]))[PROTOTYPE]),result=apply.call(target,instance,argumentsList);return isObject(result)?result:instance}var create=Object.create,getPrototypeOf=Object.getPrototypeOf,setPrototypeOf=Object.setPrototypeOf,defineProperty=Object.defineProperty,defineProperties=Object.defineProperties,getOwnDescriptor=Object.getOwnPropertyDescriptor,getKeys=Object.keys,getNames=Object.getOwnPropertyNames,getSymbols=Object.getOwnPropertySymbols,has=ctx(call,ObjectProto[HAS_OWN],2),ES5Object=Object,Dict;function toObject(it){return ES5Object(assertDefined(it))}function returnIt(it){return it}function returnThis(){return this}function get(object,key){if(has(object,key))return object[key]}function ownKeys(it){assertObject(it);return getSymbols?getNames(it).concat(getSymbols(it)):getNames(it)}var assign=Object.assign||function(target,source){var T=Object(assertDefined(target)),l=arguments.length,i=1;while(l>i){var S=ES5Object(arguments[i++]),keys=getKeys(S),length=keys.length,j=0,key;while(length>j)T[key=keys[j++]]=S[key]}return T};function keyOf(object,el){var O=toObject(object),keys=getKeys(O),length=keys.length,index=0,key;while(length>index)if(O[key=keys[index++]]===el)return key}function array(it){return String(it).split(",")}var push=ArrayProto.push,unshift=ArrayProto.unshift,slice=ArrayProto.slice,splice=ArrayProto.splice,indexOf=ArrayProto.indexOf,forEach=ArrayProto[FOR_EACH];function createArrayMethod(type){var isMap=type==1,isFilter=type==2,isSome=type==3,isEvery=type==4,isFindIndex=type==6,noholes=type==5||isFindIndex;return function(callbackfn){var O=Object(assertDefined(this)),that=arguments[1],self=ES5Object(O),f=ctx(callbackfn,that,3),length=toLength(self.length),index=0,result=isMap?Array(length):isFilter?[]:undefined,val,res;for(;length>index;index++)if(noholes||index in self){val=self[index];res=f(val,index,O);if(type){if(isMap)result[index]=res;else if(res)switch(type){case 3:return true;case 5:return val;case 6:return index;case 2:result.push(val)}else if(isEvery)return false}}return isFindIndex?-1:isSome||isEvery?isEvery:result}}function createArrayContains(isContains){return function(el){var O=toObject(this),length=toLength(O.length),index=toIndex(arguments[1],length);
if(isContains&&el!=el){for(;length>index;index++)if(sameNaN(O[index]))return isContains||index}else for(;length>index;index++)if(isContains||index in O){if(O[index]===el)return isContains||index}return!isContains&&-1}}function generic(A,B){return typeof A=="function"?A:B}var MAX_SAFE_INTEGER=9007199254740991,ceil=Math.ceil,floor=Math.floor,max=Math.max,min=Math.min,random=Math.random,trunc=Math.trunc||function(it){return(it>0?floor:ceil)(it)};function sameNaN(number){return number!=number}function toInteger(it){return isNaN(it)?0:trunc(it)}function toLength(it){return it>0?min(toInteger(it),MAX_SAFE_INTEGER):0}function toIndex(index,length){var index=toInteger(index);return index<0?max(index+length,0):min(index,length)}function createReplacer(regExp,replace,isStatic){var replacer=isObject(replace)?function(part){return replace[part]}:replace;return function(it){return String(isStatic?it:this).replace(regExp,replacer)}}function createPointAt(toString){return function(pos){var s=String(assertDefined(this)),i=toInteger(pos),l=s.length,a,b;if(i<0||i>=l)return toString?"":undefined;a=s.charCodeAt(i);return a<55296||a>56319||i+1===l||(b=s.charCodeAt(i+1))<56320||b>57343?toString?s.charAt(i):a:toString?s.slice(i,i+2):(a-55296<<10)+(b-56320)+65536}}var REDUCE_ERROR="Reduce of empty object with no initial value";function assert(condition,msg1,msg2){if(!condition)throw TypeError(msg2?msg1+msg2:msg1)}function assertDefined(it){if(it==undefined)throw TypeError("Function called on null or undefined");return it}function assertFunction(it){assert(isFunction(it),it," is not a function!");return it}function assertObject(it){assert(isObject(it),it," is not an object!");return it}function assertInstance(it,Constructor,name){assert(it instanceof Constructor,name,": use the 'new' operator!")}function descriptor(bitmap,value){return{enumerable:!(bitmap&1),configurable:!(bitmap&2),writable:!(bitmap&4),value:value}}function simpleSet(object,key,value){object[key]=value;return object}function createDefiner(bitmap){return DESC?function(object,key,value){return defineProperty(object,key,descriptor(bitmap,value))}:simpleSet}function uid(key){return SYMBOL+"("+key+")_"+(++sid+random())[TO_STRING](36)}function getWellKnownSymbol(name,setter){return Symbol&&Symbol[name]||(setter?Symbol:safeSymbol)(SYMBOL+DOT+name)}var DESC=!!function(){try{return defineProperty({},DOT,ObjectProto)}catch(e){}}(),sid=0,hidden=createDefiner(1),set=Symbol?simpleSet:hidden,safeSymbol=Symbol||uid;function assignHidden(target,src){for(var key in src)hidden(target,key,src[key]);return target}var SYMBOL_UNSCOPABLES=getWellKnownSymbol("unscopables"),ArrayUnscopables=ArrayProto[SYMBOL_UNSCOPABLES]||{},SYMBOL_SPECIES=getWellKnownSymbol("species");function setSpecies(C){if(framework||!isNative(C))defineProperty(C,SYMBOL_SPECIES,{configurable:true,get:returnThis})}var SYMBOL_ITERATOR=getWellKnownSymbol(ITERATOR),SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG),SUPPORT_FF_ITER=FF_ITERATOR in ArrayProto,ITER=safeSymbol("iter"),KEY=1,VALUE=2,Iterators={},IteratorPrototype={},NATIVE_ITERATORS=SYMBOL_ITERATOR in ArrayProto,BUGGY_ITERATORS="keys"in ArrayProto&&!("next"in[].keys());setIterator(IteratorPrototype,returnThis);function setIterator(O,value){hidden(O,SYMBOL_ITERATOR,value);SUPPORT_FF_ITER&&hidden(O,FF_ITERATOR,value)}function createIterator(Constructor,NAME,next,proto){Constructor[PROTOTYPE]=create(proto||IteratorPrototype,{next:descriptor(1,next)});setToStringTag(Constructor,NAME+" Iterator")}function defineIterator(Constructor,NAME,value,DEFAULT){var proto=Constructor[PROTOTYPE],iter=get(proto,SYMBOL_ITERATOR)||get(proto,FF_ITERATOR)||DEFAULT&&get(proto,DEFAULT)||value;if(framework){setIterator(proto,iter);if(iter!==value){var iterProto=getPrototypeOf(iter.call(new Constructor));setToStringTag(iterProto,NAME+" Iterator",true);has(proto,FF_ITERATOR)&&setIterator(iterProto,returnThis)}}Iterators[NAME]=iter;Iterators[NAME+" Iterator"]=returnThis;return iter}function defineStdIterators(Base,NAME,Constructor,next,DEFAULT,IS_SET){function createIter(kind){return function(){return new Constructor(this,kind)}}createIterator(Constructor,NAME,next);var entries=createIter(KEY+VALUE),values=createIter(VALUE);if(DEFAULT==VALUE)values=defineIterator(Base,NAME,values,"values");else entries=defineIterator(Base,NAME,entries,"entries");if(DEFAULT){$define(PROTO+FORCED*BUGGY_ITERATORS,NAME,{entries:entries,keys:IS_SET?values:createIter(KEY),values:values})}}function iterResult(done,value){return{value:value,done:!!done}}function isIterable(it){var O=Object(it),Symbol=global[SYMBOL],hasExt=(Symbol&&Symbol[ITERATOR]||FF_ITERATOR)in O;return hasExt||SYMBOL_ITERATOR in O||has(Iterators,classof(O))}function getIterator(it){var Symbol=global[SYMBOL],ext=it[Symbol&&Symbol[ITERATOR]||FF_ITERATOR],getIter=ext||it[SYMBOL_ITERATOR]||Iterators[classof(it)];return assertObject(getIter.call(it))}function stepCall(fn,value,entries){return entries?invoke(fn,value):fn(value)}function forOf(iterable,entries,fn,that){var iterator=getIterator(iterable),f=ctx(fn,that,entries?2:1),step;while(!(step=iterator.next()).done)if(stepCall(f,step.value,entries)===false)return}var NODE=cof(process)==PROCESS,core={},path=framework?global:core,old=global.core,exportGlobal,FORCED=1,GLOBAL=2,STATIC=4,PROTO=8,BIND=16,WRAP=32;function $define(type,name,source){var key,own,out,exp,isGlobal=type&GLOBAL,target=isGlobal?global:type&STATIC?global[name]:(global[name]||ObjectProto)[PROTOTYPE],exports=isGlobal?core:core[name]||(core[name]={});if(isGlobal)source=name;for(key in source){own=!(type&FORCED)&&target&&key in target&&(!isFunction(target[key])||isNative(target[key]));out=(own?target:source)[key];if(type&BIND&&own)exp=ctx(out,global);else if(type&WRAP&&!framework&&target[key]==out){exp=function(param){return this instanceof out?new out(param):out(param)};exp[PROTOTYPE]=out[PROTOTYPE]}else exp=type&PROTO&&isFunction(out)?ctx(call,out):out;if(exports[key]!=out)hidden(exports,key,exp);if(framework&&target&&!own){if(isGlobal)target[key]=out;else delete target[key]&&hidden(target,key,out)}}}if(typeof module!="undefined"&&module.exports)module.exports=core;else if(isFunction(define)&&define.amd)define(function(){return core});else exportGlobal=true;if(exportGlobal||framework){core.noConflict=function(){global.core=old;return core};global.core=core}$define(GLOBAL+FORCED,{global:global});!function(TAG,SymbolRegistry,AllSymbols,setter){if(!isNative(Symbol)){Symbol=function(description){assert(!(this instanceof Symbol),SYMBOL+" is not a "+CONSTRUCTOR);var tag=uid(description);AllSymbols[tag]=true;DESC&&setter&&defineProperty(ObjectProto,tag,{configurable:true,set:function(value){hidden(this,tag,value)}});return set(create(Symbol[PROTOTYPE]),TAG,tag)};hidden(Symbol[PROTOTYPE],TO_STRING,function(){return this[TAG]})}$define(GLOBAL+WRAP,{Symbol:Symbol});var symbolStatics={"for":function(key){return has(SymbolRegistry,key+="")?SymbolRegistry[key]:SymbolRegistry[key]=Symbol(key)},iterator:SYMBOL_ITERATOR,keyFor:part.call(keyOf,SymbolRegistry),species:SYMBOL_SPECIES,toStringTag:SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG,true),unscopables:SYMBOL_UNSCOPABLES,pure:safeSymbol,set:set,useSetter:function(){setter=true},useSimple:function(){setter=false}};forEach.call(array("hasInstance,isConcatSpreadable,match,replace,search,split,toPrimitive"),function(it){symbolStatics[it]=getWellKnownSymbol(it)});$define(STATIC,SYMBOL,symbolStatics);setToStringTag(Symbol,SYMBOL);$define(STATIC+FORCED*!isNative(Symbol),OBJECT,{getOwnPropertyNames:function(it){var names=getNames(toObject(it)),result=[],key,i=0;while(names.length>i)has(AllSymbols,key=names[i++])||result.push(key);return result},getOwnPropertySymbols:function(it){var names=getNames(toObject(it)),result=[],key,i=0;while(names.length>i)has(AllSymbols,key=names[i++])&&result.push(key);return result}})}(safeSymbol("tag"),{},{},true);!function(RegExpProto,isFinite,tmp,NAME){var RangeError=global.RangeError,isInteger=Number.isInteger||function(it){return!isObject(it)&&isFinite(it)&&floor(it)===it},sign=Math.sign||function sign(x){return(x=+x)==0||x!=x?x:x<0?-1:1},E=Math.E,pow=Math.pow,abs=Math.abs,exp=Math.exp,log=Math.log,sqrt=Math.sqrt,fcc=String.fromCharCode,at=createPointAt(true);var objectStatic={assign:assign,is:function(x,y){return x===y?x!==0||1/x===1/y:x!=x&&y!=y}};"__proto__"in ObjectProto&&function(buggy,set){try{set=ctx(call,getOwnDescriptor(ObjectProto,"__proto__").set,2);set({},ArrayProto)}catch(e){buggy=true}objectStatic.setPrototypeOf=setPrototypeOf=setPrototypeOf||function(O,proto){assertObject(O);assert(proto===null||isObject(proto),proto,": can't set as prototype!");if(buggy)O.__proto__=proto;else set(O,proto);return O}}();$define(STATIC,OBJECT,objectStatic);function asinh(x){return!isFinite(x=+x)||x==0?x:x<0?-asinh(-x):log(x+sqrt(x*x+1))}function expm1(x){return(x=+x)==0?x:x>-1e-6&&x<1e-6?x+x*x/2:exp(x)-1}$define(STATIC,NUMBER,{EPSILON:pow(2,-52),isFinite:function(it){return typeof it=="number"&&isFinite(it)},isInteger:isInteger,isNaN:sameNaN,isSafeInteger:function(number){return isInteger(number)&&abs(number)<=MAX_SAFE_INTEGER},MAX_SAFE_INTEGER:MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:-MAX_SAFE_INTEGER,parseFloat:parseFloat,parseInt:parseInt});$define(STATIC,MATH,{acosh:function(x){return(x=+x)<1?NaN:isFinite(x)?log(x/E+sqrt(x+1)*sqrt(x-1)/E)+1:x},asinh:asinh,atanh:function(x){return(x=+x)==0?x:log((1+x)/(1-x))/2},cbrt:function(x){return sign(x=+x)*pow(abs(x),1/3)},clz32:function(x){return(x>>>=0)?32-x[TO_STRING](2).length:32},cosh:function(x){return(exp(x=+x)+exp(-x))/2},expm1:expm1,fround:function(x){return new Float32Array([x])[0]},hypot:function(value1,value2){var sum=0,len1=arguments.length,len2=len1,args=Array(len1),larg=-Infinity,arg;while(len1--){arg=args[len1]=+arguments[len1];if(arg==Infinity||arg==-Infinity)return Infinity;if(arg>larg)larg=arg}larg=arg||1;while(len2--)sum+=pow(args[len2]/larg,2);return larg*sqrt(sum)},imul:function(x,y){var UInt16=65535,xn=+x,yn=+y,xl=UInt16&xn,yl=UInt16&yn;return 0|xl*yl+((UInt16&xn>>>16)*yl+xl*(UInt16&yn>>>16)<<16>>>0)},log1p:function(x){return(x=+x)>-1e-8&&x<1e-8?x-x*x/2:log(1+x)},log10:function(x){return log(x)/Math.LN10},log2:function(x){return log(x)/Math.LN2},sign:sign,sinh:function(x){return abs(x=+x)<1?(expm1(x)-expm1(-x))/2:(exp(x-1)-exp(-x-1))*(E/2)},tanh:function(x){var a=expm1(x=+x),b=expm1(-x);return a==Infinity?1:b==Infinity?-1:(a-b)/(exp(x)+exp(-x))},trunc:trunc});setToStringTag(Math,MATH,true);function assertNotRegExp(it){if(cof(it)==REGEXP)throw TypeError()}$define(STATIC,STRING,{fromCodePoint:function(x){var res=[],len=arguments.length,i=0,code;while(len>i){code=+arguments[i++];if(toIndex(code,1114111)!==code)throw RangeError(code+" is not a valid code point");res.push(code<65536?fcc(code):fcc(((code-=65536)>>10)+55296,code%1024+56320))}return res.join("")},raw:function(callSite){var raw=toObject(callSite.raw),len=toLength(raw.length),sln=arguments.length,res=[],i=0;while(len>i){res.push(String(raw[i++]));if(i<sln)res.push(String(arguments[i]))}return res.join("")}});$define(PROTO,STRING,{codePointAt:createPointAt(false),endsWith:function(searchString){assertNotRegExp(searchString);var that=String(assertDefined(this)),endPosition=arguments[1],len=toLength(that.length),end=endPosition===undefined?len:min(toLength(endPosition),len);searchString+="";return that.slice(end-searchString.length,end)===searchString},includes:function(searchString){assertNotRegExp(searchString);return!!~String(assertDefined(this)).indexOf(searchString,arguments[1])},repeat:function(count){var str=String(assertDefined(this)),res="",n=toInteger(count);if(0>n||n==Infinity)throw RangeError("Count can't be negative");for(;n>0;(n>>>=1)&&(str+=str))if(n&1)res+=str;return res},startsWith:function(searchString){assertNotRegExp(searchString);var that=String(assertDefined(this)),index=toLength(min(arguments[1],that.length));searchString+="";return that.slice(index,index+searchString.length)===searchString}});defineStdIterators(String,STRING,function(iterated){set(this,ITER,{o:String(iterated),i:0})},function(){var iter=this[ITER],O=iter.o,index=iter.i,point;if(index>=O.length)return iterResult(1);point=at.call(O,index);iter.i+=point.length;return iterResult(0,point)});$define(STATIC,ARRAY,{from:function(arrayLike){var O=Object(assertDefined(arrayLike)),result=new(generic(this,Array)),mapfn=arguments[1],that=arguments[2],mapping=mapfn!==undefined,f=mapping?ctx(mapfn,that,2):undefined,index=0,length;if(isIterable(O))for(var iter=getIterator(O),step;!(step=iter.next()).done;index++){result[index]=mapping?f(step.value,index):step.value}else for(length=toLength(O.length);length>index;index++){result[index]=mapping?f(O[index],index):O[index]}result.length=index;return result},of:function(){var index=0,length=arguments.length,result=new(generic(this,Array))(length);while(length>index)result[index]=arguments[index++];result.length=length;return result}});$define(PROTO,ARRAY,{copyWithin:function(target,start){var O=Object(assertDefined(this)),len=toLength(O.length),to=toIndex(target,len),from=toIndex(start,len),end=arguments[2],fin=end===undefined?len:toIndex(end,len),count=min(fin-from,len-to),inc=1;if(from<to&&to<from+count){inc=-1;from=from+count-1;to=to+count-1}while(count-->0){if(from in O)O[to]=O[from];else delete O[to];to+=inc;from+=inc}return O},fill:function(value){var O=Object(assertDefined(this)),length=toLength(O.length),index=toIndex(arguments[1],length),end=arguments[2],endPos=end===undefined?length:toIndex(end,length);while(endPos>index)O[index++]=value;return O},find:createArrayMethod(5),findIndex:createArrayMethod(6)});defineStdIterators(Array,ARRAY,function(iterated,kind){set(this,ITER,{o:toObject(iterated),i:0,k:kind})},function(){var iter=this[ITER],O=iter.o,kind=iter.k,index=iter.i++;if(!O||index>=O.length)return iter.o=undefined,iterResult(1);if(kind==KEY)return iterResult(0,index);if(kind==VALUE)return iterResult(0,O[index]);return iterResult(0,[index,O[index]])},VALUE);Iterators[ARGUMENTS]=Iterators[ARRAY];setToStringTag(global.JSON,"JSON",true);function wrapObjectMethod(key,MODE){var fn=Object[key],exp=core[OBJECT][key],f=0,o={};if(!exp||isNative(exp)){o[key]=MODE==1?function(it){return isObject(it)?fn(it):it}:MODE==2?function(it){return isObject(it)?fn(it):true}:MODE==3?function(it){return isObject(it)?fn(it):false}:MODE==4?function(it,key){return fn(toObject(it),key)}:function(it){return fn(toObject(it))};try{fn(DOT)}catch(e){f=1}$define(STATIC+FORCED*f,OBJECT,o)}}wrapObjectMethod("freeze",1);wrapObjectMethod("seal",1);wrapObjectMethod("preventExtensions",1);wrapObjectMethod("isFrozen",2);wrapObjectMethod("isSealed",2);wrapObjectMethod("isExtensible",3);wrapObjectMethod("getOwnPropertyDescriptor",4);wrapObjectMethod("getPrototypeOf");wrapObjectMethod("keys");wrapObjectMethod("getOwnPropertyNames");if(framework){tmp[SYMBOL_TAG]=DOT;if(cof(tmp)!=DOT)hidden(ObjectProto,TO_STRING,function(){return"[object "+classof(this)+"]"});NAME in FunctionProto||defineProperty(FunctionProto,NAME,{configurable:true,get:function(){var match=String(this).match(/^\s*function ([^ (]*)/),name=match?match[1]:"";has(this,NAME)||defineProperty(this,NAME,descriptor(5,name));return name},set:function(value){has(this,NAME)||defineProperty(this,NAME,descriptor(0,value))}});if(DESC&&!function(){try{return RegExp(/a/g,"i")=="/a/i"}catch(e){}}()){var _RegExp=RegExp;RegExp=function RegExp(pattern,flags){return new _RegExp(cof(pattern)==REGEXP&&flags!==undefined?pattern.source:pattern,flags)};forEach.call(getNames(_RegExp),function(key){key in RegExp||defineProperty(RegExp,key,{configurable:true,get:function(){return _RegExp[key]},set:function(it){_RegExp[key]=it}})});RegExpProto[CONSTRUCTOR]=RegExp;RegExp[PROTOTYPE]=RegExpProto;hidden(global,REGEXP,RegExp)}if(/./g.flags!="g")defineProperty(RegExpProto,"flags",{configurable:true,get:createReplacer(/^.*\/(\w*)$/,"$1")});forEach.call(array("find,findIndex,fill,copyWithin,entries,keys,values"),function(it){ArrayUnscopables[it]=true});SYMBOL_UNSCOPABLES in ArrayProto||hidden(ArrayProto,SYMBOL_UNSCOPABLES,ArrayUnscopables)}setSpecies(RegExp);setSpecies(Array)}(RegExp[PROTOTYPE],isFinite,{},"name");isFunction(setImmediate)&&isFunction(clearImmediate)||function(ONREADYSTATECHANGE){var postMessage=global.postMessage,addEventListener=global.addEventListener,MessageChannel=global.MessageChannel,counter=0,queue={},defer,channel,port;setImmediate=function(fn){var args=[],i=1;while(arguments.length>i)args.push(arguments[i++]);queue[++counter]=function(){invoke(isFunction(fn)?fn:Function(fn),args)};defer(counter);return counter};clearImmediate=function(id){delete queue[id]};function run(id){if(has(queue,id)){var fn=queue[id];delete queue[id];fn()}}function listner(event){run(event.data)}if(NODE){defer=function(id){nextTick(part.call(run,id))}}else if(addEventListener&&isFunction(postMessage)&&!global.importScripts){defer=function(id){postMessage(id,"*")};addEventListener("message",listner,false)}else if(isFunction(MessageChannel)){channel=new MessageChannel;port=channel.port2;channel.port1.onmessage=listner;defer=ctx(port.postMessage,port,1)}else if(document&&ONREADYSTATECHANGE in document[CREATE_ELEMENT]("script")){defer=function(id){html.appendChild(document[CREATE_ELEMENT]("script"))[ONREADYSTATECHANGE]=function(){html.removeChild(this);run(id)}}}else{defer=function(id){setTimeout(part.call(run,id),0)}}}("onreadystatechange");$define(GLOBAL+BIND,{setImmediate:setImmediate,clearImmediate:clearImmediate});!function(Promise,test){isFunction(Promise)&&isFunction(Promise.resolve)&&Promise.resolve(test=new Promise(function(){}))==test||function(asap,DEF){function isThenable(o){var then;if(isObject(o))then=o.then;return isFunction(then)?then:false}function notify(def){var chain=def.chain;chain.length&&asap(function(){var msg=def.msg,ok=def.state==1,i=0;while(chain.length>i)!function(react){var cb=ok?react.ok:react.fail,ret,then;try{if(cb){ret=cb===true?msg:cb(msg);if(ret===react.P){react.rej(TypeError(PROMISE+"-chain cycle"))}else if(then=isThenable(ret)){then.call(ret,react.res,react.rej)}else react.res(ret)}else react.rej(msg)}catch(err){react.rej(err)}}(chain[i++]);chain.length=0})}function resolve(msg){var def=this,then,wrapper;if(def.done)return;def.done=true;def=def.def||def;try{if(then=isThenable(msg)){wrapper={def:def,done:false};then.call(msg,ctx(resolve,wrapper,1),ctx(reject,wrapper,1))}else{def.msg=msg;def.state=1;notify(def)}}catch(err){reject.call(wrapper||{def:def,done:false},err)}}function reject(msg){var def=this;if(def.done)return;def.done=true;def=def.def||def;def.msg=msg;def.state=2;notify(def)}function getConstructor(C){var S=assertObject(C)[SYMBOL_SPECIES];return S!=undefined?S:C}Promise=function(executor){assertFunction(executor);assertInstance(this,Promise,PROMISE);var def={chain:[],state:0,done:false,msg:undefined};hidden(this,DEF,def);try{executor(ctx(resolve,def,1),ctx(reject,def,1))}catch(err){reject.call(def,err)}};assignHidden(Promise[PROTOTYPE],{then:function(onFulfilled,onRejected){var S=assertObject(assertObject(this)[CONSTRUCTOR])[SYMBOL_SPECIES];var react={ok:isFunction(onFulfilled)?onFulfilled:true,fail:isFunction(onRejected)?onRejected:false},P=react.P=new(S!=undefined?S:Promise)(function(resolve,reject){react.res=assertFunction(resolve);react.rej=assertFunction(reject)}),def=this[DEF];def.chain.push(react);def.state&¬ify(def);return P},"catch":function(onRejected){return this.then(undefined,onRejected)}});assignHidden(Promise,{all:function(iterable){var Promise=getConstructor(this),values=[];return new Promise(function(resolve,reject){forOf(iterable,false,push,values);var remaining=values.length,results=Array(remaining);if(remaining)forEach.call(values,function(promise,index){Promise.resolve(promise).then(function(value){results[index]=value;--remaining||resolve(results)},reject)});else resolve(results)})},race:function(iterable){var Promise=getConstructor(this);return new Promise(function(resolve,reject){forOf(iterable,false,function(promise){Promise.resolve(promise).then(resolve,reject)})})},reject:function(r){return new(getConstructor(this))(function(resolve,reject){reject(r)})},resolve:function(x){return isObject(x)&&DEF in x&&getPrototypeOf(x)===this[PROTOTYPE]?x:new(getConstructor(this))(function(resolve,reject){resolve(x)})}})}(nextTick||setImmediate,safeSymbol("def"));setToStringTag(Promise,PROMISE);setSpecies(Promise);$define(GLOBAL+FORCED*!isNative(Promise),{Promise:Promise})}(global[PROMISE]);!function(){var UID=safeSymbol("uid"),DATA=safeSymbol("data"),WEAK=safeSymbol("weak"),LAST=safeSymbol("last"),FIRST=safeSymbol("first"),SIZE=DESC?safeSymbol("size"):"size",uid=0;function getCollection(C,NAME,methods,commonMethods,isMap,isWeak){var ADDER=isMap?"set":"add",proto=C&&C[PROTOTYPE],O={};function initFromIterable(that,iterable){if(iterable!=undefined)forOf(iterable,isMap,that[ADDER],that);return that}function fixSVZ(key,chain){var method=proto[key];framework&&hidden(proto,key,function(a,b){var result=method.call(this,a===0?0:a,b);return chain?this:result})}if(!isNative(C)||!(isWeak||!BUGGY_ITERATORS&&has(proto,"entries"))){C=isWeak?function(iterable){assertInstance(this,C,NAME);set(this,UID,uid++);initFromIterable(this,iterable)}:function(iterable){var that=this;assertInstance(that,C,NAME);set(that,DATA,create(null));set(that,SIZE,0);set(that,LAST,undefined);set(that,FIRST,undefined);initFromIterable(that,iterable)};assignHidden(assignHidden(C[PROTOTYPE],methods),commonMethods);isWeak||defineProperty(C[PROTOTYPE],"size",{get:function(){return assertDefined(this[SIZE])}})}else{var Native=C,inst=new C,chain=inst[ADDER](isWeak?{}:-0,1),buggyZero;if(!NATIVE_ITERATORS||!C.length){C=function(iterable){assertInstance(this,C,NAME);return initFromIterable(new Native,iterable)};C[PROTOTYPE]=proto}isWeak||inst[FOR_EACH](function(val,key){buggyZero=1/key===-Infinity});if(buggyZero){fixSVZ("delete");fixSVZ("has");isMap&&fixSVZ("get")}if(buggyZero||chain!==inst)fixSVZ(ADDER,true)}setToStringTag(C,NAME);setSpecies(C);O[NAME]=C;$define(GLOBAL+WRAP+FORCED*!isNative(C),O);isWeak||defineStdIterators(C,NAME,function(iterated,kind){set(this,ITER,{o:iterated,k:kind})},function(){var iter=this[ITER],O=iter.o,kind=iter.k,entry=iter.l;while(entry&&entry.r)entry=entry.p;if(!O||!(iter.l=entry=entry?entry.n:O[FIRST]))return iter.o=undefined,iterResult(1);if(kind==KEY)return iterResult(0,entry.k);if(kind==VALUE)return iterResult(0,entry.v);return iterResult(0,[entry.k,entry.v])},isMap?KEY+VALUE:VALUE,!isMap);return C}function fastKey(it,create){if(!isObject(it))return(typeof it=="string"?"S":"P")+it;if(!has(it,UID)){if(create)hidden(it,UID,++uid);else return""}return"O"+it[UID]}function def(that,key,value){var index=fastKey(key,true),data=that[DATA],last=that[LAST],entry;if(index in data)data[index].v=value;else{entry=data[index]={k:key,v:value,p:last};if(!that[FIRST])that[FIRST]=entry;if(last)last.n=entry;that[LAST]=entry;that[SIZE]++}return that}function del(that,index){var data=that[DATA],entry=data[index],next=entry.n,prev=entry.p;delete data[index];entry.r=true;if(prev)prev.n=next;if(next)next.p=prev;if(that[FIRST]==entry)that[FIRST]=next;if(that[LAST]==entry)that[LAST]=prev;that[SIZE]--}var collectionMethods={clear:function(){for(var index in this[DATA])del(this,index)},"delete":function(key){var index=fastKey(key),contains=index in this[DATA];if(contains)del(this,index);return contains},forEach:function(callbackfn){var f=ctx(callbackfn,arguments[1],3),entry;while(entry=entry?entry.n:this[FIRST]){f(entry.v,entry.k,this);while(entry&&entry.r)entry=entry.p}},has:function(key){return fastKey(key)in this[DATA]}};Map=getCollection(Map,MAP,{get:function(key){var entry=this[DATA][fastKey(key)];return entry&&entry.v},set:function(key,value){return def(this,key===0?0:key,value)}},collectionMethods,true);Set=getCollection(Set,SET,{add:function(value){return def(this,value=value===0?0:value,value)}},collectionMethods);function setWeak(that,key,value){has(assertObject(key),WEAK)||hidden(key,WEAK,{});key[WEAK][that[UID]]=value;return that}function hasWeak(key){return isObject(key)&&has(key,WEAK)&&has(key[WEAK],this[UID])}var weakMethods={"delete":function(key){return hasWeak.call(this,key)&&delete key[WEAK][this[UID]]},has:hasWeak};WeakMap=getCollection(WeakMap,WEAKMAP,{get:function(key){if(isObject(key)&&has(key,WEAK))return key[WEAK][this[UID]]},set:function(key,value){return setWeak(this,key,value)}},weakMethods,true,true);WeakSet=getCollection(WeakSet,WEAKSET,{add:function(value){return setWeak(this,value,true)}},weakMethods,false,true)}();!function(){function Enumerate(iterated){var keys=[],key;for(key in iterated)keys.push(key);set(this,ITER,{o:iterated,a:keys,i:0})}createIterator(Enumerate,OBJECT,function(){var iter=this[ITER],keys=iter.a,key;do{if(iter.i>=keys.length)return iterResult(1)}while(!((key=keys[iter.i++])in iter.o));return iterResult(0,key)});function wrap(fn){return function(it){assertObject(it);try{return fn.apply(undefined,arguments),true}catch(e){return false}}}function reflectGet(target,propertyKey){var receiver=arguments.length<3?target:arguments[2],desc=getOwnDescriptor(assertObject(target),propertyKey),proto;if(desc)return desc.get?desc.get.call(receiver):desc.value;return isObject(proto=getPrototypeOf(target))?reflectGet(proto,propertyKey,receiver):undefined}function reflectSet(target,propertyKey,V){var receiver=arguments.length<4?target:arguments[3],desc=getOwnDescriptor(assertObject(target),propertyKey),proto;if(desc){if(desc.writable===false)return false;if(desc.set)return desc.set.call(receiver,V),true}if(isObject(proto=getPrototypeOf(target)))return reflectSet(proto,propertyKey,V,receiver);desc=getOwnDescriptor(receiver,propertyKey)||descriptor(0);desc.value=V;return defineProperty(receiver,propertyKey,desc),true}var isExtensible=Object.isExtensible||returnIt;var reflect={apply:ctx(call,apply,3),construct:construct,defineProperty:wrap(defineProperty),deleteProperty:function(target,propertyKey){var desc=getOwnDescriptor(assertObject(target),propertyKey);return desc&&!desc.configurable?false:delete target[propertyKey]},enumerate:function(target){return new Enumerate(assertObject(target))},get:reflectGet,getOwnPropertyDescriptor:function(target,propertyKey){return getOwnDescriptor(assertObject(target),propertyKey)},getPrototypeOf:function(target){return getPrototypeOf(assertObject(target))},has:function(target,propertyKey){return propertyKey in target},isExtensible:function(target){return!!isExtensible(assertObject(target))},ownKeys:ownKeys,preventExtensions:wrap(Object.preventExtensions||returnIt),set:reflectSet};if(setPrototypeOf)reflect.setPrototypeOf=function(target,proto){return setPrototypeOf(assertObject(target),proto),true};$define(GLOBAL,{Reflect:{}});$define(STATIC,"Reflect",reflect)}();!function(){$define(PROTO,ARRAY,{includes:createArrayContains(true)});$define(PROTO,STRING,{at:createPointAt(true)});function createObjectToArray(isEntries){return function(object){var O=toObject(object),keys=getKeys(object),length=keys.length,i=0,result=Array(length),key;if(isEntries)while(length>i)result[i]=[key=keys[i++],O[key]];else while(length>i)result[i]=O[keys[i++]];return result}}$define(STATIC,OBJECT,{values:createObjectToArray(false),entries:createObjectToArray(true)});$define(STATIC,REGEXP,{escape:createReplacer(/([\\\-[\]{}()*+?.,^$|])/g,"\\$1",true)})}();!function(REFERENCE){REFERENCE_GET=getWellKnownSymbol(REFERENCE+"Get",true);var REFERENCE_SET=getWellKnownSymbol(REFERENCE+SET,true),REFERENCE_DELETE=getWellKnownSymbol(REFERENCE+"Delete",true);$define(STATIC,SYMBOL,{referenceGet:REFERENCE_GET,referenceSet:REFERENCE_SET,referenceDelete:REFERENCE_DELETE});hidden(FunctionProto,REFERENCE_GET,returnThis);function setMapMethods(Constructor){if(Constructor){var MapProto=Constructor[PROTOTYPE];hidden(MapProto,REFERENCE_GET,MapProto.get);hidden(MapProto,REFERENCE_SET,MapProto.set);hidden(MapProto,REFERENCE_DELETE,MapProto["delete"])}}setMapMethods(Map);setMapMethods(WeakMap)}("reference");!function(NodeList){if(framework&&NodeList&&!(SYMBOL_ITERATOR in NodeList[PROTOTYPE])){hidden(NodeList[PROTOTYPE],SYMBOL_ITERATOR,Iterators[ARRAY])}Iterators.NodeList=Iterators[ARRAY]}(global.NodeList);!function(DICT){Dict=function(iterable){var dict=create(null);if(iterable!=undefined){if(isIterable(iterable)){for(var iter=getIterator(iterable),step,value;!(step=iter.next()).done;){value=step.value;dict[value[0]]=value[1]}}else assign(dict,iterable)}return dict};Dict[PROTOTYPE]=null;function DictIterator(iterated,kind){set(this,ITER,{o:toObject(iterated),a:getKeys(iterated),i:0,k:kind})}createIterator(DictIterator,DICT,function(){var iter=this[ITER],O=iter.o,keys=iter.a,kind=iter.k,key;do{if(iter.i>=keys.length)return iterResult(1)}while(!has(O,key=keys[iter.i++]));if(kind==KEY)return iterResult(0,key);if(kind==VALUE)return iterResult(0,O[key]);return iterResult(0,[key,O[key]])});function createDictIter(kind){return function(it){return new DictIterator(it,kind)}}function createDictMethod(type){var isMap=type==1,isEvery=type==4;return function(object,callbackfn,that){var f=ctx(callbackfn,that,3),O=toObject(object),result=isMap||type==7||type==2?new(generic(this,Dict)):undefined,key,val,res;for(key in O)if(has(O,key)){val=O[key];res=f(val,key,object);if(type){if(isMap)result[key]=res;else if(res)switch(type){case 2:result[key]=val;break;case 3:return true;case 5:return val;case 6:return key;case 7:result[res[0]]=res[1]}else if(isEvery)return false}}return type==3||isEvery?isEvery:result}}function createDictReduce(isTurn){return function(object,mapfn,init){assertFunction(mapfn);var O=toObject(object),keys=getKeys(O),length=keys.length,i=0,memo,key,result;if(isTurn)memo=init==undefined?new(generic(this,Dict)):Object(init);else if(arguments.length<3){assert(length,REDUCE_ERROR);memo=O[keys[i++]]}else memo=Object(init);while(length>i)if(has(O,key=keys[i++])){result=mapfn(memo,O[key],key,object);if(isTurn){if(result===false)break}else memo=result}return memo}}var findKey=createDictMethod(6);function includes(object,el){return(el==el?keyOf(object,el):findKey(object,sameNaN))!==undefined}var dictMethods={keys:createDictIter(KEY),values:createDictIter(VALUE),entries:createDictIter(KEY+VALUE),forEach:createDictMethod(0),map:createDictMethod(1),filter:createDictMethod(2),some:createDictMethod(3),every:createDictMethod(4),find:createDictMethod(5),findKey:findKey,mapPairs:createDictMethod(7),reduce:createDictReduce(false),turn:createDictReduce(true),keyOf:keyOf,includes:includes,has:has,get:get,set:createDefiner(0),isDict:function(it){return isObject(it)&&getPrototypeOf(it)===Dict[PROTOTYPE]}};if(REFERENCE_GET)for(var key in dictMethods)!function(fn){function method(){for(var args=[this],i=0;i<arguments.length;)args.push(arguments[i++]);return invoke(fn,args)}fn[REFERENCE_GET]=function(){return method}}(dictMethods[key]);$define(GLOBAL+FORCED,{Dict:assignHidden(Dict,dictMethods)})}("Dict");!function(ENTRIES,FN){function $for(iterable,entries){if(!(this instanceof $for))return new $for(iterable,entries);this[ITER]=getIterator(iterable);this[ENTRIES]=!!entries}createIterator($for,"Wrapper",function(){return this[ITER].next()});var $forProto=$for[PROTOTYPE];setIterator($forProto,function(){return this[ITER]});function createChainIterator(next){function Iter(I,fn,that){this[ITER]=getIterator(I);this[ENTRIES]=I[ENTRIES];this[FN]=ctx(fn,that,I[ENTRIES]?2:1)}createIterator(Iter,"Chain",next,$forProto);setIterator(Iter[PROTOTYPE],returnThis);return Iter}var MapIter=createChainIterator(function(){var step=this[ITER].next();return step.done?step:iterResult(0,stepCall(this[FN],step.value,this[ENTRIES]))});var FilterIter=createChainIterator(function(){for(;;){var step=this[ITER].next();if(step.done||stepCall(this[FN],step.value,this[ENTRIES]))return step}});assignHidden($forProto,{of:function(fn,that){forOf(this,this[ENTRIES],fn,that)},array:function(fn,that){var result=[];forOf(fn!=undefined?this.map(fn,that):this,false,push,result);
return result},filter:function(fn,that){return new FilterIter(this,fn,that)},map:function(fn,that){return new MapIter(this,fn,that)}});$for.isIterable=isIterable;$for.getIterator=getIterator;$define(GLOBAL+FORCED,{$for:$for})}("entries",safeSymbol("fn"));!function(_,toLocaleString){core._=path._=path._||{};$define(PROTO+FORCED,FUNCTION,{part:part,only:function(numberArguments,that){var fn=assertFunction(this),n=toLength(numberArguments),isThat=arguments.length>1;return function(){var length=min(n,arguments.length),args=Array(length),i=0;while(length>i)args[i]=arguments[i++];return invoke(fn,args,isThat?that:this)}}});function tie(key){var that=this,bound={};return hidden(that,_,function(key){if(key===undefined||!(key in that))return toLocaleString.call(that);return has(bound,key)?bound[key]:bound[key]=ctx(that[key],that,-1)})[_](key)}hidden(path._,TO_STRING,function(){return _});hidden(ObjectProto,_,tie);DESC||hidden(ArrayProto,_,tie)}(DESC?uid("tie"):TO_LOCALE,ObjectProto[TO_LOCALE]);!function(){function define(target,mixin){var keys=ownKeys(toObject(mixin)),length=keys.length,i=0,key;while(length>i)defineProperty(target,key=keys[i++],getOwnDescriptor(mixin,key));return target}$define(STATIC+FORCED,OBJECT,{isObject:isObject,classof:classof,define:define,make:function(proto,mixin){return define(create(proto),mixin)}})}();$define(PROTO+FORCED,ARRAY,{turn:function(fn,target){assertFunction(fn);var memo=target==undefined?[]:Object(target),O=ES5Object(this),length=toLength(O.length),index=0;while(length>index)if(fn(memo,O[index],index++,this)===false)break;return memo}});if(framework)ArrayUnscopables.turn=true;!function(arrayStatics){function setArrayStatics(keys,length){forEach.call(array(keys),function(key){if(key in ArrayProto)arrayStatics[key]=ctx(call,ArrayProto[key],length)})}setArrayStatics("pop,reverse,shift,keys,values,entries",1);setArrayStatics("indexOf,every,some,forEach,map,filter,find,findIndex,includes",3);setArrayStatics("join,slice,concat,push,splice,unshift,sort,lastIndexOf,"+"reduce,reduceRight,copyWithin,fill,turn");$define(STATIC,ARRAY,arrayStatics)}({});!function(numberMethods){function NumberIterator(iterated){set(this,ITER,{l:toLength(iterated),i:0})}createIterator(NumberIterator,NUMBER,function(){var iter=this[ITER],i=iter.i++;return i<iter.l?iterResult(0,i):iterResult(1)});defineIterator(Number,NUMBER,function(){return new NumberIterator(this)});numberMethods.random=function(lim){var a=+this,b=lim==undefined?0:+lim,m=min(a,b);return random()*(max(a,b)-m)+m};forEach.call(array("round,floor,ceil,abs,sin,asin,cos,acos,tan,atan,exp,sqrt,max,min,pow,atan2,"+"acosh,asinh,atanh,cbrt,clz32,cosh,expm1,hypot,imul,log1p,log10,log2,sign,sinh,tanh,trunc"),function(key){var fn=Math[key];if(fn)numberMethods[key]=function(){var args=[+this],i=0;while(arguments.length>i)args.push(arguments[i++]);return invoke(fn,args)}});$define(PROTO+FORCED,NUMBER,numberMethods)}({});!function(){var escapeHTMLDict={"&":"&","<":"<",">":">",'"':""","'":"'"},unescapeHTMLDict={},key;for(key in escapeHTMLDict)unescapeHTMLDict[escapeHTMLDict[key]]=key;$define(PROTO+FORCED,STRING,{escapeHTML:createReplacer(/[&<>"']/g,escapeHTMLDict),unescapeHTML:createReplacer(/&(?:amp|lt|gt|quot|apos);/g,unescapeHTMLDict)})}();!function(formatRegExp,flexioRegExp,locales,current,SECONDS,MINUTES,HOURS,MONTH,YEAR){function createFormat(prefix){return function(template,locale){var that=this,dict=locales[has(locales,locale)?locale:current];function get(unit){return that[prefix+unit]()}return String(template).replace(formatRegExp,function(part){switch(part){case"s":return get(SECONDS);case"ss":return lz(get(SECONDS));case"m":return get(MINUTES);case"mm":return lz(get(MINUTES));case"h":return get(HOURS);case"hh":return lz(get(HOURS));case"D":return get(DATE);case"DD":return lz(get(DATE));case"W":return dict[0][get("Day")];case"N":return get(MONTH)+1;case"NN":return lz(get(MONTH)+1);case"M":return dict[2][get(MONTH)];case"MM":return dict[1][get(MONTH)];case"Y":return get(YEAR);case"YY":return lz(get(YEAR)%100)}return part})}}function lz(num){return num>9?num:"0"+num}function addLocale(lang,locale){function split(index){var result=[];forEach.call(array(locale.months),function(it){result.push(it.replace(flexioRegExp,"$"+index))});return result}locales[lang]=[array(locale.weekdays),split(1),split(2)];return core}$define(PROTO+FORCED,DATE,{format:createFormat("get"),formatUTC:createFormat("getUTC")});addLocale(current,{weekdays:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday",months:"January,February,March,April,May,June,July,August,September,October,November,December"});addLocale("ru",{weekdays:"Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота",months:"Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,"+"Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь"});core.locale=function(locale){return has(locales,locale)?current=locale:current};core.addLocale=addLocale}(/\b\w\w?\b/g,/:(.*)\|(.*)$/,{},"en","Seconds","Minutes","Hours","Month","FullYear")}(typeof self!="undefined"&&self.Math===Math?self:Function("return this")(),false)},{}],155:[function(require,module,exports){"use strict";var repeating=require("repeating");var INDENT_RE=/^(?:( )+|\t+)/;function getMostUsed(indents){var result=0;var maxUsed=0;var maxWeight=0;for(var n in indents){var indent=indents[n];var u=indent[0];var w=indent[1];if(u>maxUsed||u===maxUsed&&w>maxWeight){maxUsed=u;maxWeight=w;result=+n}}return result}module.exports=function(str){if(typeof str!=="string"){throw new TypeError("Expected a string")}var tabs=0;var spaces=0;var prev=0;var indents={};var current;var isIndent;str.split(/\n/g).forEach(function(line){if(!line){return}var indent;var matches=line.match(INDENT_RE);if(!matches){indent=0}else{indent=matches[0].length;if(matches[1]){spaces++}else{tabs++}}var diff=indent-prev;prev=indent;if(diff){isIndent=diff>0;current=indents[isIndent?diff:-diff];if(current){current[0]++}else{current=indents[diff]=[1,0]}}else if(current){current[1]+=+isIndent}});var amount=getMostUsed(indents);var type;var actual;if(!amount){type=null;actual=""}else if(spaces>=tabs){type="space";actual=repeating(" ",amount)}else{type="tab";actual=repeating(" ",amount)}return{amount:amount,type:type,indent:actual}}},{repeating:156}],156:[function(require,module,exports){"use strict";var isFinite=require("is-finite");module.exports=function(str,n){if(typeof str!=="string"){throw new TypeError("Expected a string as the first argument")}if(n<0||!isFinite(n)){throw new TypeError("Expected a finite positive number")}var ret="";do{if(n&1){ret+=str}str+=str}while(n=n>>1);return ret}},{"is-finite":157}],157:[function(require,module,exports){"use strict";module.exports=Number.isFinite||function(val){if(typeof val!=="number"||val!==val||val===Infinity||val===-Infinity){return false}return true}},{}],158:[function(require,module,exports){(function(root,factory){"use strict";if(typeof define==="function"&&define.amd){define(["exports"],factory)}else if(typeof exports!=="undefined"){factory(exports)}else{factory(root.estraverse={})}})(this,function clone(exports){"use strict";var Syntax,isArray,VisitorOption,VisitorKeys,objectCreate,objectKeys,BREAK,SKIP,REMOVE;function ignoreJSHintError(){}isArray=Array.isArray;if(!isArray){isArray=function isArray(array){return Object.prototype.toString.call(array)==="[object Array]"}}function deepCopy(obj){var ret={},key,val;for(key in obj){if(obj.hasOwnProperty(key)){val=obj[key];if(typeof val==="object"&&val!==null){ret[key]=deepCopy(val)}else{ret[key]=val}}}return ret}function shallowCopy(obj){var ret={},key;for(key in obj){if(obj.hasOwnProperty(key)){ret[key]=obj[key]}}return ret}ignoreJSHintError(shallowCopy);function upperBound(array,func){var diff,len,i,current;len=array.length;i=0;while(len){diff=len>>>1;current=i+diff;if(func(array[current])){len=diff}else{i=current+1;len-=diff+1}}return i}function lowerBound(array,func){var diff,len,i,current;len=array.length;i=0;while(len){diff=len>>>1;current=i+diff;if(func(array[current])){i=current+1;len-=diff+1}else{len=diff}}return i}ignoreJSHintError(lowerBound);objectCreate=Object.create||function(){function F(){}return function(o){F.prototype=o;return new F}}();objectKeys=Object.keys||function(o){var keys=[],key;for(key in o){keys.push(key)}return keys};function extend(to,from){objectKeys(from).forEach(function(key){to[key]=from[key]});return to}Syntax={AssignmentExpression:"AssignmentExpression",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",AwaitExpression:"AwaitExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportBatchSpecifier:"ExportBatchSpecifier",ExportDeclaration:"ExportDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",Program:"Program",Property:"Property",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"};VisitorKeys={AssignmentExpression:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],AwaitExpression:["argument"],BlockStatement:["body"],BinaryExpression:["left","right"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ComprehensionBlock:["left","right"],ComprehensionExpression:["blocks","filter","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],ForStatement:["init","test","update","body"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],GeneratorExpression:["blocks","filter","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportDeclaration:["specifiers","source"],ImportDefaultSpecifier:["id"],ImportNamespaceSpecifier:["id"],ImportSpecifier:["id","name"],Literal:[],LabeledStatement:["label","body"],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],ModuleSpecifier:[],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],Program:["body"],Property:["key","value"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SwitchStatement:["discriminant","cases"],SwitchCase:["test","consequent"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"]};BREAK={};SKIP={};REMOVE={};VisitorOption={Break:BREAK,Skip:SKIP,Remove:REMOVE};function Reference(parent,key){this.parent=parent;this.key=key}Reference.prototype.replace=function replace(node){this.parent[this.key]=node};Reference.prototype.remove=function remove(){if(isArray(this.parent)){this.parent.splice(this.key,1);return true}else{this.replace(null);return false}};function Element(node,path,wrap,ref){this.node=node;this.path=path;this.wrap=wrap;this.ref=ref}function Controller(){}Controller.prototype.path=function path(){var i,iz,j,jz,result,element;function addToPath(result,path){if(isArray(path)){for(j=0,jz=path.length;j<jz;++j){result.push(path[j])}}else{result.push(path)}}if(!this.__current.path){return null}result=[];for(i=2,iz=this.__leavelist.length;i<iz;++i){element=this.__leavelist[i];addToPath(result,element.path)}addToPath(result,this.__current.path);return result};Controller.prototype.type=function(){var node=this.current();return node.type||this.__current.wrap};Controller.prototype.parents=function parents(){var i,iz,result;result=[];for(i=1,iz=this.__leavelist.length;i<iz;++i){result.push(this.__leavelist[i].node)}return result};Controller.prototype.current=function current(){return this.__current.node};Controller.prototype.__execute=function __execute(callback,element){var previous,result;result=undefined;previous=this.__current;this.__current=element;this.__state=null;if(callback){result=callback.call(this,element.node,this.__leavelist[this.__leavelist.length-1].node)}this.__current=previous;return result};Controller.prototype.notify=function notify(flag){this.__state=flag};Controller.prototype.skip=function(){this.notify(SKIP)};Controller.prototype["break"]=function(){this.notify(BREAK)};Controller.prototype.remove=function(){this.notify(REMOVE)};Controller.prototype.__initialize=function(root,visitor){this.visitor=visitor;this.root=root;this.__worklist=[];this.__leavelist=[];this.__current=null;this.__state=null;this.__fallback=visitor.fallback==="iteration";this.__keys=VisitorKeys;if(visitor.keys){this.__keys=extend(objectCreate(this.__keys),visitor.keys)}};function isNode(node){if(node==null){return false}return typeof node==="object"&&typeof node.type==="string"}function isProperty(nodeType,key){return(nodeType===Syntax.ObjectExpression||nodeType===Syntax.ObjectPattern)&&"properties"===key}Controller.prototype.traverse=function traverse(root,visitor){var worklist,leavelist,element,node,nodeType,ret,key,current,current2,candidates,candidate,sentinel;this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;worklist.push(new Element(root,null,null,null));leavelist.push(new Element(null,null,null,null));while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();ret=this.__execute(visitor.leave,element);if(this.__state===BREAK||ret===BREAK){return}continue}if(element.node){ret=this.__execute(visitor.enter,element);if(this.__state===BREAK||ret===BREAK){return}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||ret===SKIP){continue}node=element.node;nodeType=element.wrap||node.type;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=objectKeys(node)}else{throw new Error("Unknown node type "+nodeType+".")}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],"Property",null)}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,null)}else{continue}worklist.push(element)}}else if(isNode(candidate)){worklist.push(new Element(candidate,key,null,null))}}}}};Controller.prototype.replace=function replace(root,visitor){function removeElem(element){var i,key,nextElem,parent;if(element.ref.remove()){key=element.ref.key;parent=element.ref.parent;i=worklist.length;while(i--){nextElem=worklist[i];if(nextElem.ref&&nextElem.ref.parent===parent){if(nextElem.ref.key<key){break}--nextElem.ref.key}}}}var worklist,leavelist,node,nodeType,target,element,current,current2,candidates,candidate,sentinel,outer,key;this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;outer={root:root};element=new Element(root,null,null,new Reference(outer,"root"));worklist.push(element);leavelist.push(element);while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();target=this.__execute(visitor.leave,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target)}if(this.__state===REMOVE||target===REMOVE){removeElem(element)}if(this.__state===BREAK||target===BREAK){return outer.root}continue}target=this.__execute(visitor.enter,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target);element.node=target}if(this.__state===REMOVE||target===REMOVE){removeElem(element);element.node=null}if(this.__state===BREAK||target===BREAK){return outer.root}node=element.node;if(!node){continue}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||target===SKIP){continue}nodeType=element.wrap||node.type;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=objectKeys(node)}else{throw new Error("Unknown node type "+nodeType+".")}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],"Property",new Reference(candidate,current2))}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,new Reference(candidate,current2))}else{continue}worklist.push(element)}}else if(isNode(candidate)){worklist.push(new Element(candidate,key,null,new Reference(node,key)))}}}return outer.root};function traverse(root,visitor){var controller=new Controller;return controller.traverse(root,visitor)}function replace(root,visitor){var controller=new Controller;return controller.replace(root,visitor)}function extendCommentRange(comment,tokens){var target;target=upperBound(tokens,function search(token){return token.range[0]>comment.range[0]});comment.extendedRange=[comment.range[0],comment.range[1]];if(target!==tokens.length){comment.extendedRange[1]=tokens[target].range[0]}target-=1;if(target>=0){comment.extendedRange[0]=tokens[target].range[1]}return comment}function attachComments(tree,providedComments,tokens){var comments=[],comment,len,i,cursor;if(!tree.range){throw new Error("attachComments needs range information")}if(!tokens.length){if(providedComments.length){for(i=0,len=providedComments.length;i<len;i+=1){comment=deepCopy(providedComments[i]);comment.extendedRange=[0,tree.range[0]];comments.push(comment)}tree.leadingComments=comments}return tree}for(i=0,len=providedComments.length;i<len;i+=1){comments.push(extendCommentRange(deepCopy(providedComments[i]),tokens))}cursor=0;traverse(tree,{enter:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(comment.extendedRange[1]>node.range[0]){break}if(comment.extendedRange[1]===node.range[0]){if(!node.leadingComments){node.leadingComments=[]}node.leadingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});cursor=0;traverse(tree,{leave:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(node.range[1]<comment.extendedRange[0]){break}if(node.range[1]===comment.extendedRange[0]){if(!node.trailingComments){node.trailingComments=[]}node.trailingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});return tree}exports.version="1.8.1-dev";exports.Syntax=Syntax;exports.traverse=traverse;exports.replace=replace;exports.attachComments=attachComments;exports.VisitorKeys=VisitorKeys;exports.VisitorOption=VisitorOption;exports.Controller=Controller;exports.cloneEnvironment=function(){return clone({})};return exports})},{}],159:[function(require,module,exports){(function(){"use strict";function isExpression(node){if(node==null){return false}switch(node.type){case"ArrayExpression":case"AssignmentExpression":case"BinaryExpression":case"CallExpression":case"ConditionalExpression":case"FunctionExpression":case"Identifier":case"Literal":case"LogicalExpression":case"MemberExpression":case"NewExpression":case"ObjectExpression":case"SequenceExpression":case"ThisExpression":case"UnaryExpression":case"UpdateExpression":return true}return false}function isIterationStatement(node){if(node==null){return false}switch(node.type){case"DoWhileStatement":case"ForInStatement":case"ForStatement":case"WhileStatement":return true}return false}function isStatement(node){if(node==null){return false}switch(node.type){case"BlockStatement":case"BreakStatement":case"ContinueStatement":case"DebuggerStatement":case"DoWhileStatement":case"EmptyStatement":case"ExpressionStatement":case"ForInStatement":case"ForStatement":case"IfStatement":case"LabeledStatement":case"ReturnStatement":case"SwitchStatement":case"ThrowStatement":case"TryStatement":case"VariableDeclaration":case"WhileStatement":case"WithStatement":return true}return false}function isSourceElement(node){return isStatement(node)||node!=null&&node.type==="FunctionDeclaration"}function trailingStatement(node){switch(node.type){case"IfStatement":if(node.alternate!=null){return node.alternate}return node.consequent;case"LabeledStatement":case"ForStatement":case"ForInStatement":case"WhileStatement":case"WithStatement":return node.body}return null}function isProblematicIfStatement(node){var current;if(node.type!=="IfStatement"){return false}if(node.alternate==null){return false}current=node.consequent;do{if(current.type==="IfStatement"){if(current.alternate==null){return true}}current=trailingStatement(current)}while(current);return false}module.exports={isExpression:isExpression,isStatement:isStatement,isIterationStatement:isIterationStatement,isSourceElement:isSourceElement,isProblematicIfStatement:isProblematicIfStatement,trailingStatement:trailingStatement}})()},{}],160:[function(require,module,exports){(function(){"use strict";var Regex,NON_ASCII_WHITESPACES;Regex={NonAsciiIdentifierStart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]"),NonAsciiIdentifierPart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԧԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠࢢ-ࢬࣤ-ࣾऀ-ॣ०-९ॱ-ॷॹ-ॿঁ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఁ-ఃఅ-ఌఎ-ఐఒ-నప-ళవ-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಂಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲംഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤜᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶᴀ-ᷦ᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚗꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺꩻꪀ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︦︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]")};function isDecimalDigit(ch){return ch>=48&&ch<=57}function isHexDigit(ch){return isDecimalDigit(ch)||97<=ch&&ch<=102||65<=ch&&ch<=70}function isOctalDigit(ch){return ch>=48&&ch<=55}NON_ASCII_WHITESPACES=[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279];function isWhiteSpace(ch){return ch===32||ch===9||ch===11||ch===12||ch===160||ch>=5760&&NON_ASCII_WHITESPACES.indexOf(ch)>=0}function isLineTerminator(ch){return ch===10||ch===13||ch===8232||ch===8233}function isIdentifierStart(ch){return ch>=97&&ch<=122||ch>=65&&ch<=90||ch===36||ch===95||ch===92||ch>=128&&Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))}function isIdentifierPart(ch){return ch>=97&&ch<=122||ch>=65&&ch<=90||ch>=48&&ch<=57||ch===36||ch===95||ch===92||ch>=128&&Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))}module.exports={isDecimalDigit:isDecimalDigit,isHexDigit:isHexDigit,isOctalDigit:isOctalDigit,isWhiteSpace:isWhiteSpace,isLineTerminator:isLineTerminator,isIdentifierStart:isIdentifierStart,isIdentifierPart:isIdentifierPart}})()},{}],161:[function(require,module,exports){(function(){"use strict";var code=require("./code");function isStrictModeReservedWordES6(id){switch(id){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"let":return true;default:return false}}function isKeywordES5(id,strict){if(!strict&&id==="yield"){return false}return isKeywordES6(id,strict)}function isKeywordES6(id,strict){if(strict&&isStrictModeReservedWordES6(id)){return true}switch(id.length){case 2:return id==="if"||id==="in"||id==="do";case 3:return id==="var"||id==="for"||id==="new"||id==="try";case 4:return id==="this"||id==="else"||id==="case"||id==="void"||id==="with"||id==="enum";case 5:return id==="while"||id==="break"||id==="catch"||id==="throw"||id==="const"||id==="yield"||id==="class"||id==="super";case 6:return id==="return"||id==="typeof"||id==="delete"||id==="switch"||id==="export"||id==="import";case 7:return id==="default"||id==="finally"||id==="extends";case 8:return id==="function"||id==="continue"||id==="debugger";case 10:return id==="instanceof";default:return false}}function isReservedWordES5(id,strict){return id==="null"||id==="true"||id==="false"||isKeywordES5(id,strict)}function isReservedWordES6(id,strict){return id==="null"||id==="true"||id==="false"||isKeywordES6(id,strict)}function isRestrictedWord(id){return id==="eval"||id==="arguments"}function isIdentifierName(id){var i,iz,ch;if(id.length===0){return false}ch=id.charCodeAt(0);if(!code.isIdentifierStart(ch)||ch===92){return false}for(i=1,iz=id.length;i<iz;++i){ch=id.charCodeAt(i);if(!code.isIdentifierPart(ch)||ch===92){return false}}return true}function isIdentifierES5(id,strict){return isIdentifierName(id)&&!isReservedWordES5(id,strict)}function isIdentifierES6(id,strict){return isIdentifierName(id)&&!isReservedWordES6(id,strict)}module.exports={isKeywordES5:isKeywordES5,isKeywordES6:isKeywordES6,isReservedWordES5:isReservedWordES5,isReservedWordES6:isReservedWordES6,isRestrictedWord:isRestrictedWord,isIdentifierName:isIdentifierName,isIdentifierES5:isIdentifierES5,isIdentifierES6:isIdentifierES6}})()},{"./code":160}],162:[function(require,module,exports){(function(){"use strict";exports.ast=require("./ast");exports.code=require("./code");exports.keyword=require("./keyword")})()},{"./ast":159,"./code":160,"./keyword":161}],163:[function(require,module,exports){function combine(){return new RegExp("("+[].slice.call(arguments).map(function(e){var e=e.toString();return"(?:"+e.substring(1,e.length-1)+")"}).join("|")+")")}function makeTester(rx){var s=rx.toString();return new RegExp("^"+s.substring(1,s.length-1)+"$")}var pattern={string1:/"(?:(?:\\\n|\\"|[^"\n]))*?"/,string2:/'(?:(?:\\\n|\\'|[^'\n]))*?'/,comment1:/\/\*[\s\S]*?\*\//,comment2:/\/\/.*?\n/,whitespace:/\s+/,keyword:/\b(?:var|let|for|if|else|in|class|function|return|with|case|break|switch|export|new|while|do|throw|catch)\b/,regexp:/\/(?:(?:\\\/|[^\n\/]))*?\//,name:/[a-zA-Z_\$][a-zA-Z_\$0-9]*/,number:/\d+(?:\.\d+)?(?:e[+-]?\d+)?/,parens:/[\(\)]/,curly:/[{}]/,square:/[\[\]]/,punct:/[;.:\?\^%<>=!&|+\-,~]/};var match=combine(pattern.string1,pattern.string2,pattern.comment1,pattern.comment2,pattern.regexp,pattern.whitespace,pattern.name,pattern.number,pattern.parens,pattern.curly,pattern.square,pattern.punct);var tester={};for(var k in pattern){tester[k]=makeTester(pattern[k])}module.exports=function(str,doNotThrow){return str.split(match).filter(function(e,i){if(i%2)return true;if(e!==""){if(!doNotThrow)throw new Error("invalid token:"+JSON.stringify(e));return true}})};module.exports.type=function(e){for(var type in pattern)if(tester[type].test(e))return type;return"invalid"}},{}],164:[function(require,module,exports){(function(global){(function(){var undefined;var VERSION="3.0.0";var BIND_FLAG=1,BIND_KEY_FLAG=2,CURRY_BOUND_FLAG=4,CURRY_FLAG=8,CURRY_RIGHT_FLAG=16,PARTIAL_FLAG=32,PARTIAL_RIGHT_FLAG=64,REARG_FLAG=128,ARY_FLAG=256;var DEFAULT_TRUNC_LENGTH=30,DEFAULT_TRUNC_OMISSION="...";var HOT_COUNT=150,HOT_SPAN=16;var LAZY_FILTER_FLAG=0,LAZY_MAP_FLAG=1,LAZY_WHILE_FLAG=2;var FUNC_ERROR_TEXT="Expected a function";var PLACEHOLDER="__lodash_placeholder__";var argsTag="[object Arguments]",arrayTag="[object Array]",boolTag="[object Boolean]",dateTag="[object Date]",errorTag="[object Error]",funcTag="[object Function]",mapTag="[object Map]",numberTag="[object Number]",objectTag="[object Object]",regexpTag="[object RegExp]",setTag="[object Set]",stringTag="[object String]",weakMapTag="[object WeakMap]";var arrayBufferTag="[object ArrayBuffer]",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]";var reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g;var reEscapedHtml=/&(?:amp|lt|gt|quot|#39|#96);/g,reUnescapedHtml=/[&<>"'`]/g,reHasEscapedHtml=RegExp(reEscapedHtml.source),reHasUnescapedHtml=RegExp(reUnescapedHtml.source);
var reEscape=/<%-([\s\S]+?)%>/g,reEvaluate=/<%([\s\S]+?)%>/g,reInterpolate=/<%=([\s\S]+?)%>/g;var reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;var reFlags=/\w*$/;var reFuncName=/^\s*function[ \n\r\t]+\w/;var reHexPrefix=/^0[xX]/;var reHostCtor=/^\[object .+?Constructor\]$/;var reLatin1=/[\xc0-\xd6\xd8-\xde\xdf-\xf6\xf8-\xff]/g;var reNoMatch=/($^)/;var reRegExpChars=/[.*+?^${}()|[\]\/\\]/g,reHasRegExpChars=RegExp(reRegExpChars.source);var reThis=/\bthis\b/;var reUnescapedString=/['\n\r\u2028\u2029\\]/g;var reWords=function(){var upper="[A-Z\\xc0-\\xd6\\xd8-\\xde]",lower="[a-z\\xdf-\\xf6\\xf8-\\xff]+";return RegExp(upper+"{2,}(?="+upper+lower+")|"+upper+"?"+lower+"|"+upper+"+|[0-9]+","g")}();var whitespace=" \f "+"\n\r\u2028\u2029"+" ";var contextProps=["Array","ArrayBuffer","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Math","Number","Object","RegExp","Set","String","_","clearTimeout","document","isFinite","parseInt","setTimeout","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","window","WinRTError"];var templateCounter=-1;var typedArrayTags={};typedArrayTags[float32Tag]=typedArrayTags[float64Tag]=typedArrayTags[int8Tag]=typedArrayTags[int16Tag]=typedArrayTags[int32Tag]=typedArrayTags[uint8Tag]=typedArrayTags[uint8ClampedTag]=typedArrayTags[uint16Tag]=typedArrayTags[uint32Tag]=true;typedArrayTags[argsTag]=typedArrayTags[arrayTag]=typedArrayTags[arrayBufferTag]=typedArrayTags[boolTag]=typedArrayTags[dateTag]=typedArrayTags[errorTag]=typedArrayTags[funcTag]=typedArrayTags[mapTag]=typedArrayTags[numberTag]=typedArrayTags[objectTag]=typedArrayTags[regexpTag]=typedArrayTags[setTag]=typedArrayTags[stringTag]=typedArrayTags[weakMapTag]=false;var cloneableTags={};cloneableTags[argsTag]=cloneableTags[arrayTag]=cloneableTags[arrayBufferTag]=cloneableTags[boolTag]=cloneableTags[dateTag]=cloneableTags[float32Tag]=cloneableTags[float64Tag]=cloneableTags[int8Tag]=cloneableTags[int16Tag]=cloneableTags[int32Tag]=cloneableTags[numberTag]=cloneableTags[objectTag]=cloneableTags[regexpTag]=cloneableTags[stringTag]=cloneableTags[uint8Tag]=cloneableTags[uint8ClampedTag]=cloneableTags[uint16Tag]=cloneableTags[uint32Tag]=true;cloneableTags[errorTag]=cloneableTags[funcTag]=cloneableTags[mapTag]=cloneableTags[setTag]=cloneableTags[weakMapTag]=false;var debounceOptions={leading:false,maxWait:0,trailing:false};var deburredLetters={"À":"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"};var htmlEscapes={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"};var htmlUnescapes={"&":"&","<":"<",">":">",""":'"',"'":"'","`":"`"};var objectTypes={"function":true,object:true};var stringEscapes={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"};var root=objectTypes[typeof window]&&window!==(this&&this.window)?window:this;var freeExports=objectTypes[typeof exports]&&exports&&!exports.nodeType&&exports;var freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module;var freeGlobal=freeExports&&freeModule&&typeof global=="object"&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal)){root=freeGlobal}var moduleExports=freeModule&&freeModule.exports===freeExports&&freeExports;function baseCompareAscending(value,other){if(value!==other){var valIsReflexive=value===value,othIsReflexive=other===other;if(value>other||!valIsReflexive||typeof value=="undefined"&&othIsReflexive){return 1}if(value<other||!othIsReflexive||typeof other=="undefined"&&valIsReflexive){return-1}}return 0}function baseIndexOf(array,value,fromIndex){if(value!==value){return indexOfNaN(array,fromIndex)}var index=(fromIndex||0)-1,length=array.length;while(++index<length){if(array[index]===value){return index}}return-1}function baseSortBy(array,comparer){var length=array.length;array.sort(comparer);while(length--){array[length]=array[length].value}return array}function baseToString(value){if(typeof value=="string"){return value}return value==null?"":value+""}function charAtCallback(string){return string.charCodeAt(0)}function charsLeftIndex(string,chars){var index=-1,length=string.length;while(++index<length&&chars.indexOf(string.charAt(index))>-1){}return index}function charsRightIndex(string,chars){var index=string.length;while(index--&&chars.indexOf(string.charAt(index))>-1){}return index}function compareAscending(object,other){return baseCompareAscending(object.criteria,other.criteria)||object.index-other.index}function compareMultipleAscending(object,other){var index=-1,objCriteria=object.criteria,othCriteria=other.criteria,length=objCriteria.length;while(++index<length){var result=baseCompareAscending(objCriteria[index],othCriteria[index]);if(result){return result}}return object.index-other.index}function deburrLetter(letter){return deburredLetters[letter]}function escapeHtmlChar(chr){return htmlEscapes[chr]}function escapeStringChar(chr){return"\\"+stringEscapes[chr]}function indexOfNaN(array,fromIndex,fromRight){var length=array.length,index=fromRight?fromIndex||length:(fromIndex||0)-1;while(fromRight?index--:++index<length){var other=array[index];if(other!==other){return index}}return-1}function isObjectLike(value){return value&&typeof value=="object"||false}function isSpace(charCode){return charCode<=160&&(charCode>=9&&charCode<=13)||charCode==32||charCode==160||charCode==5760||charCode==6158||charCode>=8192&&(charCode<=8202||charCode==8232||charCode==8233||charCode==8239||charCode==8287||charCode==12288||charCode==65279)}function replaceHolders(array,placeholder){var index=-1,length=array.length,resIndex=-1,result=[];while(++index<length){if(array[index]===placeholder){array[index]=PLACEHOLDER;result[++resIndex]=index}}return result}function sortedUniq(array,iteratee){var seen,index=-1,length=array.length,resIndex=-1,result=[];while(++index<length){var value=array[index],computed=iteratee?iteratee(value,index,array):value;if(!index||seen!==computed){seen=computed;result[++resIndex]=value}}return result}function trimmedLeftIndex(string){var index=-1,length=string.length;while(++index<length&&isSpace(string.charCodeAt(index))){}return index}function trimmedRightIndex(string){var index=string.length;while(index--&&isSpace(string.charCodeAt(index))){}return index}function unescapeHtmlChar(chr){return htmlUnescapes[chr]}function runInContext(context){context=context?_.defaults(root.Object(),context,_.pick(root,contextProps)):root;var Array=context.Array,Date=context.Date,Error=context.Error,Function=context.Function,Math=context.Math,Number=context.Number,Object=context.Object,RegExp=context.RegExp,String=context.String,TypeError=context.TypeError;var arrayProto=Array.prototype,objectProto=Object.prototype;var document=(document=context.window)&&document.document;var fnToString=Function.prototype.toString;var getLength=baseProperty("length");var hasOwnProperty=objectProto.hasOwnProperty;var idCounter=0;var objToString=objectProto.toString;var oldDash=context._;var reNative=RegExp("^"+escapeRegExp(objToString).replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");var ArrayBuffer=isNative(ArrayBuffer=context.ArrayBuffer)&&ArrayBuffer,bufferSlice=isNative(bufferSlice=ArrayBuffer&&new ArrayBuffer(0).slice)&&bufferSlice,ceil=Math.ceil,clearTimeout=context.clearTimeout,floor=Math.floor,getPrototypeOf=isNative(getPrototypeOf=Object.getPrototypeOf)&&getPrototypeOf,push=arrayProto.push,propertyIsEnumerable=objectProto.propertyIsEnumerable,Set=isNative(Set=context.Set)&&Set,setTimeout=context.setTimeout,splice=arrayProto.splice,Uint8Array=isNative(Uint8Array=context.Uint8Array)&&Uint8Array,unshift=arrayProto.unshift,WeakMap=isNative(WeakMap=context.WeakMap)&&WeakMap;var Float64Array=function(){try{var func=isNative(func=context.Float64Array)&&func,result=new func(new ArrayBuffer(10),0,1)&&func}catch(e){}return result}();var nativeIsArray=isNative(nativeIsArray=Array.isArray)&&nativeIsArray,nativeCreate=isNative(nativeCreate=Object.create)&&nativeCreate,nativeIsFinite=context.isFinite,nativeKeys=isNative(nativeKeys=Object.keys)&&nativeKeys,nativeMax=Math.max,nativeMin=Math.min,nativeNow=isNative(nativeNow=Date.now)&&nativeNow,nativeNumIsFinite=isNative(nativeNumIsFinite=Number.isFinite)&&nativeNumIsFinite,nativeParseInt=context.parseInt,nativeRandom=Math.random;var NEGATIVE_INFINITY=Number.NEGATIVE_INFINITY,POSITIVE_INFINITY=Number.POSITIVE_INFINITY;var MAX_ARRAY_LENGTH=Math.pow(2,32)-1,MAX_ARRAY_INDEX=MAX_ARRAY_LENGTH-1,HALF_MAX_ARRAY_LENGTH=MAX_ARRAY_LENGTH>>>1;var FLOAT64_BYTES_PER_ELEMENT=Float64Array?Float64Array.BYTES_PER_ELEMENT:0;var MAX_SAFE_INTEGER=Math.pow(2,53)-1;var metaMap=WeakMap&&new WeakMap;function lodash(value){if(isObjectLike(value)&&!isArray(value)){if(value instanceof LodashWrapper){return value}if(hasOwnProperty.call(value,"__wrapped__")){return new LodashWrapper(value.__wrapped__,value.__chain__,arrayCopy(value.__actions__))}}return new LodashWrapper(value)}function LodashWrapper(value,chainAll,actions){this.__actions__=actions||[];this.__chain__=!!chainAll;this.__wrapped__=value}var support=lodash.support={};(function(x){support.funcDecomp=!isNative(context.WinRTError)&&reThis.test(runInContext);support.funcNames=typeof Function.name=="string";try{support.dom=document.createDocumentFragment().nodeType===11}catch(e){support.dom=false}try{support.nonEnumArgs=!propertyIsEnumerable.call(arguments,1)}catch(e){support.nonEnumArgs=true}})(0,0);lodash.templateSettings={escape:reEscape,evaluate:reEvaluate,interpolate:reInterpolate,variable:"",imports:{_:lodash}};function LazyWrapper(value){this.actions=null;this.dir=1;this.dropCount=0;this.filtered=false;this.iteratees=null;this.takeCount=POSITIVE_INFINITY;this.views=null;this.wrapped=value}function lazyClone(){var actions=this.actions,iteratees=this.iteratees,views=this.views,result=new LazyWrapper(this.wrapped);result.actions=actions?arrayCopy(actions):null;result.dir=this.dir;result.dropCount=this.dropCount;result.filtered=this.filtered;result.iteratees=iteratees?arrayCopy(iteratees):null;result.takeCount=this.takeCount;result.views=views?arrayCopy(views):null;return result}function lazyReverse(){var filtered=this.filtered,result=filtered?new LazyWrapper(this):this.clone();result.dir=this.dir*-1;result.filtered=filtered;return result}function lazyValue(){var array=this.wrapped.value();if(!isArray(array)){return baseWrapperValue(array,this.actions)}var dir=this.dir,isRight=dir<0,length=array.length,view=getView(0,length,this.views),start=view.start,end=view.end,dropCount=this.dropCount,takeCount=nativeMin(end-start,this.takeCount-dropCount),index=isRight?end:start-1,iteratees=this.iteratees,iterLength=iteratees?iteratees.length:0,resIndex=0,result=[];outer:while(length--&&resIndex<takeCount){index+=dir;var iterIndex=-1,value=array[index];while(++iterIndex<iterLength){var data=iteratees[iterIndex],iteratee=data.iteratee,computed=iteratee(value,index,array),type=data.type;if(type==LAZY_MAP_FLAG){value=computed}else if(!computed){if(type==LAZY_FILTER_FLAG){continue outer}else{break outer}}}if(dropCount){dropCount--}else{result[resIndex++]=value}}return isRight?result.reverse():result}function MapCache(){this.__data__={}}function mapDelete(key){return this.has(key)&&delete this.__data__[key]}function mapGet(key){return key=="__proto__"?undefined:this.__data__[key]}function mapHas(key){return key!="__proto__"&&hasOwnProperty.call(this.__data__,key)}function mapSet(key,value){if(key!="__proto__"){this.__data__[key]=value}return this}function SetCache(values){var length=values?values.length:0;this.data={hash:nativeCreate(null),set:new Set};while(length--){this.push(values[length])}}function cacheIndexOf(cache,value){var data=cache.data,result=typeof value=="string"||isObject(value)?data.set.has(value):data.hash[value];return result?0:-1}function cachePush(value){var data=this.data;if(typeof value=="string"||isObject(value)){data.set.add(value)}else{data.hash[value]=true}}function arrayCopy(source,array){var index=-1,length=source.length;array||(array=Array(length));while(++index<length){array[index]=source[index]}return array}function arrayEach(array,iteratee){var index=-1,length=array.length;while(++index<length){if(iteratee(array[index],index,array)===false){break}}return array}function arrayEachRight(array,iteratee){var length=array.length;while(length--){if(iteratee(array[length],length,array)===false){break}}return array}function arrayEvery(array,predicate){var index=-1,length=array.length;while(++index<length){if(!predicate(array[index],index,array)){return false}}return true}function arrayFilter(array,predicate){var index=-1,length=array.length,resIndex=-1,result=[];while(++index<length){var value=array[index];if(predicate(value,index,array)){result[++resIndex]=value}}return result}function arrayMap(array,iteratee){var index=-1,length=array.length,result=Array(length);while(++index<length){result[index]=iteratee(array[index],index,array)}return result}function arrayMax(array){var index=-1,length=array.length,result=NEGATIVE_INFINITY;while(++index<length){var value=array[index];if(value>result){result=value}}return result}function arrayMin(array){var index=-1,length=array.length,result=POSITIVE_INFINITY;while(++index<length){var value=array[index];if(value<result){result=value}}return result}function arrayReduce(array,iteratee,accumulator,initFromArray){var index=-1,length=array.length;if(initFromArray&&length){accumulator=array[++index]}while(++index<length){accumulator=iteratee(accumulator,array[index],index,array)}return accumulator}function arrayReduceRight(array,iteratee,accumulator,initFromArray){var length=array.length;if(initFromArray&&length){accumulator=array[--length]}while(length--){accumulator=iteratee(accumulator,array[length],length,array)}return accumulator}function arraySome(array,predicate){var index=-1,length=array.length;while(++index<length){if(predicate(array[index],index,array)){return true}}return false}function assignDefaults(objectValue,sourceValue){return typeof objectValue=="undefined"?sourceValue:objectValue}function assignOwnDefaults(objectValue,sourceValue,key,object){return typeof objectValue=="undefined"||!hasOwnProperty.call(object,key)?sourceValue:objectValue}function baseAssign(object,source,customizer){var props=keys(source);if(!customizer){return baseCopy(source,object,props)}var index=-1,length=props.length;while(++index<length){var key=props[index],value=object[key],result=customizer(value,source[key],key,object,source);if((result===result?result!==value:value===value)||typeof value=="undefined"&&!(key in object)){object[key]=result}}return object}function baseAt(collection,props){var index=-1,length=collection.length,isArr=isLength(length),propsLength=props.length,result=Array(propsLength);while(++index<propsLength){var key=props[index];if(isArr){key=parseFloat(key);result[index]=isIndex(key,length)?collection[key]:undefined}else{result[index]=collection[key]}}return result}function baseCopy(source,object,props){if(!props){props=object;object={}}var index=-1,length=props.length;while(++index<length){var key=props[index];object[key]=source[key]}return object}function baseBindAll(object,methodNames){var index=-1,length=methodNames.length;while(++index<length){var key=methodNames[index];object[key]=createWrapper(object[key],BIND_FLAG,object)}return object}function baseCallback(func,thisArg,argCount){var type=typeof func;if(type=="function"){return typeof thisArg!="undefined"&&isBindable(func)?bindCallback(func,thisArg,argCount):func}if(func==null){return identity}return type=="object"?baseMatches(func,!argCount):baseProperty(argCount?baseToString(func):func)}function baseClone(value,isDeep,customizer,key,object,stackA,stackB){var result;if(customizer){result=object?customizer(value,key,object):customizer(value)}if(typeof result!="undefined"){return result}if(!isObject(value)){return value}var isArr=isArray(value);if(isArr){result=initCloneArray(value);if(!isDeep){return arrayCopy(value,result)}}else{var tag=objToString.call(value),isFunc=tag==funcTag;if(tag==objectTag||tag==argsTag||isFunc&&!object){result=initCloneObject(isFunc?{}:value);if(!isDeep){return baseCopy(value,result,keys(value))}}else{return cloneableTags[tag]?initCloneByTag(value,tag,isDeep):object?value:{}}}stackA||(stackA=[]);stackB||(stackB=[]);var length=stackA.length;while(length--){if(stackA[length]==value){return stackB[length]}}stackA.push(value);stackB.push(result);(isArr?arrayEach:baseForOwn)(value,function(subValue,key){result[key]=baseClone(subValue,isDeep,customizer,key,value,stackA,stackB)});return result}var baseCreate=function(){function Object(){}return function(prototype){if(isObject(prototype)){Object.prototype=prototype;var result=new Object;Object.prototype=null}return result||context.Object()}}();function baseDelay(func,wait,args,fromIndex){if(!isFunction(func)){throw new TypeError(FUNC_ERROR_TEXT)}return setTimeout(function(){func.apply(undefined,baseSlice(args,fromIndex))},wait)}function baseDifference(array,values){var length=array?array.length:0,result=[];if(!length){return result}var index=-1,indexOf=getIndexOf(),isCommon=indexOf==baseIndexOf,cache=isCommon&&values.length>=200&&createCache(values),valuesLength=values.length;if(cache){indexOf=cacheIndexOf;isCommon=false;values=cache}outer:while(++index<length){var value=array[index];if(isCommon&&value===value){var valuesIndex=valuesLength;while(valuesIndex--){if(values[valuesIndex]===value){continue outer}}result.push(value)}else if(indexOf(values,value)<0){result.push(value)}}return result}function baseEach(collection,iteratee){var length=collection?collection.length:0;if(!isLength(length)){return baseForOwn(collection,iteratee)}var index=-1,iterable=toObject(collection);while(++index<length){if(iteratee(iterable[index],index,iterable)===false){break}}return collection}function baseEachRight(collection,iteratee){var length=collection?collection.length:0;if(!isLength(length)){return baseForOwnRight(collection,iteratee)}var iterable=toObject(collection);while(length--){if(iteratee(iterable[length],length,iterable)===false){break}}return collection}function baseEvery(collection,predicate){var result=true;baseEach(collection,function(value,index,collection){result=!!predicate(value,index,collection);return result});return result}function baseFilter(collection,predicate){var result=[];baseEach(collection,function(value,index,collection){if(predicate(value,index,collection)){result.push(value)}});return result}function baseFind(collection,predicate,eachFunc,retKey){var result;eachFunc(collection,function(value,key,collection){if(predicate(value,key,collection)){result=retKey?key:value;return false}});return result}function baseFlatten(array,isDeep,isStrict,fromIndex){var index=(fromIndex||0)-1,length=array.length,resIndex=-1,result=[];while(++index<length){var value=array[index];if(isObjectLike(value)&&isLength(value.length)&&(isArray(value)||isArguments(value))){if(isDeep){value=baseFlatten(value,isDeep,isStrict)}var valIndex=-1,valLength=value.length;result.length+=valLength;while(++valIndex<valLength){result[++resIndex]=value[valIndex]}}else if(!isStrict){result[++resIndex]=value}}return result}function baseFor(object,iteratee,keysFunc){var index=-1,iterable=toObject(object),props=keysFunc(object),length=props.length;while(++index<length){var key=props[index];if(iteratee(iterable[key],key,iterable)===false){break}}return object}function baseForRight(object,iteratee,keysFunc){var iterable=toObject(object),props=keysFunc(object),length=props.length;while(length--){var key=props[length];if(iteratee(iterable[key],key,iterable)===false){break}}return object}function baseForIn(object,iteratee){return baseFor(object,iteratee,keysIn)}function baseForOwn(object,iteratee){return baseFor(object,iteratee,keys)}function baseForOwnRight(object,iteratee){return baseForRight(object,iteratee,keys)}function baseFunctions(object,props){var index=-1,length=props.length,resIndex=-1,result=[];while(++index<length){var key=props[index];if(isFunction(object[key])){result[++resIndex]=key}}return result}function baseInvoke(collection,methodName,args){var index=-1,isFunc=typeof methodName=="function",length=collection?collection.length:0,result=isLength(length)?Array(length):[];baseEach(collection,function(value){var func=isFunc?methodName:value!=null&&value[methodName];result[++index]=func?func.apply(value,args):undefined});return result}function baseIsEqual(value,other,customizer,isWhere,stackA,stackB){if(value===other){return value!==0||1/value==1/other}var valType=typeof value,othType=typeof other;if(valType!="function"&&valType!="object"&&othType!="function"&&othType!="object"||value==null||other==null){return value!==value&&other!==other}return baseIsEqualDeep(value,other,baseIsEqual,customizer,isWhere,stackA,stackB)}function baseIsEqualDeep(object,other,equalFunc,customizer,isWhere,stackA,stackB){var objIsArr=isArray(object),othIsArr=isArray(other),objTag=arrayTag,othTag=arrayTag;if(!objIsArr){objTag=objToString.call(object);if(objTag==argsTag){objTag=objectTag}else if(objTag!=objectTag){objIsArr=isTypedArray(object)}}if(!othIsArr){othTag=objToString.call(other);if(othTag==argsTag){othTag=objectTag}else if(othTag!=objectTag){othIsArr=isTypedArray(other)}}var objIsObj=objTag==objectTag,othIsObj=othTag==objectTag,isSameTag=objTag==othTag;if(isSameTag&&!(objIsArr||objIsObj)){return equalByTag(object,other,objTag)}var valWrapped=objIsObj&&hasOwnProperty.call(object,"__wrapped__"),othWrapped=othIsObj&&hasOwnProperty.call(other,"__wrapped__");if(valWrapped||othWrapped){return equalFunc(valWrapped?object.value():object,othWrapped?other.value():other,customizer,isWhere,stackA,stackB)}if(!isSameTag){return false}stackA||(stackA=[]);stackB||(stackB=[]);var length=stackA.length;while(length--){if(stackA[length]==object){return stackB[length]==other}}stackA.push(object);stackB.push(other);var result=(objIsArr?equalArrays:equalObjects)(object,other,equalFunc,customizer,isWhere,stackA,stackB);stackA.pop();stackB.pop();return result}function baseIsMatch(object,props,values,strictCompareFlags,customizer){var length=props.length;if(object==null){return!length}var index=-1,noCustomizer=!customizer;while(++index<length){if(noCustomizer&&strictCompareFlags[index]?values[index]!==object[props[index]]:!hasOwnProperty.call(object,props[index])){return false}}index=-1;while(++index<length){var key=props[index];if(noCustomizer&&strictCompareFlags[index]){var result=hasOwnProperty.call(object,key)}else{var objValue=object[key],srcValue=values[index];result=customizer?customizer(objValue,srcValue,key):undefined;if(typeof result=="undefined"){result=baseIsEqual(srcValue,objValue,customizer,true)}}if(!result){return false}}return true}function baseMap(collection,iteratee){var result=[];baseEach(collection,function(value,key,collection){result.push(iteratee(value,key,collection))});return result}function baseMatches(source,isCloned){var props=keys(source),length=props.length;if(length==1){var key=props[0],value=source[key];if(isStrictComparable(value)){return function(object){return object!=null&&value===object[key]&&hasOwnProperty.call(object,key)}}}if(isCloned){source=baseClone(source,true)}var values=Array(length),strictCompareFlags=Array(length);while(length--){value=source[props[length]];values[length]=value;strictCompareFlags[length]=isStrictComparable(value)}return function(object){return baseIsMatch(object,props,values,strictCompareFlags)}}function baseMerge(object,source,customizer,stackA,stackB){var isSrcArr=isLength(source.length)&&(isArray(source)||isTypedArray(source));(isSrcArr?arrayEach:baseForOwn)(source,function(srcValue,key,source){if(isObjectLike(srcValue)){stackA||(stackA=[]);stackB||(stackB=[]);return baseMergeDeep(object,source,key,baseMerge,customizer,stackA,stackB)}var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=typeof result=="undefined";if(isCommon){result=srcValue}if((isSrcArr||typeof result!="undefined")&&(isCommon||(result===result?result!==value:value===value))){object[key]=result}});return object}function baseMergeDeep(object,source,key,mergeFunc,customizer,stackA,stackB){var length=stackA.length,srcValue=source[key];while(length--){if(stackA[length]==srcValue){object[key]=stackB[length];return}}var value=object[key],result=customizer?customizer(value,srcValue,key,object,source):undefined,isCommon=typeof result=="undefined";if(isCommon){result=srcValue;if(isLength(srcValue.length)&&(isArray(srcValue)||isTypedArray(srcValue))){result=isArray(value)?value:value?arrayCopy(value):[]}else if(isPlainObject(srcValue)||isArguments(srcValue)){result=isArguments(value)?toPlainObject(value):isPlainObject(value)?value:{}}}stackA.push(srcValue);stackB.push(result);if(isCommon){object[key]=mergeFunc(result,srcValue,customizer,stackA,stackB)}else if(result===result?result!==value:value===value){object[key]=result}}function baseProperty(key){return function(object){return object==null?undefined:object[key]}}function basePullAt(array,indexes){var length=indexes.length,result=baseAt(array,indexes);indexes.sort(baseCompareAscending);while(length--){var index=parseFloat(indexes[length]);if(index!=previous&&isIndex(index)){var previous=index;splice.call(array,index,1)}}return result}function baseRandom(min,max){return min+floor(nativeRandom()*(max-min+1))}function baseReduce(collection,iteratee,accumulator,initFromCollection,eachFunc){eachFunc(collection,function(value,index,collection){accumulator=initFromCollection?(initFromCollection=false,value):iteratee(accumulator,value,index,collection)});return accumulator}var baseSetData=!metaMap?identity:function(func,data){metaMap.set(func,data);return func};function baseSlice(array,start,end){var index=-1,length=array.length;start=start==null?0:+start||0;if(start<0){start=-start>length?0:length+start}end=typeof end=="undefined"||end>length?length:+end||0;if(end<0){end+=length}length=start>end?0:end-start;var result=Array(length);while(++index<length){result[index]=array[index+start]}return result}function baseSome(collection,predicate){var result;baseEach(collection,function(value,index,collection){result=predicate(value,index,collection);return!result});return!!result}function baseUniq(array,iteratee){var index=-1,indexOf=getIndexOf(),length=array.length,isCommon=indexOf==baseIndexOf,isLarge=isCommon&&length>=200,seen=isLarge&&createCache(),result=[];if(seen){indexOf=cacheIndexOf;isCommon=false}else{isLarge=false;seen=iteratee?[]:result}outer:while(++index<length){var value=array[index],computed=iteratee?iteratee(value,index,array):value;if(isCommon&&value===value){var seenIndex=seen.length;while(seenIndex--){if(seen[seenIndex]===computed){continue outer}}if(iteratee){seen.push(computed)}result.push(value)}else if(indexOf(seen,computed)<0){if(iteratee||isLarge){seen.push(computed)}result.push(value)}}return result}function baseValues(object,props){var index=-1,length=props.length,result=Array(length);while(++index<length){result[index]=object[props[index]]}return result}function baseWrapperValue(value,actions){var result=value;if(result instanceof LazyWrapper){result=result.value()}var index=-1,length=actions.length;while(++index<length){var args=[result],action=actions[index];push.apply(args,action.args);result=action.func.apply(action.thisArg,args)}return result}function binaryIndex(array,value,retHighest){var low=0,high=array?array.length:low;if(typeof value=="number"&&value===value&&high<=HALF_MAX_ARRAY_LENGTH){while(low<high){var mid=low+high>>>1,computed=array[mid];if(retHighest?computed<=value:computed<value){low=mid+1}else{high=mid}}return high}return binaryIndexBy(array,value,identity,retHighest)}function binaryIndexBy(array,value,iteratee,retHighest){value=iteratee(value);var low=0,high=array?array.length:0,valIsNaN=value!==value,valIsUndef=typeof value=="undefined";while(low<high){var mid=floor((low+high)/2),computed=iteratee(array[mid]),isReflexive=computed===computed;if(valIsNaN){var setLow=isReflexive||retHighest}else if(valIsUndef){setLow=isReflexive&&(retHighest||typeof computed!="undefined")}else{setLow=retHighest?computed<=value:computed<value}if(setLow){low=mid+1}else{high=mid}}return nativeMin(high,MAX_ARRAY_INDEX)}function bindCallback(func,thisArg,argCount){if(typeof func!="function"){return identity}if(typeof thisArg=="undefined"){return func}switch(argCount){case 1:return function(value){return func.call(thisArg,value)};case 3:return function(value,index,collection){return func.call(thisArg,value,index,collection)};case 4:return function(accumulator,value,index,collection){return func.call(thisArg,accumulator,value,index,collection)};case 5:return function(value,other,key,object,source){return func.call(thisArg,value,other,key,object,source)}}return function(){return func.apply(thisArg,arguments)}}function bufferClone(buffer){return bufferSlice.call(buffer,0)}if(!bufferSlice){bufferClone=!(ArrayBuffer&&Uint8Array)?constant(null):function(buffer){var byteLength=buffer.byteLength,floatLength=Float64Array?floor(byteLength/FLOAT64_BYTES_PER_ELEMENT):0,offset=floatLength*FLOAT64_BYTES_PER_ELEMENT,result=new ArrayBuffer(byteLength);if(floatLength){var view=new Float64Array(result,0,floatLength);view.set(new Float64Array(buffer,0,floatLength))}if(byteLength!=offset){view=new Uint8Array(result,offset);view.set(new Uint8Array(buffer,offset))}return result}}function composeArgs(args,partials,holders){var holdersLength=holders.length,argsIndex=-1,argsLength=nativeMax(args.length-holdersLength,0),leftIndex=-1,leftLength=partials.length,result=Array(argsLength+leftLength);while(++leftIndex<leftLength){result[leftIndex]=partials[leftIndex]}while(++argsIndex<holdersLength){result[holders[argsIndex]]=args[argsIndex]}while(argsLength--){result[leftIndex++]=args[argsIndex++]}return result}function composeArgsRight(args,partials,holders){var holdersIndex=-1,holdersLength=holders.length,argsIndex=-1,argsLength=nativeMax(args.length-holdersLength,0),rightIndex=-1,rightLength=partials.length,result=Array(argsLength+rightLength);while(++argsIndex<argsLength){result[argsIndex]=args[argsIndex]}var pad=argsIndex;while(++rightIndex<rightLength){result[pad+rightIndex]=partials[rightIndex]}while(++holdersIndex<holdersLength){result[pad+holders[holdersIndex]]=args[argsIndex++]}return result}function createAggregator(setter,initializer){return function(collection,iteratee,thisArg){var result=initializer?initializer():{};iteratee=getCallback(iteratee,thisArg,3);if(isArray(collection)){var index=-1,length=collection.length;while(++index<length){var value=collection[index];setter(result,value,iteratee(value,index,collection),collection)}}else{baseEach(collection,function(value,key,collection){setter(result,value,iteratee(value,key,collection),collection)})}return result}}function createAssigner(assigner){return function(){var length=arguments.length,object=arguments[0];if(length<2||object==null){return object}if(length>3&&isIterateeCall(arguments[1],arguments[2],arguments[3])){length=2}if(length>3&&typeof arguments[length-2]=="function"){var customizer=bindCallback(arguments[--length-1],arguments[length--],5)}else if(length>2&&typeof arguments[length-1]=="function"){customizer=arguments[--length]}var index=0;while(++index<length){var source=arguments[index];if(source){assigner(object,source,customizer)}}return object}}function createBindWrapper(func,thisArg){var Ctor=createCtorWrapper(func);
function wrapper(){return(this instanceof wrapper?Ctor:func).apply(thisArg,arguments)}return wrapper}var createCache=!(nativeCreate&&Set)?constant(null):function(values){return new SetCache(values)};function createCompounder(callback){return function(string){var index=-1,array=words(deburr(string)),length=array.length,result="";while(++index<length){result=callback(result,array[index],index)}return result}}function createCtorWrapper(Ctor){return function(){var thisBinding=baseCreate(Ctor.prototype),result=Ctor.apply(thisBinding,arguments);return isObject(result)?result:thisBinding}}function createExtremum(arrayFunc,isMin){return function(collection,iteratee,thisArg){if(thisArg&&isIterateeCall(collection,iteratee,thisArg)){iteratee=null}var func=getCallback(),noIteratee=iteratee==null;if(!(func===baseCallback&&noIteratee)){noIteratee=false;iteratee=func(iteratee,thisArg,3)}if(noIteratee){var isArr=isArray(collection);if(!isArr&&isString(collection)){iteratee=charAtCallback}else{return arrayFunc(isArr?collection:toIterable(collection))}}return extremumBy(collection,iteratee,isMin)}}function createHybridWrapper(func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity){var isAry=bitmask&ARY_FLAG,isBind=bitmask&BIND_FLAG,isBindKey=bitmask&BIND_KEY_FLAG,isCurry=bitmask&CURRY_FLAG,isCurryBound=bitmask&CURRY_BOUND_FLAG,isCurryRight=bitmask&CURRY_RIGHT_FLAG;var Ctor=!isBindKey&&createCtorWrapper(func),key=func;function wrapper(){var length=arguments.length,index=length,args=Array(length);while(index--){args[index]=arguments[index]}if(partials){args=composeArgs(args,partials,holders)}if(partialsRight){args=composeArgsRight(args,partialsRight,holdersRight)}if(isCurry||isCurryRight){var placeholder=wrapper.placeholder,argsHolders=replaceHolders(args,placeholder);length-=argsHolders.length;if(length<arity){var newArgPos=argPos?arrayCopy(argPos):null,newArity=nativeMax(arity-length,0),newsHolders=isCurry?argsHolders:null,newHoldersRight=isCurry?null:argsHolders,newPartials=isCurry?args:null,newPartialsRight=isCurry?null:args;bitmask|=isCurry?PARTIAL_FLAG:PARTIAL_RIGHT_FLAG;bitmask&=~(isCurry?PARTIAL_RIGHT_FLAG:PARTIAL_FLAG);if(!isCurryBound){bitmask&=~(BIND_FLAG|BIND_KEY_FLAG)}var result=createHybridWrapper(func,bitmask,thisArg,newPartials,newsHolders,newPartialsRight,newHoldersRight,newArgPos,ary,newArity);result.placeholder=placeholder;return result}}var thisBinding=isBind?thisArg:this;if(isBindKey){func=thisBinding[key]}if(argPos){args=reorder(args,argPos)}if(isAry&&ary<args.length){args.length=ary}return(this instanceof wrapper?Ctor||createCtorWrapper(func):func).apply(thisBinding,args)}return wrapper}function createPad(string,length,chars){var strLength=string.length;length=+length;if(strLength>=length||!nativeIsFinite(length)){return""}var padLength=length-strLength;chars=chars==null?" ":baseToString(chars);return repeat(chars,ceil(padLength/chars.length)).slice(0,padLength)}function createPartialWrapper(func,bitmask,thisArg,partials){var isBind=bitmask&BIND_FLAG,Ctor=createCtorWrapper(func);function wrapper(){var argsIndex=-1,argsLength=arguments.length,leftIndex=-1,leftLength=partials.length,args=Array(argsLength+leftLength);while(++leftIndex<leftLength){args[leftIndex]=partials[leftIndex]}while(argsLength--){args[leftIndex++]=arguments[++argsIndex]}return(this instanceof wrapper?Ctor:func).apply(isBind?thisArg:this,args)}return wrapper}function createWrapper(func,bitmask,thisArg,partials,holders,argPos,ary,arity){var isBindKey=bitmask&BIND_KEY_FLAG;if(!isBindKey&&!isFunction(func)){throw new TypeError(FUNC_ERROR_TEXT)}var length=partials?partials.length:0;if(!length){bitmask&=~(PARTIAL_FLAG|PARTIAL_RIGHT_FLAG);partials=holders=null}length-=holders?holders.length:0;if(bitmask&PARTIAL_RIGHT_FLAG){var partialsRight=partials,holdersRight=holders;partials=holders=null}var data=!isBindKey&&getData(func),newData=[func,bitmask,thisArg,partials,holders,partialsRight,holdersRight,argPos,ary,arity];if(data&&data!==true){mergeData(newData,data);bitmask=newData[1];arity=newData[9]}newData[9]=arity==null?isBindKey?0:func.length:nativeMax(arity-length,0)||0;if(bitmask==BIND_FLAG){var result=createBindWrapper(newData[0],newData[2])}else if((bitmask==PARTIAL_FLAG||bitmask==(BIND_FLAG|PARTIAL_FLAG))&&!newData[4].length){result=createPartialWrapper.apply(null,newData)}else{result=createHybridWrapper.apply(null,newData)}var setter=data?baseSetData:setData;return setter(result,newData)}function equalArrays(array,other,equalFunc,customizer,isWhere,stackA,stackB){var index=-1,arrLength=array.length,othLength=other.length,result=true;if(arrLength!=othLength&&!(isWhere&&othLength>arrLength)){return false}while(result&&++index<arrLength){var arrValue=array[index],othValue=other[index];result=undefined;if(customizer){result=isWhere?customizer(othValue,arrValue,index):customizer(arrValue,othValue,index)}if(typeof result=="undefined"){if(isWhere){var othIndex=othLength;while(othIndex--){othValue=other[othIndex];result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isWhere,stackA,stackB);if(result){break}}}else{result=arrValue&&arrValue===othValue||equalFunc(arrValue,othValue,customizer,isWhere,stackA,stackB)}}}return!!result}function equalByTag(object,other,tag){switch(tag){case boolTag:case dateTag:return+object==+other;case errorTag:return object.name==other.name&&object.message==other.message;case numberTag:return object!=+object?other!=+other:object==0?1/object==1/other:object==+other;case regexpTag:case stringTag:return object==baseToString(other)}return false}function equalObjects(object,other,equalFunc,customizer,isWhere,stackA,stackB){var objProps=keys(object),objLength=objProps.length,othProps=keys(other),othLength=othProps.length;if(objLength!=othLength&&!isWhere){return false}var hasCtor,index=-1;while(++index<objLength){var key=objProps[index],result=hasOwnProperty.call(other,key);if(result){var objValue=object[key],othValue=other[key];result=undefined;if(customizer){result=isWhere?customizer(othValue,objValue,key):customizer(objValue,othValue,key)}if(typeof result=="undefined"){result=objValue&&objValue===othValue||equalFunc(objValue,othValue,customizer,isWhere,stackA,stackB)}}if(!result){return false}hasCtor||(hasCtor=key=="constructor")}if(!hasCtor){var objCtor=object.constructor,othCtor=other.constructor;if(objCtor!=othCtor&&("constructor"in object&&"constructor"in other)&&!(typeof objCtor=="function"&&objCtor instanceof objCtor&&typeof othCtor=="function"&&othCtor instanceof othCtor)){return false}}return true}function extremumBy(collection,iteratee,isMin){var exValue=isMin?POSITIVE_INFINITY:NEGATIVE_INFINITY,computed=exValue,result=computed;baseEach(collection,function(value,index,collection){var current=iteratee(value,index,collection);if((isMin?current<computed:current>computed)||current===exValue&¤t===result){computed=current;result=value}});return result}function getCallback(func,thisArg,argCount){var result=lodash.callback||callback;result=result===callback?baseCallback:result;return argCount?result(func,thisArg,argCount):result}var getData=!metaMap?noop:function(func){return metaMap.get(func)};function getIndexOf(collection,target,fromIndex){var result=lodash.indexOf||indexOf;result=result===indexOf?baseIndexOf:result;return collection?result(collection,target,fromIndex):result}function getView(start,end,transforms){var index=-1,length=transforms?transforms.length:0;while(++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);break}}return{start:start,end:end}}function initCloneArray(array){var length=array.length,result=new array.constructor(length);if(length&&typeof array[0]=="string"&&hasOwnProperty.call(array,"index")){result.index=array.index;result.input=array.input}return result}function initCloneObject(object){var Ctor=object.constructor;if(!(typeof Ctor=="function"&&Ctor instanceof Ctor)){Ctor=Object}return new Ctor}function initCloneByTag(object,tag,isDeep){var Ctor=object.constructor;switch(tag){case arrayBufferTag:return bufferClone(object);case boolTag:case dateTag:return new Ctor(+object);case float32Tag:case float64Tag:case int8Tag:case int16Tag:case int32Tag:case uint8Tag:case uint8ClampedTag:case uint16Tag:case uint32Tag:var buffer=object.buffer;return new Ctor(isDeep?bufferClone(buffer):buffer,object.byteOffset,object.length);case numberTag:case stringTag:return new Ctor(object);case regexpTag:var result=new Ctor(object.source,reFlags.exec(object));result.lastIndex=object.lastIndex}return result}function isBindable(func){var support=lodash.support,result=!(support.funcNames?func.name:support.funcDecomp);if(!result){var source=fnToString.call(func);if(!support.funcNames){result=!reFuncName.test(source)}if(!result){result=reThis.test(source)||isNative(func);baseSetData(func,result)}}return result}function isIndex(value,length){value=+value;length=length==null?MAX_SAFE_INTEGER:length;return value>-1&&value%1==0&&value<length}function isIterateeCall(value,index,object){if(!isObject(object)){return false}var type=typeof index;if(type=="number"){var length=object.length,prereq=isLength(length)&&isIndex(index,length)}else{prereq=type=="string"&&index in value}return prereq&&object[index]===value}function isLength(value){return typeof value=="number"&&value>-1&&value%1==0&&value<=MAX_SAFE_INTEGER}function isStrictComparable(value){return value===value&&(value===0?1/value>0:!isObject(value))}function mergeData(data,source){var bitmask=data[1],srcBitmask=source[1],newBitmask=bitmask|srcBitmask;var arityFlags=ARY_FLAG|REARG_FLAG,bindFlags=BIND_FLAG|BIND_KEY_FLAG,comboFlags=arityFlags|bindFlags|CURRY_BOUND_FLAG|CURRY_RIGHT_FLAG;var isAry=bitmask&ARY_FLAG&&!(srcBitmask&ARY_FLAG),isRearg=bitmask&REARG_FLAG&&!(srcBitmask&REARG_FLAG),argPos=(isRearg?data:source)[7],ary=(isAry?data:source)[8];var isCommon=!(bitmask>=REARG_FLAG&&srcBitmask>bindFlags)&&!(bitmask>bindFlags&&srcBitmask>=REARG_FLAG);var isCombo=newBitmask>=arityFlags&&newBitmask<=comboFlags&&(bitmask<REARG_FLAG||(isRearg||isAry)&&argPos.length<=ary);if(!(isCommon||isCombo)){return data}if(srcBitmask&BIND_FLAG){data[2]=source[2];newBitmask|=bitmask&BIND_FLAG?0:CURRY_BOUND_FLAG}var value=source[3];if(value){var partials=data[3];data[3]=partials?composeArgs(partials,value,source[4]):arrayCopy(value);data[4]=partials?replaceHolders(data[3],PLACEHOLDER):arrayCopy(source[4])}value=source[5];if(value){partials=data[5];data[5]=partials?composeArgsRight(partials,value,source[6]):arrayCopy(value);data[6]=partials?replaceHolders(data[5],PLACEHOLDER):arrayCopy(source[6])}value=source[7];if(value){data[7]=arrayCopy(value)}if(srcBitmask&ARY_FLAG){data[8]=data[8]==null?source[8]:nativeMin(data[8],source[8])}if(data[9]==null){data[9]=source[9]}data[0]=source[0];data[1]=newBitmask;return data}function pickByArray(object,props){object=toObject(object);var index=-1,length=props.length,result={};while(++index<length){var key=props[index];if(key in object){result[key]=object[key]}}return result}function pickByCallback(object,predicate){var result={};baseForIn(object,function(value,key,object){if(predicate(value,key,object)){result[key]=value}});return result}function reorder(array,indexes){var arrLength=array.length,length=nativeMin(indexes.length,arrLength),oldArray=arrayCopy(array);while(length--){var index=indexes[length];array[length]=isIndex(index,arrLength)?oldArray[index]:undefined}return array}var setData=function(){var count=0,lastCalled=0;return function(key,value){var stamp=now(),remaining=HOT_SPAN-(stamp-lastCalled);lastCalled=stamp;if(remaining>0){if(++count>=HOT_COUNT){return key}}else{count=0}return baseSetData(key,value)}}();function shimIsPlainObject(value){var Ctor,support=lodash.support;if(!(isObjectLike(value)&&objToString.call(value)==objectTag)||!hasOwnProperty.call(value,"constructor")&&(Ctor=value.constructor,typeof Ctor=="function"&&!(Ctor instanceof Ctor))){return false}var result;baseForIn(value,function(subValue,key){result=key});return typeof result=="undefined"||hasOwnProperty.call(value,result)}function shimKeys(object){var props=keysIn(object),propsLength=props.length,length=propsLength&&object.length,support=lodash.support;var allowIndexes=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object));var index=-1,result=[];while(++index<propsLength){var key=props[index];if(allowIndexes&&isIndex(key,length)||hasOwnProperty.call(object,key)){result.push(key)}}return result}function toIterable(value){if(value==null){return[]}if(!isLength(value.length)){return values(value)}return isObject(value)?value:Object(value)}function toObject(value){return isObject(value)?value:Object(value)}function chunk(array,size,guard){if(guard?isIterateeCall(array,size,guard):size==null){size=1}else{size=nativeMax(+size||1,1)}var index=0,length=array?array.length:0,resIndex=-1,result=Array(ceil(length/size));while(index<length){result[++resIndex]=baseSlice(array,index,index+=size)}return result}function compact(array){var index=-1,length=array?array.length:0,resIndex=-1,result=[];while(++index<length){var value=array[index];if(value){result[++resIndex]=value}}return result}function difference(){var index=-1,length=arguments.length;while(++index<length){var value=arguments[index];if(isArray(value)||isArguments(value)){break}}return baseDifference(value,baseFlatten(arguments,false,true,++index))}function drop(array,n,guard){var length=array?array.length:0;if(!length){return[]}if(guard?isIterateeCall(array,n,guard):n==null){n=1}return baseSlice(array,n<0?0:n)}function dropRight(array,n,guard){var length=array?array.length:0;if(!length){return[]}if(guard?isIterateeCall(array,n,guard):n==null){n=1}n=length-(+n||0);return baseSlice(array,0,n<0?0:n)}function dropRightWhile(array,predicate,thisArg){var length=array?array.length:0;if(!length){return[]}predicate=getCallback(predicate,thisArg,3);while(length--&&predicate(array[length],length,array)){}return baseSlice(array,0,length+1)}function dropWhile(array,predicate,thisArg){var length=array?array.length:0;if(!length){return[]}var index=-1;predicate=getCallback(predicate,thisArg,3);while(++index<length&&predicate(array[index],index,array)){}return baseSlice(array,index)}function findIndex(array,predicate,thisArg){var index=-1,length=array?array.length:0;predicate=getCallback(predicate,thisArg,3);while(++index<length){if(predicate(array[index],index,array)){return index}}return-1}function findLastIndex(array,predicate,thisArg){var length=array?array.length:0;predicate=getCallback(predicate,thisArg,3);while(length--){if(predicate(array[length],length,array)){return length}}return-1}function first(array){return array?array[0]:undefined}function flatten(array,isDeep,guard){var length=array?array.length:0;if(guard&&isIterateeCall(array,isDeep,guard)){isDeep=false}return length?baseFlatten(array,isDeep):[]}function flattenDeep(array){var length=array?array.length:0;return length?baseFlatten(array,true):[]}function indexOf(array,value,fromIndex){var length=array?array.length:0;if(!length){return-1}if(typeof fromIndex=="number"){fromIndex=fromIndex<0?nativeMax(length+fromIndex,0):fromIndex||0}else if(fromIndex){var index=binaryIndex(array,value),other=array[index];return(value===value?value===other:other!==other)?index:-1}return baseIndexOf(array,value,fromIndex)}function initial(array){return dropRight(array,1)}function intersection(){var args=[],argsIndex=-1,argsLength=arguments.length,caches=[],indexOf=getIndexOf(),isCommon=indexOf==baseIndexOf;while(++argsIndex<argsLength){var value=arguments[argsIndex];if(isArray(value)||isArguments(value)){args.push(value);caches.push(isCommon&&value.length>=120&&createCache(argsIndex&&value))}}argsLength=args.length;var array=args[0],index=-1,length=array?array.length:0,result=[],seen=caches[0];outer:while(++index<length){value=array[index];if((seen?cacheIndexOf(seen,value):indexOf(result,value))<0){argsIndex=argsLength;while(--argsIndex){var cache=caches[argsIndex];if((cache?cacheIndexOf(cache,value):indexOf(args[argsIndex],value))<0){continue outer}}if(seen){seen.push(value)}result.push(value)}}return result}function last(array){var length=array?array.length:0;return length?array[length-1]:undefined}function lastIndexOf(array,value,fromIndex){var length=array?array.length:0;if(!length){return-1}var index=length;if(typeof fromIndex=="number"){index=(fromIndex<0?nativeMax(length+fromIndex,0):nativeMin(fromIndex||0,length-1))+1}else if(fromIndex){index=binaryIndex(array,value,true)-1;var other=array[index];return(value===value?value===other:other!==other)?index:-1}if(value!==value){return indexOfNaN(array,index,true)}while(index--){if(array[index]===value){return index}}return-1}function pull(){var array=arguments[0];if(!(array&&array.length)){return array}var index=0,indexOf=getIndexOf(),length=arguments.length;while(++index<length){var fromIndex=0,value=arguments[index];while((fromIndex=indexOf(array,value,fromIndex))>-1){splice.call(array,fromIndex,1)}}return array}function pullAt(array){return basePullAt(array||[],baseFlatten(arguments,false,false,1))}function remove(array,predicate,thisArg){var index=-1,length=array?array.length:0,result=[];predicate=getCallback(predicate,thisArg,3);while(++index<length){var value=array[index];if(predicate(value,index,array)){result.push(value);splice.call(array,index--,1);length--}}return result}function rest(array){return drop(array,1)}function slice(array,start,end){var length=array?array.length:0;if(!length){return[]}if(end&&typeof end!="number"&&isIterateeCall(array,start,end)){start=0;end=length}return baseSlice(array,start,end)}function sortedIndex(array,value,iteratee,thisArg){var func=getCallback(iteratee);return func===baseCallback&&iteratee==null?binaryIndex(array,value):binaryIndexBy(array,value,func(iteratee,thisArg,1))}function sortedLastIndex(array,value,iteratee,thisArg){var func=getCallback(iteratee);return func===baseCallback&&iteratee==null?binaryIndex(array,value,true):binaryIndexBy(array,value,func(iteratee,thisArg,1),true)}function take(array,n,guard){var length=array?array.length:0;if(!length){return[]}if(guard?isIterateeCall(array,n,guard):n==null){n=1}return baseSlice(array,0,n<0?0:n)}function takeRight(array,n,guard){var length=array?array.length:0;if(!length){return[]}if(guard?isIterateeCall(array,n,guard):n==null){n=1}n=length-(+n||0);return baseSlice(array,n<0?0:n)}function takeRightWhile(array,predicate,thisArg){var length=array?array.length:0;if(!length){return[]}predicate=getCallback(predicate,thisArg,3);while(length--&&predicate(array[length],length,array)){}return baseSlice(array,length+1)}function takeWhile(array,predicate,thisArg){var length=array?array.length:0;if(!length){return[]}var index=-1;predicate=getCallback(predicate,thisArg,3);while(++index<length&&predicate(array[index],index,array)){}return baseSlice(array,0,index)}function union(){return baseUniq(baseFlatten(arguments,false,true))}function uniq(array,isSorted,iteratee,thisArg){var length=array?array.length:0;if(!length){return[]}if(typeof isSorted!="boolean"&&isSorted!=null){thisArg=iteratee;iteratee=isIterateeCall(array,isSorted,thisArg)?null:isSorted;isSorted=false}var func=getCallback();if(!(func===baseCallback&&iteratee==null)){iteratee=func(iteratee,thisArg,3)}return isSorted&&getIndexOf()==baseIndexOf?sortedUniq(array,iteratee):baseUniq(array,iteratee)}function unzip(array){var index=-1,length=(array&&array.length&&arrayMax(arrayMap(array,getLength)))>>>0,result=Array(length);while(++index<length){result[index]=arrayMap(array,baseProperty(index))}return result}function without(array){return baseDifference(array,baseSlice(arguments,1))}function xor(){var index=-1,length=arguments.length;while(++index<length){var array=arguments[index];if(isArray(array)||isArguments(array)){var result=result?baseDifference(result,array).concat(baseDifference(array,result)):array}}return result?baseUniq(result):[]}function zip(){var length=arguments.length,array=Array(length);while(length--){array[length]=arguments[length]}return unzip(array)}function zipObject(props,values){var index=-1,length=props?props.length:0,result={};if(length&&!values&&!isArray(props[0])){values=[]}while(++index<length){var key=props[index];if(values){result[key]=values[index]}else if(key){result[key[0]]=key[1]}}return result}function chain(value){var result=lodash(value);result.__chain__=true;return result}function tap(value,interceptor,thisArg){interceptor.call(thisArg,value);return value}function thru(value,interceptor,thisArg){return interceptor.call(thisArg,value)}function wrapperChain(){return chain(this)}function wrapperReverse(){var value=this.__wrapped__;if(value instanceof LazyWrapper){return new LodashWrapper(value.reverse())}return this.thru(function(value){return value.reverse()})}function wrapperToString(){return this.value()+""}function wrapperValue(){return baseWrapperValue(this.__wrapped__,this.__actions__)}function at(collection){var length=collection?collection.length:0;if(isLength(length)){collection=toIterable(collection)}return baseAt(collection,baseFlatten(arguments,false,false,1))}function includes(collection,target,fromIndex){var length=collection?collection.length:0;if(!isLength(length)){collection=values(collection);length=collection.length}if(!length){return false}if(typeof fromIndex=="number"){fromIndex=fromIndex<0?nativeMax(length+fromIndex,0):fromIndex||0}else{fromIndex=0}return typeof collection=="string"||!isArray(collection)&&isString(collection)?fromIndex<length&&collection.indexOf(target,fromIndex)>-1:getIndexOf(collection,target,fromIndex)>-1}var countBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?++result[key]:result[key]=1});function every(collection,predicate,thisArg){var func=isArray(collection)?arrayEvery:baseEvery;if(typeof predicate!="function"||typeof thisArg!="undefined"){predicate=getCallback(predicate,thisArg,3)}return func(collection,predicate)}function filter(collection,predicate,thisArg){var func=isArray(collection)?arrayFilter:baseFilter;predicate=getCallback(predicate,thisArg,3);return func(collection,predicate)}function find(collection,predicate,thisArg){if(isArray(collection)){var index=findIndex(collection,predicate,thisArg);return index>-1?collection[index]:undefined}predicate=getCallback(predicate,thisArg,3);return baseFind(collection,predicate,baseEach)}function findLast(collection,predicate,thisArg){predicate=getCallback(predicate,thisArg,3);return baseFind(collection,predicate,baseEachRight)}function findWhere(collection,source){return find(collection,matches(source))}function forEach(collection,iteratee,thisArg){return typeof iteratee=="function"&&typeof thisArg=="undefined"&&isArray(collection)?arrayEach(collection,iteratee):baseEach(collection,bindCallback(iteratee,thisArg,3))}function forEachRight(collection,iteratee,thisArg){return typeof iteratee=="function"&&typeof thisArg=="undefined"&&isArray(collection)?arrayEachRight(collection,iteratee):baseEachRight(collection,bindCallback(iteratee,thisArg,3))}var groupBy=createAggregator(function(result,value,key){if(hasOwnProperty.call(result,key)){result[key].push(value)}else{result[key]=[value]}});var indexBy=createAggregator(function(result,value,key){result[key]=value});function invoke(collection,methodName){return baseInvoke(collection,methodName,baseSlice(arguments,2))}function map(collection,iteratee,thisArg){var func=isArray(collection)?arrayMap:baseMap;iteratee=getCallback(iteratee,thisArg,3);return func(collection,iteratee)}var max=createExtremum(arrayMax);var min=createExtremum(arrayMin,true);var partition=createAggregator(function(result,value,key){result[key?0:1].push(value)},function(){return[[],[]]});function pluck(collection,key){return map(collection,property(key))}function reduce(collection,iteratee,accumulator,thisArg){var func=isArray(collection)?arrayReduce:baseReduce;return func(collection,getCallback(iteratee,thisArg,4),accumulator,arguments.length<3,baseEach)}function reduceRight(collection,iteratee,accumulator,thisArg){var func=isArray(collection)?arrayReduceRight:baseReduce;return func(collection,getCallback(iteratee,thisArg,4),accumulator,arguments.length<3,baseEachRight)}function reject(collection,predicate,thisArg){var func=isArray(collection)?arrayFilter:baseFilter;predicate=getCallback(predicate,thisArg,3);return func(collection,function(value,index,collection){return!predicate(value,index,collection)})}function sample(collection,n,guard){if(guard?isIterateeCall(collection,n,guard):n==null){collection=toIterable(collection);var length=collection.length;return length>0?collection[baseRandom(0,length-1)]:undefined}var result=shuffle(collection);result.length=nativeMin(n<0?0:+n||0,result.length);return result}function shuffle(collection){collection=toIterable(collection);var index=-1,length=collection.length,result=Array(length);while(++index<length){var rand=baseRandom(0,index);if(index!=rand){result[index]=result[rand]}result[rand]=collection[index]}return result}function size(collection){var length=collection?collection.length:0;return isLength(length)?length:keys(collection).length}function some(collection,predicate,thisArg){var func=isArray(collection)?arraySome:baseSome;if(typeof predicate!="function"||typeof thisArg!="undefined"){predicate=getCallback(predicate,thisArg,3)}return func(collection,predicate)}function sortBy(collection,iteratee,thisArg){var index=-1,length=collection?collection.length:0,result=isLength(length)?Array(length):[];if(thisArg&&isIterateeCall(collection,iteratee,thisArg)){iteratee=null}iteratee=getCallback(iteratee,thisArg,3);baseEach(collection,function(value,key,collection){result[++index]={criteria:iteratee(value,key,collection),index:index,value:value}});return baseSortBy(result,compareAscending)}function sortByAll(collection){var args=arguments;if(args.length>3&&isIterateeCall(args[1],args[2],args[3])){args=[collection,args[1]]}var index=-1,length=collection?collection.length:0,props=baseFlatten(args,false,false,1),result=isLength(length)?Array(length):[];baseEach(collection,function(value,key,collection){var length=props.length,criteria=Array(length);while(length--){criteria[length]=value==null?undefined:value[props[length]]}result[++index]={criteria:criteria,index:index,value:value}});return baseSortBy(result,compareMultipleAscending)}function where(collection,source){return filter(collection,matches(source))}var now=nativeNow||function(){return(new Date).getTime()};function after(n,func){if(!isFunction(func)){if(isFunction(n)){var temp=n;n=func;func=temp}else{throw new TypeError(FUNC_ERROR_TEXT)}}n=nativeIsFinite(n=+n)?n:0;return function(){if(--n<1){return func.apply(this,arguments)}}}function ary(func,n,guard){if(guard&&isIterateeCall(func,n,guard)){n=null}n=func&&n==null?func.length:nativeMax(+n||0,0);return createWrapper(func,ARY_FLAG,null,null,null,null,n)}function before(n,func){var result;if(!isFunction(func)){if(isFunction(n)){var temp=n;n=func;func=temp}else{throw new TypeError(FUNC_ERROR_TEXT)}}return function(){if(--n>0){result=func.apply(this,arguments)}else{func=null}return result}}function bind(func,thisArg){var bitmask=BIND_FLAG;if(arguments.length>2){var partials=baseSlice(arguments,2),holders=replaceHolders(partials,bind.placeholder);bitmask|=PARTIAL_FLAG}return createWrapper(func,bitmask,thisArg,partials,holders)}function bindAll(object){return baseBindAll(object,arguments.length>1?baseFlatten(arguments,false,false,1):functions(object))}function bindKey(object,key){var bitmask=BIND_FLAG|BIND_KEY_FLAG;if(arguments.length>2){var partials=baseSlice(arguments,2),holders=replaceHolders(partials,bindKey.placeholder);bitmask|=PARTIAL_FLAG}return createWrapper(key,bitmask,object,partials,holders)}function curry(func,arity,guard){if(guard&&isIterateeCall(func,arity,guard)){arity=null}var result=createWrapper(func,CURRY_FLAG,null,null,null,null,null,arity);result.placeholder=curry.placeholder;return result}function curryRight(func,arity,guard){if(guard&&isIterateeCall(func,arity,guard)){arity=null}var result=createWrapper(func,CURRY_RIGHT_FLAG,null,null,null,null,null,arity);result.placeholder=curryRight.placeholder;return result}function debounce(func,wait,options){var args,maxTimeoutId,result,stamp,thisArg,timeoutId,trailingCall,lastCalled=0,maxWait=false,trailing=true;if(!isFunction(func)){throw new TypeError(FUNC_ERROR_TEXT)}wait=wait<0?0:wait;if(options===true){var leading=true;trailing=false}else if(isObject(options)){leading=options.leading;maxWait="maxWait"in options&&nativeMax(+options.maxWait||0,wait);trailing="trailing"in options?options.trailing:trailing}function cancel(){if(timeoutId){clearTimeout(timeoutId)}if(maxTimeoutId){clearTimeout(maxTimeoutId)}maxTimeoutId=timeoutId=trailingCall=undefined}function delayed(){var remaining=wait-(now()-stamp);if(remaining<=0||remaining>wait){if(maxTimeoutId){clearTimeout(maxTimeoutId)}var isCalled=trailingCall;maxTimeoutId=timeoutId=trailingCall=undefined;if(isCalled){lastCalled=now();result=func.apply(thisArg,args);if(!timeoutId&&!maxTimeoutId){args=thisArg=null}}}else{timeoutId=setTimeout(delayed,remaining)}}function maxDelayed(){if(timeoutId){clearTimeout(timeoutId)}maxTimeoutId=timeoutId=trailingCall=undefined;if(trailing||maxWait!==wait){lastCalled=now();result=func.apply(thisArg,args);if(!timeoutId&&!maxTimeoutId){args=thisArg=null}}}function debounced(){args=arguments;stamp=now();thisArg=this;trailingCall=trailing&&(timeoutId||!leading);if(maxWait===false){var leadingCall=leading&&!timeoutId}else{if(!maxTimeoutId&&!leading){lastCalled=stamp}var remaining=maxWait-(stamp-lastCalled),isCalled=remaining<=0||remaining>maxWait;if(isCalled){if(maxTimeoutId){maxTimeoutId=clearTimeout(maxTimeoutId)}lastCalled=stamp;result=func.apply(thisArg,args)}else if(!maxTimeoutId){maxTimeoutId=setTimeout(maxDelayed,remaining)}}if(isCalled&&timeoutId){timeoutId=clearTimeout(timeoutId)}else if(!timeoutId&&wait!==maxWait){timeoutId=setTimeout(delayed,wait)}if(leadingCall){isCalled=true;result=func.apply(thisArg,args)}if(isCalled&&!timeoutId&&!maxTimeoutId){args=thisArg=null}return result}debounced.cancel=cancel;return debounced}function defer(func){return baseDelay(func,1,arguments,1)}function delay(func,wait){return baseDelay(func,wait,arguments,2)}function flow(){var funcs=arguments,length=funcs.length;if(!length){return function(){}}if(!arrayEvery(funcs,isFunction)){throw new TypeError(FUNC_ERROR_TEXT)}return function(){var index=0,result=funcs[index].apply(this,arguments);while(++index<length){result=funcs[index].call(this,result)}return result}}function flowRight(){var funcs=arguments,fromIndex=funcs.length-1;if(fromIndex<0){return function(){}}if(!arrayEvery(funcs,isFunction)){throw new TypeError(FUNC_ERROR_TEXT)}return function(){var index=fromIndex,result=funcs[index].apply(this,arguments);while(index--){result=funcs[index].call(this,result)}return result}}function memoize(func,resolver){if(!isFunction(func)||resolver&&!isFunction(resolver)){throw new TypeError(FUNC_ERROR_TEXT)}var memoized=function(){var cache=memoized.cache,key=resolver?resolver.apply(this,arguments):arguments[0];if(cache.has(key)){return cache.get(key)}var result=func.apply(this,arguments);cache.set(key,result);return result};memoized.cache=new memoize.Cache;return memoized}function negate(predicate){if(!isFunction(predicate)){throw new TypeError(FUNC_ERROR_TEXT)}return function(){return!predicate.apply(this,arguments)}}function once(func){return before(func,2)}function partial(func){var partials=baseSlice(arguments,1),holders=replaceHolders(partials,partial.placeholder);return createWrapper(func,PARTIAL_FLAG,null,partials,holders)}function partialRight(func){var partials=baseSlice(arguments,1),holders=replaceHolders(partials,partialRight.placeholder);return createWrapper(func,PARTIAL_RIGHT_FLAG,null,partials,holders)
}function rearg(func){var indexes=baseFlatten(arguments,false,false,1);return createWrapper(func,REARG_FLAG,null,null,null,indexes)}function throttle(func,wait,options){var leading=true,trailing=true;if(!isFunction(func)){throw new TypeError(FUNC_ERROR_TEXT)}if(options===false){leading=false}else if(isObject(options)){leading="leading"in options?!!options.leading:leading;trailing="trailing"in options?!!options.trailing:trailing}debounceOptions.leading=leading;debounceOptions.maxWait=+wait;debounceOptions.trailing=trailing;return debounce(func,wait,debounceOptions)}function wrap(value,wrapper){wrapper=wrapper==null?identity:wrapper;return createWrapper(wrapper,PARTIAL_FLAG,null,[value],[])}function clone(value,isDeep,customizer,thisArg){if(typeof isDeep!="boolean"&&isDeep!=null){thisArg=customizer;customizer=isIterateeCall(value,isDeep,thisArg)?null:isDeep;isDeep=false}customizer=typeof customizer=="function"&&bindCallback(customizer,thisArg,1);return baseClone(value,isDeep,customizer)}function cloneDeep(value,customizer,thisArg){customizer=typeof customizer=="function"&&bindCallback(customizer,thisArg,1);return baseClone(value,true,customizer)}function isArguments(value){var length=isObjectLike(value)?value.length:undefined;return isLength(length)&&objToString.call(value)==argsTag||false}var isArray=nativeIsArray||function(value){return isObjectLike(value)&&isLength(value.length)&&objToString.call(value)==arrayTag||false};function isBoolean(value){return value===true||value===false||isObjectLike(value)&&objToString.call(value)==boolTag||false}function isDate(value){return isObjectLike(value)&&objToString.call(value)==dateTag||false}function isElement(value){return value&&value.nodeType===1&&isObjectLike(value)&&objToString.call(value).indexOf("Element")>-1||false}if(!support.dom){isElement=function(value){return value&&value.nodeType===1&&isObjectLike(value)&&!isPlainObject(value)||false}}function isEmpty(value){if(value==null){return true}var length=value.length;if(isLength(length)&&(isArray(value)||isString(value)||isArguments(value)||isObjectLike(value)&&isFunction(value.splice))){return!length}return!keys(value).length}function isEqual(value,other,customizer,thisArg){customizer=typeof customizer=="function"&&bindCallback(customizer,thisArg,3);if(!customizer&&isStrictComparable(value)&&isStrictComparable(other)){return value===other}var result=customizer?customizer(value,other):undefined;return typeof result=="undefined"?baseIsEqual(value,other,customizer):!!result}function isError(value){return isObjectLike(value)&&typeof value.message=="string"&&objToString.call(value)==errorTag||false}var isFinite=nativeNumIsFinite||function(value){return typeof value=="number"&&nativeIsFinite(value)};function isFunction(value){return typeof value=="function"||false}if(isFunction(/x/)||Uint8Array&&!isFunction(Uint8Array)){isFunction=function(value){return objToString.call(value)==funcTag}}function isObject(value){var type=typeof value;return type=="function"||value&&type=="object"||false}function isMatch(object,source,customizer,thisArg){var props=keys(source),length=props.length;customizer=typeof customizer=="function"&&bindCallback(customizer,thisArg,3);if(!customizer&&length==1){var key=props[0],value=source[key];if(isStrictComparable(value)){return object!=null&&value===object[key]&&hasOwnProperty.call(object,key)}}var values=Array(length),strictCompareFlags=Array(length);while(length--){value=values[length]=source[props[length]];strictCompareFlags[length]=isStrictComparable(value)}return baseIsMatch(object,props,values,strictCompareFlags,customizer)}function isNaN(value){return isNumber(value)&&value!=+value}function isNative(value){if(value==null){return false}if(objToString.call(value)==funcTag){return reNative.test(fnToString.call(value))}return isObjectLike(value)&&reHostCtor.test(value)||false}function isNull(value){return value===null}function isNumber(value){return typeof value=="number"||isObjectLike(value)&&objToString.call(value)==numberTag||false}var isPlainObject=!getPrototypeOf?shimIsPlainObject:function(value){if(!(value&&objToString.call(value)==objectTag)){return false}var valueOf=value.valueOf,objProto=isNative(valueOf)&&(objProto=getPrototypeOf(valueOf))&&getPrototypeOf(objProto);return objProto?value==objProto||getPrototypeOf(value)==objProto:shimIsPlainObject(value)};function isRegExp(value){return isObjectLike(value)&&objToString.call(value)==regexpTag||false}function isString(value){return typeof value=="string"||isObjectLike(value)&&objToString.call(value)==stringTag||false}function isTypedArray(value){return isObjectLike(value)&&isLength(value.length)&&typedArrayTags[objToString.call(value)]||false}function isUndefined(value){return typeof value=="undefined"}function toArray(value){var length=value?value.length:0;if(!isLength(length)){return values(value)}if(!length){return[]}return arrayCopy(value)}function toPlainObject(value){return baseCopy(value,keysIn(value))}var assign=createAssigner(baseAssign);function create(prototype,properties,guard){var result=baseCreate(prototype);if(guard&&isIterateeCall(prototype,properties,guard)){properties=null}return properties?baseCopy(properties,result,keys(properties)):result}function defaults(object){if(object==null){return object}var args=arrayCopy(arguments);args.push(assignDefaults);return assign.apply(undefined,args)}function findKey(object,predicate,thisArg){predicate=getCallback(predicate,thisArg,3);return baseFind(object,predicate,baseForOwn,true)}function findLastKey(object,predicate,thisArg){predicate=getCallback(predicate,thisArg,3);return baseFind(object,predicate,baseForOwnRight,true)}function forIn(object,iteratee,thisArg){if(typeof iteratee!="function"||typeof thisArg!="undefined"){iteratee=bindCallback(iteratee,thisArg,3)}return baseFor(object,iteratee,keysIn)}function forInRight(object,iteratee,thisArg){iteratee=bindCallback(iteratee,thisArg,3);return baseForRight(object,iteratee,keysIn)}function forOwn(object,iteratee,thisArg){if(typeof iteratee!="function"||typeof thisArg!="undefined"){iteratee=bindCallback(iteratee,thisArg,3)}return baseForOwn(object,iteratee)}function forOwnRight(object,iteratee,thisArg){iteratee=bindCallback(iteratee,thisArg,3);return baseForRight(object,iteratee,keys)}function functions(object){return baseFunctions(object,keysIn(object))}function has(object,key){return object?hasOwnProperty.call(object,key):false}function invert(object,multiValue,guard){if(guard&&isIterateeCall(object,multiValue,guard)){multiValue=null}var index=-1,props=keys(object),length=props.length,result={};while(++index<length){var key=props[index],value=object[key];if(multiValue){if(hasOwnProperty.call(result,value)){result[value].push(key)}else{result[value]=[key]}}else{result[value]=key}}return result}var keys=!nativeKeys?shimKeys:function(object){if(object){var Ctor=object.constructor,length=object.length}if(typeof Ctor=="function"&&Ctor.prototype===object||typeof object!="function"&&(length&&isLength(length))){return shimKeys(object)}return isObject(object)?nativeKeys(object):[]};function keysIn(object){if(object==null){return[]}if(!isObject(object)){object=Object(object)}var length=object.length;length=length&&isLength(length)&&(isArray(object)||support.nonEnumArgs&&isArguments(object))&&length||0;var Ctor=object.constructor,index=-1,isProto=typeof Ctor=="function"&&Ctor.prototype==object,result=Array(length),skipIndexes=length>0;while(++index<length){result[index]=index+""}for(var key in object){if(!(skipIndexes&&isIndex(key,length))&&!(key=="constructor"&&(isProto||!hasOwnProperty.call(object,key)))){result.push(key)}}return result}function mapValues(object,iteratee,thisArg){var result={};iteratee=getCallback(iteratee,thisArg,3);baseForOwn(object,function(value,key,object){result[key]=iteratee(value,key,object)});return result}var merge=createAssigner(baseMerge);function omit(object,predicate,thisArg){if(object==null){return{}}if(typeof predicate!="function"){var props=arrayMap(baseFlatten(arguments,false,false,1),String);return pickByArray(object,baseDifference(keysIn(object),props))}predicate=bindCallback(predicate,thisArg,3);return pickByCallback(object,function(value,key,object){return!predicate(value,key,object)})}function pairs(object){var index=-1,props=keys(object),length=props.length,result=Array(length);while(++index<length){var key=props[index];result[index]=[key,object[key]]}return result}function pick(object,predicate,thisArg){if(object==null){return{}}return typeof predicate=="function"?pickByCallback(object,bindCallback(predicate,thisArg,3)):pickByArray(object,baseFlatten(arguments,false,false,1))}function result(object,key,defaultValue){var value=object==null?undefined:object[key];if(typeof value=="undefined"){value=defaultValue}return isFunction(value)?value.call(object):value}function transform(object,iteratee,accumulator,thisArg){var isArr=isArray(object)||isTypedArray(object);iteratee=getCallback(iteratee,thisArg,4);if(accumulator==null){if(isArr||isObject(object)){var Ctor=object.constructor;if(isArr){accumulator=isArray(object)?new Ctor:[]}else{accumulator=baseCreate(typeof Ctor=="function"&&Ctor.prototype)}}else{accumulator={}}}(isArr?arrayEach:baseForOwn)(object,function(value,index,object){return iteratee(accumulator,value,index,object)});return accumulator}function values(object){return baseValues(object,keys(object))}function valuesIn(object){return baseValues(object,keysIn(object))}function random(min,max,floating){if(floating&&isIterateeCall(min,max,floating)){max=floating=null}var noMin=min==null,noMax=max==null;if(floating==null){if(noMax&&typeof min=="boolean"){floating=min;min=1}else if(typeof max=="boolean"){floating=max;noMax=true}}if(noMin&&noMax){max=1;noMax=false}min=+min||0;if(noMax){max=min;min=0}else{max=+max||0}if(floating||min%1||max%1){var rand=nativeRandom();return nativeMin(min+rand*(max-min+parseFloat("1e-"+((rand+"").length-1))),max)}return baseRandom(min,max)}var camelCase=createCompounder(function(result,word,index){word=word.toLowerCase();return index?result+word.charAt(0).toUpperCase()+word.slice(1):word});function capitalize(string){string=baseToString(string);return string&&string.charAt(0).toUpperCase()+string.slice(1)}function deburr(string){string=baseToString(string);return string&&string.replace(reLatin1,deburrLetter)}function endsWith(string,target,position){string=baseToString(string);target=target+"";var length=string.length;position=(typeof position=="undefined"?length:nativeMin(position<0?0:+position||0,length))-target.length;return position>=0&&string.indexOf(target,position)==position}function escape(string){string=baseToString(string);return string&&reHasUnescapedHtml.test(string)?string.replace(reUnescapedHtml,escapeHtmlChar):string}function escapeRegExp(string){string=baseToString(string);return string&&reHasRegExpChars.test(string)?string.replace(reRegExpChars,"\\$&"):string}var kebabCase=createCompounder(function(result,word,index){return result+(index?"-":"")+word.toLowerCase()});function pad(string,length,chars){string=baseToString(string);length=+length;var strLength=string.length;if(strLength>=length||!nativeIsFinite(length)){return string}var mid=(length-strLength)/2,leftLength=floor(mid),rightLength=ceil(mid);chars=createPad("",rightLength,chars);return chars.slice(0,leftLength)+string+chars}function padLeft(string,length,chars){string=baseToString(string);return string&&createPad(string,length,chars)+string}function padRight(string,length,chars){string=baseToString(string);return string&&string+createPad(string,length,chars)}function parseInt(string,radix,guard){if(guard&&isIterateeCall(string,radix,guard)){radix=0}return nativeParseInt(string,radix)}if(nativeParseInt(whitespace+"08")!=8){parseInt=function(string,radix,guard){if(guard?isIterateeCall(string,radix,guard):radix==null){radix=0}else if(radix){radix=+radix}string=trim(string);return nativeParseInt(string,radix||(reHexPrefix.test(string)?16:10))}}function repeat(string,n){var result="";string=baseToString(string);n=+n;if(n<1||!string||!nativeIsFinite(n)){return result}do{if(n%2){result+=string}n=floor(n/2);string+=string}while(n);return result}var snakeCase=createCompounder(function(result,word,index){return result+(index?"_":"")+word.toLowerCase()});function startsWith(string,target,position){string=baseToString(string);position=position==null?0:nativeMin(position<0?0:+position||0,string.length);return string.lastIndexOf(target,position)==position}function template(string,options,otherOptions){var settings=lodash.templateSettings;if(otherOptions&&isIterateeCall(string,options,otherOptions)){options=otherOptions=null}string=baseToString(string);options=baseAssign(baseAssign({},otherOptions||options),settings,assignOwnDefaults);var imports=baseAssign(baseAssign({},options.imports),settings.imports,assignOwnDefaults),importsKeys=keys(imports),importsValues=baseValues(imports,importsKeys);var isEscaping,isEvaluating,index=0,interpolate=options.interpolate||reNoMatch,source="__p += '";var reDelimiters=RegExp((options.escape||reNoMatch).source+"|"+interpolate.source+"|"+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+"|"+(options.evaluate||reNoMatch).source+"|$","g");var sourceURL="//# sourceURL="+("sourceURL"in options?options.sourceURL:"lodash.templateSources["+ ++templateCounter+"]")+"\n";string.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){interpolateValue||(interpolateValue=esTemplateValue);source+=string.slice(index,offset).replace(reUnescapedString,escapeStringChar);if(escapeValue){isEscaping=true;source+="' +\n__e("+escapeValue+") +\n'"}if(evaluateValue){isEvaluating=true;source+="';\n"+evaluateValue+";\n__p += '"}if(interpolateValue){source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'"}index=offset+match.length;return match});source+="';\n";var variable=options.variable;if(!variable){source="with (obj) {\n"+source+"\n}\n"}source=(isEvaluating?source.replace(reEmptyStringLeading,""):source).replace(reEmptyStringMiddle,"$1").replace(reEmptyStringTrailing,"$1;");source="function("+(variable||"obj")+") {\n"+(variable?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(isEscaping?", __e = _.escape":"")+(isEvaluating?", __j = Array.prototype.join;\n"+"function print() { __p += __j.call(arguments, '') }\n":";\n")+source+"return __p\n}";var result=attempt(function(){return Function(importsKeys,sourceURL+"return "+source).apply(undefined,importsValues)});result.source=source;if(isError(result)){throw result}return result}function trim(string,chars,guard){var value=string;string=baseToString(string);if(!string){return string}if(guard?isIterateeCall(value,chars,guard):chars==null){return string.slice(trimmedLeftIndex(string),trimmedRightIndex(string)+1)}chars=baseToString(chars);return string.slice(charsLeftIndex(string,chars),charsRightIndex(string,chars)+1)}function trimLeft(string,chars,guard){var value=string;string=baseToString(string);if(!string){return string}if(guard?isIterateeCall(value,chars,guard):chars==null){return string.slice(trimmedLeftIndex(string))}return string.slice(charsLeftIndex(string,baseToString(chars)))}function trimRight(string,chars,guard){var value=string;string=baseToString(string);if(!string){return string}if(guard?isIterateeCall(value,chars,guard):chars==null){return string.slice(0,trimmedRightIndex(string)+1)}return string.slice(0,charsRightIndex(string,baseToString(chars))+1)}function trunc(string,options,guard){if(guard&&isIterateeCall(string,options,guard)){options=null}var length=DEFAULT_TRUNC_LENGTH,omission=DEFAULT_TRUNC_OMISSION;if(options!=null){if(isObject(options)){var separator="separator"in options?options.separator:separator;length="length"in options?+options.length||0:length;omission="omission"in options?baseToString(options.omission):omission}else{length=+options||0}}string=baseToString(string);if(length>=string.length){return string}var end=length-omission.length;if(end<1){return omission}var result=string.slice(0,end);if(separator==null){return result+omission}if(isRegExp(separator)){if(string.slice(end).search(separator)){var match,newEnd,substring=string.slice(0,end);if(!separator.global){separator=RegExp(separator.source,(reFlags.exec(separator)||"")+"g")}separator.lastIndex=0;while(match=separator.exec(substring)){newEnd=match.index}result=result.slice(0,newEnd==null?end:newEnd)}}else if(string.indexOf(separator,end)!=end){var index=result.lastIndexOf(separator);if(index>-1){result=result.slice(0,index)}}return result+omission}function unescape(string){string=baseToString(string);return string&&reHasEscapedHtml.test(string)?string.replace(reEscapedHtml,unescapeHtmlChar):string}function words(string,pattern,guard){if(guard&&isIterateeCall(string,pattern,guard)){pattern=null}string=baseToString(string);return string.match(pattern||reWords)||[]}function attempt(func){try{return func()}catch(e){return isError(e)?e:Error(e)}}function callback(func,thisArg,guard){if(guard&&isIterateeCall(func,thisArg,guard)){thisArg=null}return baseCallback(func,thisArg)}function constant(value){return function(){return value}}function identity(value){return value}function matches(source){return baseMatches(source,true)}function mixin(object,source,options){if(options==null){var isObj=isObject(source),props=isObj&&keys(source),methodNames=props&&props.length&&baseFunctions(source,props);if(!(methodNames?methodNames.length:isObj)){methodNames=false;options=source;source=object;object=this}}if(!methodNames){methodNames=baseFunctions(source,keys(source))}var chain=true,index=-1,isFunc=isFunction(object),length=methodNames.length;if(options===false){chain=false}else if(isObject(options)&&"chain"in options){chain=options.chain}while(++index<length){var methodName=methodNames[index],func=source[methodName];object[methodName]=func;if(isFunc){object.prototype[methodName]=function(func){return function(){var chainAll=this.__chain__;if(chain||chainAll){var result=object(this.__wrapped__);(result.__actions__=arrayCopy(this.__actions__)).push({func:func,args:arguments,thisArg:object});result.__chain__=chainAll;return result}var args=[this.value()];push.apply(args,arguments);return func.apply(object,args)}}(func)}}return object}function noConflict(){context._=oldDash;return this}function noop(){}function property(key){return baseProperty(key+"")}function propertyOf(object){return function(key){return object==null?undefined:object[key]}}function range(start,end,step){if(step&&isIterateeCall(start,end,step)){end=step=null}start=+start||0;step=step==null?1:+step||0;if(end==null){end=start;start=0}else{end=+end||0}var index=-1,length=nativeMax(ceil((end-start)/(step||1)),0),result=Array(length);while(++index<length){result[index]=start;start+=step}return result}function times(n,iteratee,thisArg){n=+n;if(n<1||!nativeIsFinite(n)){return[]}var index=-1,result=Array(nativeMin(n,MAX_ARRAY_LENGTH));iteratee=bindCallback(iteratee,thisArg,1);while(++index<n){if(index<MAX_ARRAY_LENGTH){result[index]=iteratee(index)}else{iteratee(index)}}return result}function uniqueId(prefix){var id=++idCounter;return baseToString(prefix)+id}LodashWrapper.prototype=lodash.prototype;MapCache.prototype["delete"]=mapDelete;MapCache.prototype.get=mapGet;MapCache.prototype.has=mapHas;MapCache.prototype.set=mapSet;SetCache.prototype.push=cachePush;memoize.Cache=MapCache;lodash.after=after;lodash.ary=ary;lodash.assign=assign;lodash.at=at;lodash.before=before;lodash.bind=bind;lodash.bindAll=bindAll;lodash.bindKey=bindKey;lodash.callback=callback;lodash.chain=chain;lodash.chunk=chunk;lodash.compact=compact;lodash.constant=constant;lodash.countBy=countBy;lodash.create=create;lodash.curry=curry;lodash.curryRight=curryRight;lodash.debounce=debounce;lodash.defaults=defaults;lodash.defer=defer;lodash.delay=delay;lodash.difference=difference;lodash.drop=drop;lodash.dropRight=dropRight;lodash.dropRightWhile=dropRightWhile;lodash.dropWhile=dropWhile;lodash.filter=filter;lodash.flatten=flatten;lodash.flattenDeep=flattenDeep;lodash.flow=flow;lodash.flowRight=flowRight;lodash.forEach=forEach;lodash.forEachRight=forEachRight;lodash.forIn=forIn;lodash.forInRight=forInRight;lodash.forOwn=forOwn;lodash.forOwnRight=forOwnRight;lodash.functions=functions;lodash.groupBy=groupBy;lodash.indexBy=indexBy;lodash.initial=initial;lodash.intersection=intersection;lodash.invert=invert;lodash.invoke=invoke;lodash.keys=keys;lodash.keysIn=keysIn;lodash.map=map;lodash.mapValues=mapValues;lodash.matches=matches;lodash.memoize=memoize;lodash.merge=merge;lodash.mixin=mixin;lodash.negate=negate;lodash.omit=omit;lodash.once=once;lodash.pairs=pairs;lodash.partial=partial;lodash.partialRight=partialRight;lodash.partition=partition;lodash.pick=pick;lodash.pluck=pluck;lodash.property=property;lodash.propertyOf=propertyOf;lodash.pull=pull;lodash.pullAt=pullAt;lodash.range=range;lodash.rearg=rearg;lodash.reject=reject;lodash.remove=remove;lodash.rest=rest;lodash.shuffle=shuffle;lodash.slice=slice;lodash.sortBy=sortBy;lodash.sortByAll=sortByAll;lodash.take=take;lodash.takeRight=takeRight;lodash.takeRightWhile=takeRightWhile;lodash.takeWhile=takeWhile;lodash.tap=tap;lodash.throttle=throttle;lodash.thru=thru;lodash.times=times;lodash.toArray=toArray;lodash.toPlainObject=toPlainObject;lodash.transform=transform;lodash.union=union;lodash.uniq=uniq;lodash.unzip=unzip;lodash.values=values;lodash.valuesIn=valuesIn;lodash.where=where;lodash.without=without;lodash.wrap=wrap;lodash.xor=xor;lodash.zip=zip;lodash.zipObject=zipObject;lodash.backflow=flowRight;lodash.collect=map;lodash.compose=flowRight;lodash.each=forEach;lodash.eachRight=forEachRight;lodash.extend=assign;lodash.iteratee=callback;lodash.methods=functions;lodash.object=zipObject;lodash.select=filter;lodash.tail=rest;lodash.unique=uniq;mixin(lodash,lodash);lodash.attempt=attempt;lodash.camelCase=camelCase;lodash.capitalize=capitalize;lodash.clone=clone;lodash.cloneDeep=cloneDeep;lodash.deburr=deburr;lodash.endsWith=endsWith;lodash.escape=escape;lodash.escapeRegExp=escapeRegExp;lodash.every=every;lodash.find=find;lodash.findIndex=findIndex;lodash.findKey=findKey;lodash.findLast=findLast;lodash.findLastIndex=findLastIndex;lodash.findLastKey=findLastKey;lodash.findWhere=findWhere;lodash.first=first;lodash.has=has;lodash.identity=identity;lodash.includes=includes;lodash.indexOf=indexOf;lodash.isArguments=isArguments;lodash.isArray=isArray;lodash.isBoolean=isBoolean;lodash.isDate=isDate;lodash.isElement=isElement;lodash.isEmpty=isEmpty;lodash.isEqual=isEqual;lodash.isError=isError;lodash.isFinite=isFinite;lodash.isFunction=isFunction;lodash.isMatch=isMatch;lodash.isNaN=isNaN;lodash.isNative=isNative;lodash.isNull=isNull;lodash.isNumber=isNumber;lodash.isObject=isObject;lodash.isPlainObject=isPlainObject;lodash.isRegExp=isRegExp;lodash.isString=isString;lodash.isTypedArray=isTypedArray;lodash.isUndefined=isUndefined;lodash.kebabCase=kebabCase;lodash.last=last;lodash.lastIndexOf=lastIndexOf;lodash.max=max;lodash.min=min;lodash.noConflict=noConflict;lodash.noop=noop;lodash.now=now;lodash.pad=pad;lodash.padLeft=padLeft;lodash.padRight=padRight;lodash.parseInt=parseInt;lodash.random=random;lodash.reduce=reduce;lodash.reduceRight=reduceRight;lodash.repeat=repeat;lodash.result=result;lodash.runInContext=runInContext;lodash.size=size;lodash.snakeCase=snakeCase;lodash.some=some;lodash.sortedIndex=sortedIndex;lodash.sortedLastIndex=sortedLastIndex;lodash.startsWith=startsWith;lodash.template=template;lodash.trim=trim;lodash.trimLeft=trimLeft;lodash.trimRight=trimRight;lodash.trunc=trunc;lodash.unescape=unescape;lodash.uniqueId=uniqueId;lodash.words=words;lodash.all=every;lodash.any=some;lodash.contains=includes;lodash.detect=find;lodash.foldl=reduce;lodash.foldr=reduceRight;lodash.head=first;lodash.include=includes;lodash.inject=reduce;mixin(lodash,function(){var source={};baseForOwn(lodash,function(func,methodName){if(!lodash.prototype[methodName]){source[methodName]=func}});return source}(),false);lodash.sample=sample;lodash.prototype.sample=function(n){if(!this.__chain__&&n==null){return sample(this.value())}return this.thru(function(value){return sample(value,n)})};lodash.VERSION=VERSION;arrayEach(["bind","bindKey","curry","curryRight","partial","partialRight"],function(methodName){lodash[methodName].placeholder=lodash});arrayEach(["filter","map","takeWhile"],function(methodName,index){var isFilter=index==LAZY_FILTER_FLAG;LazyWrapper.prototype[methodName]=function(iteratee,thisArg){var result=this.clone(),filtered=result.filtered,iteratees=result.iteratees||(result.iteratees=[]);result.filtered=filtered||isFilter||index==LAZY_WHILE_FLAG&&result.dir<0;iteratees.push({iteratee:getCallback(iteratee,thisArg,3),type:index});return result}});arrayEach(["drop","take"],function(methodName,index){var countName=methodName+"Count",whileName=methodName+"While";LazyWrapper.prototype[methodName]=function(n){n=n==null?1:nativeMax(+n||0,0);var result=this.clone();if(result.filtered){var value=result[countName];result[countName]=index?nativeMin(value,n):value+n}else{var views=result.views||(result.views=[]);views.push({size:n,type:methodName+(result.dir<0?"Right":"")})}return result};LazyWrapper.prototype[methodName+"Right"]=function(n){return this.reverse()[methodName](n).reverse()};LazyWrapper.prototype[methodName+"RightWhile"]=function(predicate,thisArg){return this.reverse()[whileName](predicate,thisArg).reverse()}});arrayEach(["first","last"],function(methodName,index){var takeName="take"+(index?"Right":"");LazyWrapper.prototype[methodName]=function(){return this[takeName](1).value()[0]}});arrayEach(["initial","rest"],function(methodName,index){var dropName="drop"+(index?"":"Right");LazyWrapper.prototype[methodName]=function(){return this[dropName](1)}});arrayEach(["pluck","where"],function(methodName,index){var operationName=index?"filter":"map",createCallback=index?matches:property;LazyWrapper.prototype[methodName]=function(value){return this[operationName](createCallback(value))}});LazyWrapper.prototype.dropWhile=function(iteratee,thisArg){var done,lastIndex,isRight=this.dir<0;iteratee=getCallback(iteratee,thisArg,3);return this.filter(function(value,index,array){done=done&&(isRight?index<lastIndex:index>lastIndex);lastIndex=index;return done||(done=!iteratee(value,index,array))})};LazyWrapper.prototype.reject=function(iteratee,thisArg){iteratee=getCallback(iteratee,thisArg,3);return this.filter(function(value,index,array){return!iteratee(value,index,array)})};LazyWrapper.prototype.slice=function(start,end){start=start==null?0:+start||0;var result=start<0?this.takeRight(-start):this.drop(start);if(typeof end!="undefined"){end=+end||0;result=end<0?result.dropRight(-end):result.take(end-start)}return result};baseForOwn(LazyWrapper.prototype,function(func,methodName){var retUnwrapped=/^(?:first|last)$/.test(methodName);lodash.prototype[methodName]=function(){var value=this.__wrapped__,args=arguments,chainAll=this.__chain__,isHybrid=!!this.__actions__.length,isLazy=value instanceof LazyWrapper,onlyLazy=isLazy&&!isHybrid;if(retUnwrapped&&!chainAll){return onlyLazy?func.call(value):lodash[methodName](this.value())}var interceptor=function(value){var otherArgs=[value];push.apply(otherArgs,args);return lodash[methodName].apply(lodash,otherArgs)};if(isLazy||isArray(value)){var wrapper=onlyLazy?value:new LazyWrapper(this),result=func.apply(wrapper,args);if(!retUnwrapped&&(isHybrid||result.actions)){var actions=result.actions||(result.actions=[]);actions.push({func:thru,args:[interceptor],thisArg:lodash})}return new LodashWrapper(result,chainAll)}return this.thru(interceptor)}});arrayEach(["concat","join","pop","push","shift","sort","splice","unshift"],function(methodName){var func=arrayProto[methodName],chainName=/^(?:push|sort|unshift)$/.test(methodName)?"tap":"thru",retUnwrapped=/^(?:join|pop|shift)$/.test(methodName);lodash.prototype[methodName]=function(){var args=arguments;if(retUnwrapped&&!this.__chain__){return func.apply(this.value(),args)}return this[chainName](function(value){return func.apply(value,args)})}});LazyWrapper.prototype.clone=lazyClone;LazyWrapper.prototype.reverse=lazyReverse;LazyWrapper.prototype.value=lazyValue;lodash.prototype.chain=wrapperChain;lodash.prototype.reverse=wrapperReverse;lodash.prototype.toString=wrapperToString;lodash.prototype.toJSON=lodash.prototype.valueOf=lodash.prototype.value=wrapperValue;lodash.prototype.collect=lodash.prototype.map;lodash.prototype.head=lodash.prototype.first;lodash.prototype.select=lodash.prototype.filter;lodash.prototype.tail=lodash.prototype.rest;return lodash}var _=runInContext();if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){root._=_;define(function(){return _})}else if(freeExports&&freeModule){if(moduleExports){(freeModule.exports=_)._=_}else{freeExports._=_}}else{root._=_}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],165:[function(require,module,exports){"use strict";var originalObject=Object;var originalDefProp=Object.defineProperty;var originalCreate=Object.create;function defProp(obj,name,value){if(originalDefProp)try{originalDefProp.call(originalObject,obj,name,{value:value})}catch(definePropertyIsBrokenInIE8){obj[name]=value}else{obj[name]=value}}function makeSafeToCall(fun){if(fun){defProp(fun,"call",fun.call);defProp(fun,"apply",fun.apply)}return fun}makeSafeToCall(originalDefProp);makeSafeToCall(originalCreate);var hasOwn=makeSafeToCall(Object.prototype.hasOwnProperty);var numToStr=makeSafeToCall(Number.prototype.toString);var strSlice=makeSafeToCall(String.prototype.slice);var cloner=function(){};function create(prototype){if(originalCreate){return originalCreate.call(originalObject,prototype)}cloner.prototype=prototype||null;return new cloner}var rand=Math.random;var uniqueKeys=create(null);function makeUniqueKey(){do var uniqueKey=internString(strSlice.call(numToStr.call(rand(),36),2));while(hasOwn.call(uniqueKeys,uniqueKey));return uniqueKeys[uniqueKey]=uniqueKey}function internString(str){var obj={};obj[str]=true;return Object.keys(obj)[0]}defProp(exports,"makeUniqueKey",makeUniqueKey);var originalGetOPNs=Object.getOwnPropertyNames;Object.getOwnPropertyNames=function getOwnPropertyNames(object){for(var names=originalGetOPNs(object),src=0,dst=0,len=names.length;src<len;++src){if(!hasOwn.call(uniqueKeys,names[src])){if(src>dst){names[dst]=names[src]}++dst}}names.length=dst;return names};function defaultCreatorFn(object){return create(null)}function makeAccessor(secretCreatorFn){var brand=makeUniqueKey();var passkey=create(null);secretCreatorFn=secretCreatorFn||defaultCreatorFn;function register(object){var secret;function vault(key,forget){if(key===passkey){return forget?secret=null:secret||(secret=secretCreatorFn(object))}}defProp(object,brand,vault)}function accessor(object){if(!hasOwn.call(object,brand))register(object);return object[brand](passkey)}accessor.forget=function(object){if(hasOwn.call(object,brand))object[brand](passkey,true)};return accessor}defProp(exports,"makeAccessor",makeAccessor)},{}],166:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var isArray=types.builtInTypes.array;var b=types.builders;var n=types.namedTypes;var leap=require("./leap");var meta=require("./meta");var util=require("./util");var runtimeKeysMethod=util.runtimeProperty("keys");var hasOwn=Object.prototype.hasOwnProperty;function Emitter(contextId){assert.ok(this instanceof Emitter);n.Identifier.assert(contextId);Object.defineProperties(this,{contextId:{value:contextId},listing:{value:[]},marked:{value:[true]},finalLoc:{value:loc()},tryEntries:{value:[]}});Object.defineProperties(this,{leapManager:{value:new leap.LeapManager(this)}})}var Ep=Emitter.prototype;exports.Emitter=Emitter;function loc(){return b.literal(-1)}Ep.mark=function(loc){n.Literal.assert(loc);var index=this.listing.length;if(loc.value===-1){loc.value=index
}else{assert.strictEqual(loc.value,index)}this.marked[index]=true;return loc};Ep.emit=function(node){if(n.Expression.check(node))node=b.expressionStatement(node);n.Statement.assert(node);this.listing.push(node)};Ep.emitAssign=function(lhs,rhs){this.emit(this.assign(lhs,rhs));return lhs};Ep.assign=function(lhs,rhs){return b.expressionStatement(b.assignmentExpression("=",lhs,rhs))};Ep.contextProperty=function(name,computed){return b.memberExpression(this.contextId,computed?b.literal(name):b.identifier(name),!!computed)};var volatileContextPropertyNames={prev:true,next:true,sent:true,rval:true};Ep.isVolatileContextProperty=function(expr){if(n.MemberExpression.check(expr)){if(expr.computed){return true}if(n.Identifier.check(expr.object)&&n.Identifier.check(expr.property)&&expr.object.name===this.contextId.name&&hasOwn.call(volatileContextPropertyNames,expr.property.name)){return true}}return false};Ep.stop=function(rval){if(rval){this.setReturnValue(rval)}this.jump(this.finalLoc)};Ep.setReturnValue=function(valuePath){n.Expression.assert(valuePath.value);this.emitAssign(this.contextProperty("rval"),this.explodeExpression(valuePath))};Ep.clearPendingException=function(tryLoc,assignee){n.Literal.assert(tryLoc);var catchCall=b.callExpression(this.contextProperty("catch",true),[tryLoc]);if(assignee){this.emitAssign(assignee,catchCall)}else{this.emit(catchCall)}};Ep.jump=function(toLoc){this.emitAssign(this.contextProperty("next"),toLoc);this.emit(b.breakStatement())};Ep.jumpIf=function(test,toLoc){n.Expression.assert(test);n.Literal.assert(toLoc);this.emit(b.ifStatement(test,b.blockStatement([this.assign(this.contextProperty("next"),toLoc),b.breakStatement()])))};Ep.jumpIfNot=function(test,toLoc){n.Expression.assert(test);n.Literal.assert(toLoc);var negatedTest;if(n.UnaryExpression.check(test)&&test.operator==="!"){negatedTest=test.argument}else{negatedTest=b.unaryExpression("!",test)}this.emit(b.ifStatement(negatedTest,b.blockStatement([this.assign(this.contextProperty("next"),toLoc),b.breakStatement()])))};var nextTempId=0;Ep.makeTempVar=function(){return this.contextProperty("t"+nextTempId++)};Ep.getContextFunction=function(id){var func=b.functionExpression(id||null,[this.contextId],b.blockStatement([this.getDispatchLoop()]),false,false);func._aliasFunction=true;return func};Ep.getDispatchLoop=function(){var self=this;var cases=[];var current;var alreadyEnded=false;self.listing.forEach(function(stmt,i){if(self.marked.hasOwnProperty(i)){cases.push(b.switchCase(b.literal(i),current=[]));alreadyEnded=false}if(!alreadyEnded){current.push(stmt);if(isSwitchCaseEnder(stmt))alreadyEnded=true}});this.finalLoc.value=this.listing.length;cases.push(b.switchCase(this.finalLoc,[]),b.switchCase(b.literal("end"),[b.returnStatement(b.callExpression(this.contextProperty("stop"),[]))]));return b.whileStatement(b.literal(1),b.switchStatement(b.assignmentExpression("=",this.contextProperty("prev"),this.contextProperty("next")),cases))};function isSwitchCaseEnder(stmt){return n.BreakStatement.check(stmt)||n.ContinueStatement.check(stmt)||n.ReturnStatement.check(stmt)||n.ThrowStatement.check(stmt)}Ep.getTryEntryList=function(){if(this.tryEntries.length===0){return null}var lastLocValue=0;return b.arrayExpression(this.tryEntries.map(function(tryEntry){var thisLocValue=tryEntry.firstLoc.value;assert.ok(thisLocValue>=lastLocValue,"try entries out of order");lastLocValue=thisLocValue;var ce=tryEntry.catchEntry;var fe=tryEntry.finallyEntry;var triple=[tryEntry.firstLoc,ce?ce.firstLoc:null];if(fe){triple[2]=fe.firstLoc}return b.arrayExpression(triple)}))};Ep.explode=function(path,ignoreResult){assert.ok(path instanceof types.NodePath);var node=path.value;var self=this;n.Node.assert(node);if(n.Statement.check(node))return self.explodeStatement(path);if(n.Expression.check(node))return self.explodeExpression(path,ignoreResult);if(n.Declaration.check(node))throw getDeclError(node);switch(node.type){case"Program":return path.get("body").map(self.explodeStatement,self);case"VariableDeclarator":throw getDeclError(node);case"Property":case"SwitchCase":case"CatchClause":throw new Error(node.type+" nodes should be handled by their parents");default:throw new Error("unknown Node of type "+JSON.stringify(node.type))}};function getDeclError(node){return new Error("all declarations should have been transformed into "+"assignments before the Exploder began its work: "+JSON.stringify(node))}Ep.explodeStatement=function(path,labelId){assert.ok(path instanceof types.NodePath);var stmt=path.value;var self=this;n.Statement.assert(stmt);if(labelId){n.Identifier.assert(labelId)}else{labelId=null}if(n.BlockStatement.check(stmt)){return path.get("body").each(self.explodeStatement,self)}if(!meta.containsLeap(stmt)){self.emit(stmt);return}switch(stmt.type){case"ExpressionStatement":self.explodeExpression(path.get("expression"),true);break;case"LabeledStatement":var after=loc();self.leapManager.withEntry(new leap.LabeledEntry(after,stmt.label),function(){self.explodeStatement(path.get("body"),stmt.label)});self.mark(after);break;case"WhileStatement":var before=loc();var after=loc();self.mark(before);self.jumpIfNot(self.explodeExpression(path.get("test")),after);self.leapManager.withEntry(new leap.LoopEntry(after,before,labelId),function(){self.explodeStatement(path.get("body"))});self.jump(before);self.mark(after);break;case"DoWhileStatement":var first=loc();var test=loc();var after=loc();self.mark(first);self.leapManager.withEntry(new leap.LoopEntry(after,test,labelId),function(){self.explode(path.get("body"))});self.mark(test);self.jumpIf(self.explodeExpression(path.get("test")),first);self.mark(after);break;case"ForStatement":var head=loc();var update=loc();var after=loc();if(stmt.init){self.explode(path.get("init"),true)}self.mark(head);if(stmt.test){self.jumpIfNot(self.explodeExpression(path.get("test")),after)}else{}self.leapManager.withEntry(new leap.LoopEntry(after,update,labelId),function(){self.explodeStatement(path.get("body"))});self.mark(update);if(stmt.update){self.explode(path.get("update"),true)}self.jump(head);self.mark(after);break;case"ForInStatement":n.Identifier.assert(stmt.left);var head=loc();var after=loc();var keyIterNextFn=self.makeTempVar();self.emitAssign(keyIterNextFn,b.callExpression(runtimeKeysMethod,[self.explodeExpression(path.get("right"))]));self.mark(head);var keyInfoTmpVar=self.makeTempVar();self.jumpIf(b.memberExpression(b.assignmentExpression("=",keyInfoTmpVar,b.callExpression(keyIterNextFn,[])),b.identifier("done"),false),after);self.emitAssign(stmt.left,b.memberExpression(keyInfoTmpVar,b.identifier("value"),false));self.leapManager.withEntry(new leap.LoopEntry(after,head,labelId),function(){self.explodeStatement(path.get("body"))});self.jump(head);self.mark(after);break;case"BreakStatement":self.emitAbruptCompletion({type:"break",target:self.leapManager.getBreakLoc(stmt.label)});break;case"ContinueStatement":self.emitAbruptCompletion({type:"continue",target:self.leapManager.getContinueLoc(stmt.label)});break;case"SwitchStatement":var disc=self.emitAssign(self.makeTempVar(),self.explodeExpression(path.get("discriminant")));var after=loc();var defaultLoc=loc();var condition=defaultLoc;var caseLocs=[];var cases=stmt.cases||[];for(var i=cases.length-1;i>=0;--i){var c=cases[i];n.SwitchCase.assert(c);if(c.test){condition=b.conditionalExpression(b.binaryExpression("===",disc,c.test),caseLocs[i]=loc(),condition)}else{caseLocs[i]=defaultLoc}}self.jump(self.explodeExpression(new types.NodePath(condition,path,"discriminant")));self.leapManager.withEntry(new leap.SwitchEntry(after),function(){path.get("cases").each(function(casePath){var c=casePath.value;var i=casePath.name;self.mark(caseLocs[i]);casePath.get("consequent").each(self.explodeStatement,self)})});self.mark(after);if(defaultLoc.value===-1){self.mark(defaultLoc);assert.strictEqual(after.value,defaultLoc.value)}break;case"IfStatement":var elseLoc=stmt.alternate&&loc();var after=loc();self.jumpIfNot(self.explodeExpression(path.get("test")),elseLoc||after);self.explodeStatement(path.get("consequent"));if(elseLoc){self.jump(after);self.mark(elseLoc);self.explodeStatement(path.get("alternate"))}self.mark(after);break;case"ReturnStatement":self.emitAbruptCompletion({type:"return",value:self.explodeExpression(path.get("argument"))});break;case"WithStatement":throw new Error(node.type+" not supported in generator functions.");case"TryStatement":var after=loc();var handler=stmt.handler;if(!handler&&stmt.handlers){handler=stmt.handlers[0]||null}var catchLoc=handler&&loc();var catchEntry=catchLoc&&new leap.CatchEntry(catchLoc,handler.param);var finallyLoc=stmt.finalizer&&loc();var finallyEntry=finallyLoc&&new leap.FinallyEntry(finallyLoc);var tryEntry=new leap.TryEntry(self.getUnmarkedCurrentLoc(),catchEntry,finallyEntry);self.tryEntries.push(tryEntry);self.updateContextPrevLoc(tryEntry.firstLoc);self.leapManager.withEntry(tryEntry,function(){self.explodeStatement(path.get("block"));if(catchLoc){if(finallyLoc){self.jump(finallyLoc)}else{self.jump(after)}self.updateContextPrevLoc(self.mark(catchLoc));var bodyPath=path.get("handler","body");var safeParam=self.makeTempVar();self.clearPendingException(tryEntry.firstLoc,safeParam);var catchScope=bodyPath.scope;var catchParamName=handler.param.name;n.CatchClause.assert(catchScope.node);assert.strictEqual(catchScope.lookup(catchParamName),catchScope);types.visit(bodyPath,{visitIdentifier:function(path){if(util.isReference(path,catchParamName)&&path.scope.lookup(catchParamName)===catchScope){return safeParam}this.traverse(path)},visitFunction:function(path){if(path.scope.declares(catchParamName)){return false}this.traverse(path)}});self.leapManager.withEntry(catchEntry,function(){self.explodeStatement(bodyPath)})}if(finallyLoc){self.updateContextPrevLoc(self.mark(finallyLoc));self.leapManager.withEntry(finallyEntry,function(){self.explodeStatement(path.get("finalizer"))});self.emit(b.callExpression(self.contextProperty("finish"),[finallyEntry.firstLoc]))}});self.mark(after);break;case"ThrowStatement":self.emit(b.throwStatement(self.explodeExpression(path.get("argument"))));break;default:throw new Error("unknown Statement of type "+JSON.stringify(stmt.type))}};Ep.emitAbruptCompletion=function(record){if(!isValidCompletion(record)){assert.ok(false,"invalid completion record: "+JSON.stringify(record))}assert.notStrictEqual(record.type,"normal","normal completions are not abrupt");var abruptArgs=[b.literal(record.type)];if(record.type==="break"||record.type==="continue"){n.Literal.assert(record.target);abruptArgs[1]=record.target}else if(record.type==="return"||record.type==="throw"){if(record.value){n.Expression.assert(record.value);abruptArgs[1]=record.value}}this.emit(b.returnStatement(b.callExpression(this.contextProperty("abrupt"),abruptArgs)))};function isValidCompletion(record){var type=record.type;if(type==="normal"){return!hasOwn.call(record,"target")}if(type==="break"||type==="continue"){return!hasOwn.call(record,"value")&&n.Literal.check(record.target)}if(type==="return"||type==="throw"){return hasOwn.call(record,"value")&&!hasOwn.call(record,"target")}return false}Ep.getUnmarkedCurrentLoc=function(){return b.literal(this.listing.length)};Ep.updateContextPrevLoc=function(loc){if(loc){n.Literal.assert(loc);if(loc.value===-1){loc.value=this.listing.length}else{assert.strictEqual(loc.value,this.listing.length)}}else{loc=this.getUnmarkedCurrentLoc()}this.emitAssign(this.contextProperty("prev"),loc)};Ep.explodeExpression=function(path,ignoreResult){assert.ok(path instanceof types.NodePath);var expr=path.value;if(expr){n.Expression.assert(expr)}else{return expr}var self=this;var result;function finish(expr){n.Expression.assert(expr);if(ignoreResult){self.emit(expr)}else{return expr}}if(!meta.containsLeap(expr)){return finish(expr)}var hasLeapingChildren=meta.containsLeap.onlyChildren(expr);function explodeViaTempVar(tempVar,childPath,ignoreChildResult){assert.ok(childPath instanceof types.NodePath);assert.ok(!ignoreChildResult||!tempVar,"Ignoring the result of a child expression but forcing it to "+"be assigned to a temporary variable?");var result=self.explodeExpression(childPath,ignoreChildResult);if(ignoreChildResult){}else if(tempVar||hasLeapingChildren&&(self.isVolatileContextProperty(result)||meta.hasSideEffects(result))){result=self.emitAssign(tempVar||self.makeTempVar(),result)}return result}switch(expr.type){case"MemberExpression":return finish(b.memberExpression(self.explodeExpression(path.get("object")),expr.computed?explodeViaTempVar(null,path.get("property")):expr.property,expr.computed));case"CallExpression":var oldCalleePath=path.get("callee");var newCallee=self.explodeExpression(oldCalleePath);if(!n.MemberExpression.check(oldCalleePath.node)&&n.MemberExpression.check(newCallee)){newCallee=b.sequenceExpression([b.literal(0),newCallee])}return finish(b.callExpression(newCallee,path.get("arguments").map(function(argPath){return explodeViaTempVar(null,argPath)})));case"NewExpression":return finish(b.newExpression(explodeViaTempVar(null,path.get("callee")),path.get("arguments").map(function(argPath){return explodeViaTempVar(null,argPath)})));case"ObjectExpression":return finish(b.objectExpression(path.get("properties").map(function(propPath){return b.property(propPath.value.kind,propPath.value.key,explodeViaTempVar(null,propPath.get("value")))})));case"ArrayExpression":return finish(b.arrayExpression(path.get("elements").map(function(elemPath){return explodeViaTempVar(null,elemPath)})));case"SequenceExpression":var lastIndex=expr.expressions.length-1;path.get("expressions").each(function(exprPath){if(exprPath.name===lastIndex){result=self.explodeExpression(exprPath,ignoreResult)}else{self.explodeExpression(exprPath,true)}});return result;case"LogicalExpression":var after=loc();if(!ignoreResult){result=self.makeTempVar()}var left=explodeViaTempVar(result,path.get("left"));if(expr.operator==="&&"){self.jumpIfNot(left,after)}else{assert.strictEqual(expr.operator,"||");self.jumpIf(left,after)}explodeViaTempVar(result,path.get("right"),ignoreResult);self.mark(after);return result;case"ConditionalExpression":var elseLoc=loc();var after=loc();var test=self.explodeExpression(path.get("test"));self.jumpIfNot(test,elseLoc);if(!ignoreResult){result=self.makeTempVar()}explodeViaTempVar(result,path.get("consequent"),ignoreResult);self.jump(after);self.mark(elseLoc);explodeViaTempVar(result,path.get("alternate"),ignoreResult);self.mark(after);return result;case"UnaryExpression":return finish(b.unaryExpression(expr.operator,self.explodeExpression(path.get("argument")),!!expr.prefix));case"BinaryExpression":return finish(b.binaryExpression(expr.operator,explodeViaTempVar(null,path.get("left")),explodeViaTempVar(null,path.get("right"))));case"AssignmentExpression":return finish(b.assignmentExpression(expr.operator,self.explodeExpression(path.get("left")),self.explodeExpression(path.get("right"))));case"UpdateExpression":return finish(b.updateExpression(expr.operator,self.explodeExpression(path.get("argument")),expr.prefix));case"YieldExpression":var after=loc();var arg=expr.argument&&self.explodeExpression(path.get("argument"));if(arg&&expr.delegate){var result=self.makeTempVar();self.emit(b.returnStatement(b.callExpression(self.contextProperty("delegateYield"),[arg,b.literal(result.property.name),after])));self.mark(after);return result}self.emitAssign(self.contextProperty("next"),after);self.emit(b.returnStatement(arg||null));self.mark(after);return self.contextProperty("sent");default:throw new Error("unknown Expression of type "+JSON.stringify(expr.type))}}},{"./leap":168,"./meta":169,"./util":170,assert:121,"ast-types":119}],167:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var n=types.namedTypes;var b=types.builders;var hasOwn=Object.prototype.hasOwnProperty;exports.hoist=function(funPath){assert.ok(funPath instanceof types.NodePath);n.Function.assert(funPath.value);var vars={};function varDeclToExpr(vdec,includeIdentifiers){n.VariableDeclaration.assert(vdec);var exprs=[];vdec.declarations.forEach(function(dec){vars[dec.id.name]=dec.id;if(dec.init){exprs.push(b.assignmentExpression("=",dec.id,dec.init))}else if(includeIdentifiers){exprs.push(dec.id)}});if(exprs.length===0)return null;if(exprs.length===1)return exprs[0];return b.sequenceExpression(exprs)}types.visit(funPath.get("body"),{visitVariableDeclaration:function(path){var expr=varDeclToExpr(path.value,false);if(expr===null){path.replace()}else{return b.expressionStatement(expr)}return false},visitForStatement:function(path){var init=path.value.init;if(n.VariableDeclaration.check(init)){path.get("init").replace(varDeclToExpr(init,false))}this.traverse(path)},visitForInStatement:function(path){var left=path.value.left;if(n.VariableDeclaration.check(left)){path.get("left").replace(varDeclToExpr(left,true))}this.traverse(path)},visitFunctionDeclaration:function(path){var node=path.value;vars[node.id.name]=node.id;var parentNode=path.parent.node;var assignment=b.expressionStatement(b.assignmentExpression("=",node.id,b.functionExpression(node.id,node.params,node.body,node.generator,node.expression)));if(n.BlockStatement.check(path.parent.node)){path.parent.get("body").unshift(assignment);path.replace()}else{path.replace(assignment)}return false},visitFunctionExpression:function(path){return false}});var paramNames={};funPath.get("params").each(function(paramPath){var param=paramPath.value;if(n.Identifier.check(param)){paramNames[param.name]=param}else{}});var declarations=[];Object.keys(vars).forEach(function(name){if(!hasOwn.call(paramNames,name)){declarations.push(b.variableDeclarator(vars[name],null))}});if(declarations.length===0){return null}return b.variableDeclaration("var",declarations)}},{assert:121,"ast-types":119}],168:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var n=types.namedTypes;var b=types.builders;var inherits=require("util").inherits;var hasOwn=Object.prototype.hasOwnProperty;function Entry(){assert.ok(this instanceof Entry)}function FunctionEntry(returnLoc){Entry.call(this);n.Literal.assert(returnLoc);this.returnLoc=returnLoc}inherits(FunctionEntry,Entry);exports.FunctionEntry=FunctionEntry;function LoopEntry(breakLoc,continueLoc,label){Entry.call(this);n.Literal.assert(breakLoc);n.Literal.assert(continueLoc);if(label){n.Identifier.assert(label)}else{label=null}this.breakLoc=breakLoc;this.continueLoc=continueLoc;this.label=label}inherits(LoopEntry,Entry);exports.LoopEntry=LoopEntry;function SwitchEntry(breakLoc){Entry.call(this);n.Literal.assert(breakLoc);this.breakLoc=breakLoc}inherits(SwitchEntry,Entry);exports.SwitchEntry=SwitchEntry;function TryEntry(firstLoc,catchEntry,finallyEntry){Entry.call(this);n.Literal.assert(firstLoc);if(catchEntry){assert.ok(catchEntry instanceof CatchEntry)}else{catchEntry=null}if(finallyEntry){assert.ok(finallyEntry instanceof FinallyEntry)}else{finallyEntry=null}assert.ok(catchEntry||finallyEntry);this.firstLoc=firstLoc;this.catchEntry=catchEntry;this.finallyEntry=finallyEntry}inherits(TryEntry,Entry);exports.TryEntry=TryEntry;function CatchEntry(firstLoc,paramId){Entry.call(this);n.Literal.assert(firstLoc);n.Identifier.assert(paramId);this.firstLoc=firstLoc;this.paramId=paramId}inherits(CatchEntry,Entry);exports.CatchEntry=CatchEntry;function FinallyEntry(firstLoc){Entry.call(this);n.Literal.assert(firstLoc);this.firstLoc=firstLoc}inherits(FinallyEntry,Entry);exports.FinallyEntry=FinallyEntry;function LabeledEntry(breakLoc,label){Entry.call(this);n.Literal.assert(breakLoc);n.Identifier.assert(label);this.breakLoc=breakLoc;this.label=label}inherits(LabeledEntry,Entry);exports.LabeledEntry=LabeledEntry;function LeapManager(emitter){assert.ok(this instanceof LeapManager);var Emitter=require("./emit").Emitter;assert.ok(emitter instanceof Emitter);this.emitter=emitter;this.entryStack=[new FunctionEntry(emitter.finalLoc)]}var LMp=LeapManager.prototype;exports.LeapManager=LeapManager;LMp.withEntry=function(entry,callback){assert.ok(entry instanceof Entry);this.entryStack.push(entry);try{callback.call(this.emitter)}finally{var popped=this.entryStack.pop();assert.strictEqual(popped,entry)}};LMp._findLeapLocation=function(property,label){for(var i=this.entryStack.length-1;i>=0;--i){var entry=this.entryStack[i];var loc=entry[property];if(loc){if(label){if(entry.label&&entry.label.name===label.name){return loc}}else if(entry instanceof LabeledEntry){}else{return loc}}}return null};LMp.getBreakLoc=function(label){return this._findLeapLocation("breakLoc",label)};LMp.getContinueLoc=function(label){return this._findLeapLocation("continueLoc",label)}},{"./emit":166,assert:121,"ast-types":119,util:145}],169:[function(require,module,exports){var assert=require("assert");var m=require("private").makeAccessor();var types=require("ast-types");var isArray=types.builtInTypes.array;var n=types.namedTypes;var hasOwn=Object.prototype.hasOwnProperty;function makePredicate(propertyName,knownTypes){function onlyChildren(node){n.Node.assert(node);var result=false;function check(child){if(result){}else if(isArray.check(child)){child.some(check)}else if(n.Node.check(child)){assert.strictEqual(result,false);result=predicate(child)}return result}types.eachField(node,function(name,child){check(child)});return result}function predicate(node){n.Node.assert(node);var meta=m(node);if(hasOwn.call(meta,propertyName))return meta[propertyName];if(hasOwn.call(opaqueTypes,node.type))return meta[propertyName]=false;if(hasOwn.call(knownTypes,node.type))return meta[propertyName]=true;return meta[propertyName]=onlyChildren(node)}predicate.onlyChildren=onlyChildren;return predicate}var opaqueTypes={FunctionExpression:true};var sideEffectTypes={CallExpression:true,ForInStatement:true,UnaryExpression:true,BinaryExpression:true,AssignmentExpression:true,UpdateExpression:true,NewExpression:true};var leapTypes={YieldExpression:true,BreakStatement:true,ContinueStatement:true,ReturnStatement:true,ThrowStatement:true};for(var type in leapTypes){if(hasOwn.call(leapTypes,type)){sideEffectTypes[type]=leapTypes[type]}}exports.hasSideEffects=makePredicate("hasSideEffects",sideEffectTypes);exports.containsLeap=makePredicate("containsLeap",leapTypes)},{assert:121,"ast-types":119,"private":165}],170:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var n=types.namedTypes;var b=types.builders;var hasOwn=Object.prototype.hasOwnProperty;exports.defaults=function(obj){var len=arguments.length;var extension;for(var i=1;i<len;++i){if(extension=arguments[i]){for(var key in extension){if(hasOwn.call(extension,key)&&!hasOwn.call(obj,key)){obj[key]=extension[key]}}}}return obj};exports.runtimeProperty=function(name){return b.memberExpression(b.identifier("regeneratorRuntime"),b.identifier(name),false)};exports.isReference=function(path,name){var node=path.value;if(!n.Identifier.check(node)){return false}if(name&&node.name!==name){return false}var parent=path.parent.value;switch(parent.type){case"VariableDeclarator":return path.name==="init";case"MemberExpression":return path.name==="object"||parent.computed&&path.name==="property";case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":if(path.name==="id"){return false}if(parent.params===path.parentPath&&parent.params[path.name]===node){return false}return true;case"ClassDeclaration":case"ClassExpression":return path.name!=="id";case"CatchClause":return path.name!=="param";case"Property":case"MethodDefinition":return path.name!=="key";case"ImportSpecifier":case"ImportDefaultSpecifier":case"ImportNamespaceSpecifier":case"LabeledStatement":return false;default:return true}}},{assert:121,"ast-types":119}],171:[function(require,module,exports){var assert=require("assert");var fs=require("fs");var types=require("ast-types");var n=types.namedTypes;var b=types.builders;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var NodePath=types.NodePath;var hoist=require("./hoist").hoist;var Emitter=require("./emit").Emitter;var runtimeProperty=require("./util").runtimeProperty;var runtimeWrapMethod=runtimeProperty("wrap");var runtimeMarkMethod=runtimeProperty("mark");var runtimeValuesMethod=runtimeProperty("values");var runtimeAsyncMethod=runtimeProperty("async");exports.transform=function transform(node,options){options=options||{};var path=node instanceof NodePath?node:new NodePath(node);visitor.visit(path,options);node=path.value;options.madeChanges=visitor.wasChangeReported();return node};var visitor=types.PathVisitor.fromMethodsObject({reset:function(node,options){this.options=options},visitFunction:function(path){this.traverse(path);var node=path.value;var shouldTransformAsync=node.async&&!this.options.disableAsync;if(!node.generator&&!shouldTransformAsync){return}this.reportChanged();node.generator=false;if(node.expression){node.expression=false;node.body=b.blockStatement([b.returnStatement(node.body)])}if(shouldTransformAsync){awaitVisitor.visit(path.get("body"))}var outerFnId=node.id||(node.id=path.scope.parent.declareTemporary("callee$"));var innerFnId=b.identifier(node.id.name+"$");var contextId=path.scope.declareTemporary("context$");var vars=hoist(path);var emitter=new Emitter(contextId);emitter.explode(path.get("body"));var outerBody=[];if(vars&&vars.declarations.length>0){outerBody.push(vars)}var wrapArgs=[emitter.getContextFunction(innerFnId),shouldTransformAsync?b.literal(null):outerFnId,b.thisExpression()];var tryEntryList=emitter.getTryEntryList();if(tryEntryList){wrapArgs.push(tryEntryList)}var wrapCall=b.callExpression(shouldTransformAsync?runtimeAsyncMethod:runtimeWrapMethod,wrapArgs);outerBody.push(b.returnStatement(wrapCall));node.body=b.blockStatement(outerBody);if(shouldTransformAsync){node.async=false;return}if(n.FunctionDeclaration.check(node)){var pp=path.parent;while(pp&&!(n.BlockStatement.check(pp.value)||n.Program.check(pp.value))){pp=pp.parent}if(!pp){return}path.replace();node.type="FunctionExpression";var varDecl=b.variableDeclaration("var",[b.variableDeclarator(node.id,b.callExpression(runtimeMarkMethod,[node]))]);if(node.comments){varDecl.leadingComments=node.leadingComments;varDecl.trailingComments=node.trailingComments;node.leadingComments=null;node.trailingComments=null}varDecl._blockHoist=3;var bodyPath=pp.get("body");var bodyLen=bodyPath.value.length;bodyPath.push(varDecl)}else{n.FunctionExpression.assert(node);return b.callExpression(runtimeMarkMethod,[node])}}});function shouldNotHoistAbove(stmtPath){var value=stmtPath.value;n.Statement.assert(value);if(n.ExpressionStatement.check(value)&&n.Literal.check(value.expression)&&value.expression.value==="use strict"){return true}if(n.VariableDeclaration.check(value)){for(var i=0;i<value.declarations.length;++i){var decl=value.declarations[i];if(n.CallExpression.check(decl.init)&&types.astNodesAreEquivalent(decl.init.callee,runtimeMarkMethod)){return true}}}return false}var awaitVisitor=types.PathVisitor.fromMethodsObject({visitFunction:function(path){return false},visitAwaitExpression:function(path){return b.yieldExpression(path.value.argument,false)}})},{"./emit":166,"./hoist":167,"./util":170,assert:121,"ast-types":119,fs:120}],172:[function(require,module,exports){(function(__dirname){var assert=require("assert");var path=require("path");var fs=require("fs");var through=require("through");var transform=require("./lib/visit").transform;var utils=require("./lib/util");var types=require("ast-types");var genOrAsyncFunExp=/\bfunction\s*\*|\basync\b/;var blockBindingExp=/\b(let|const)\s+/;function exports(file,options){var data=[];return through(write,end);function write(buf){data.push(buf)}function end(){this.queue(compile(data.join(""),options).code);this.queue(null)}}module.exports=exports;function runtime(){require("./runtime")}exports.runtime=runtime;runtime.path=path.join(__dirname,"runtime.js");exports.transform=transform}).call(this,"/node_modules/regenerator-6to5")},{"./lib/util":170,"./lib/visit":171,"./runtime":174,assert:121,"ast-types":119,fs:120,path:129,through:173}],173:[function(require,module,exports){(function(process){var Stream=require("stream");exports=module.exports=through;through.through=through;function through(write,end,opts){write=write||function(data){this.queue(data)};end=end||function(){this.queue(null)};var ended=false,destroyed=false,buffer=[],_ended=false;var stream=new Stream;stream.readable=stream.writable=true;stream.paused=false;stream.autoDestroy=!(opts&&opts.autoDestroy===false);stream.write=function(data){write.call(this,data);return!stream.paused};function drain(){while(buffer.length&&!stream.paused){var data=buffer.shift();if(null===data)return stream.emit("end");else stream.emit("data",data)}}stream.queue=stream.push=function(data){if(_ended)return stream;if(data==null)_ended=true;buffer.push(data);drain();return stream};stream.on("end",function(){stream.readable=false;if(!stream.writable&&stream.autoDestroy)process.nextTick(function(){stream.destroy()})});function _end(){stream.writable=false;end.call(stream);if(!stream.readable&&stream.autoDestroy)stream.destroy()}stream.end=function(data){if(ended)return;ended=true;if(arguments.length)stream.write(data);_end();return stream};stream.destroy=function(){if(destroyed)return;destroyed=true;ended=true;buffer.length=0;stream.writable=stream.readable=false;stream.emit("close");return stream};stream.pause=function(){if(stream.paused)return;stream.paused=true;return stream};stream.resume=function(){if(stream.paused){stream.paused=false;stream.emit("resume")}drain();if(!stream.paused)stream.emit("drain");return stream};return stream}}).call(this,require("_process"))},{_process:130,stream:142}],174:[function(require,module,exports){(function(global){!function(global){"use strict";var hasOwn=Object.prototype.hasOwnProperty;var undefined;var iteratorSymbol=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";var inModule=typeof module==="object";var runtime=global.regeneratorRuntime;if(runtime){if(inModule){module.exports=runtime}return}runtime=global.regeneratorRuntime=inModule?module.exports:{};function wrap(innerFn,outerFn,self,tryList){return new Generator(innerFn,outerFn,self||null,tryList||[])}runtime.wrap=wrap;function tryCatch(fn,obj,arg){try{return{type:"normal",arg:fn.call(obj,arg)}}catch(err){return{type:"throw",arg:err}}}var GenStateSuspendedStart="suspendedStart";var GenStateSuspendedYield="suspendedYield";var GenStateExecuting="executing";var GenStateCompleted="completed";var ContinueSentinel={};function GeneratorFunction(){}function GeneratorFunctionPrototype(){}var Gp=GeneratorFunctionPrototype.prototype=Generator.prototype;GeneratorFunction.prototype=Gp.constructor=GeneratorFunctionPrototype;GeneratorFunctionPrototype.constructor=GeneratorFunction;GeneratorFunction.displayName="GeneratorFunction";runtime.isGeneratorFunction=function(genFun){var ctor=typeof genFun==="function"&&genFun.constructor;return ctor?ctor===GeneratorFunction||(ctor.displayName||ctor.name)==="GeneratorFunction":false};runtime.mark=function(genFun){genFun.__proto__=GeneratorFunctionPrototype;genFun.prototype=Object.create(Gp);return genFun};runtime.async=function(innerFn,outerFn,self,tryList){return new Promise(function(resolve,reject){var generator=wrap(innerFn,outerFn,self,tryList);var callNext=step.bind(generator.next);var callThrow=step.bind(generator["throw"]);function step(arg){var record=tryCatch(this,null,arg);if(record.type==="throw"){reject(record.arg);return}var info=record.arg;if(info.done){resolve(info.value)}else{Promise.resolve(info.value).then(callNext,callThrow)}}callNext()})};function Generator(innerFn,outerFn,self,tryList){var generator=outerFn?Object.create(outerFn.prototype):this;var context=new Context(tryList);var state=GenStateSuspendedStart;function invoke(method,arg){if(state===GenStateExecuting){throw new Error("Generator is already running")}if(state===GenStateCompleted){return doneResult()
}while(true){var delegate=context.delegate;if(delegate){var record=tryCatch(delegate.iterator[method],delegate.iterator,arg);if(record.type==="throw"){context.delegate=null;method="throw";arg=record.arg;continue}method="next";arg=undefined;var info=record.arg;if(info.done){context[delegate.resultName]=info.value;context.next=delegate.nextLoc}else{state=GenStateSuspendedYield;return info}context.delegate=null}if(method==="next"){if(state===GenStateSuspendedStart&&typeof arg!=="undefined"){throw new TypeError("attempt to send "+JSON.stringify(arg)+" to newborn generator")}if(state===GenStateSuspendedYield){context.sent=arg}else{delete context.sent}}else if(method==="throw"){if(state===GenStateSuspendedStart){state=GenStateCompleted;throw arg}if(context.dispatchException(arg)){method="next";arg=undefined}}else if(method==="return"){context.abrupt("return",arg)}state=GenStateExecuting;var record=tryCatch(innerFn,self,context);if(record.type==="normal"){state=context.done?GenStateCompleted:GenStateSuspendedYield;var info={value:record.arg,done:context.done};if(record.arg===ContinueSentinel){if(context.delegate&&method==="next"){arg=undefined}}else{return info}}else if(record.type==="throw"){state=GenStateCompleted;if(method==="next"){context.dispatchException(record.arg)}else{arg=record.arg}}}}generator.next=invoke.bind(generator,"next");generator["throw"]=invoke.bind(generator,"throw");generator["return"]=invoke.bind(generator,"return");return generator}Gp[iteratorSymbol]=function(){return this};Gp.toString=function(){return"[object Generator]"};function pushTryEntry(triple){var entry={tryLoc:triple[0]};if(1 in triple){entry.catchLoc=triple[1]}if(2 in triple){entry.finallyLoc=triple[2]}this.tryEntries.push(entry)}function resetTryEntry(entry,i){var record=entry.completion||{};record.type=i===0?"normal":"return";delete record.arg;entry.completion=record}function Context(tryList){this.tryEntries=[{tryLoc:"root"}];tryList.forEach(pushTryEntry,this);this.reset()}runtime.keys=function(object){var keys=[];for(var key in object){keys.push(key)}keys.reverse();return function next(){while(keys.length){var key=keys.pop();if(key in object){next.value=key;next.done=false;return next}}next.done=true;return next}};function values(iterable){if(iterable){var iteratorMethod=iterable[iteratorSymbol];if(iteratorMethod){return iteratorMethod.call(iterable)}if(typeof iterable.next==="function"){return iterable}if(!isNaN(iterable.length)){var i=-1,next=function next(){while(++i<iterable.length){if(hasOwn.call(iterable,i)){next.value=iterable[i];next.done=false;return next}}next.value=undefined;next.done=true;return next};return next.next=next}}return{next:doneResult}}runtime.values=values;function doneResult(){return{value:undefined,done:true}}Context.prototype={constructor:Context,reset:function(){this.prev=0;this.next=0;this.sent=undefined;this.done=false;this.delegate=null;this.tryEntries.forEach(resetTryEntry);for(var tempIndex=0,tempName;hasOwn.call(this,tempName="t"+tempIndex)||tempIndex<20;++tempIndex){this[tempName]=null}},stop:function(){this.done=true;var rootEntry=this.tryEntries[0];var rootRecord=rootEntry.completion;if(rootRecord.type==="throw"){throw rootRecord.arg}return this.rval},dispatchException:function(exception){if(this.done){throw exception}var context=this;function handle(loc,caught){record.type="throw";record.arg=exception;context.next=loc;return!!caught}for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];var record=entry.completion;if(entry.tryLoc==="root"){return handle("end")}if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc");var hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}else if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else if(hasCatch){if(this.prev<entry.catchLoc){return handle(entry.catchLoc,true)}}else if(hasFinally){if(this.prev<entry.finallyLoc){return handle(entry.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},_findFinallyEntry:function(finallyLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&(entry.finallyLoc===finallyLoc||this.prev<entry.finallyLoc)){return entry}}},abrupt:function(type,arg){var entry=this._findFinallyEntry();var record=entry?entry.completion:{};record.type=type;record.arg=arg;if(entry){this.next=entry.finallyLoc}else{this.complete(record)}return ContinueSentinel},complete:function(record){if(record.type==="throw"){throw record.arg}if(record.type==="break"||record.type==="continue"){this.next=record.arg}else if(record.type==="return"){this.rval=record.arg;this.next="end"}return ContinueSentinel},finish:function(finallyLoc){var entry=this._findFinallyEntry(finallyLoc);return this.complete(entry.completion)},"catch":function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;if(record.type==="throw"){var thrown=record.arg;resetTryEntry(entry,i)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc};return ContinueSentinel}}}(typeof global==="object"?global:typeof window==="object"?window:this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],175:[function(require,module,exports){var regenerate=require("regenerate");exports.REGULAR={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,65535),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,65535),w:regenerate(95).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,65535)};exports.UNICODE={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,1114111),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,1114111),w:regenerate(95).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)};exports.UNICODE_IGNORE_CASE={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,1114111),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().addRange(0,8).addRange(14,31).addRange(33,159).addRange(161,5759).addRange(5761,6157).addRange(6159,8191).addRange(8203,8231).addRange(8234,8238).addRange(8240,8286).addRange(8288,12287).addRange(12289,65278).addRange(65280,1114111),w:regenerate(95,383,8490).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(75,83,96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)}},{regenerate:177}],176:[function(require,module,exports){module.exports={75:8490,83:383,107:8490,115:383,181:924,197:8491,383:83,452:453,453:452,455:456,456:455,458:459,459:458,497:498,498:497,837:8126,914:976,917:1013,920:1012,921:8126,922:1008,924:181,928:982,929:1009,931:962,934:981,937:8486,962:931,976:914,977:1012,981:934,982:928,1008:922,1009:929,1012:[920,977],1013:917,7776:7835,7835:7776,8126:[837,921],8486:937,8490:75,8491:197,66560:66600,66561:66601,66562:66602,66563:66603,66564:66604,66565:66605,66566:66606,66567:66607,66568:66608,66569:66609,66570:66610,66571:66611,66572:66612,66573:66613,66574:66614,66575:66615,66576:66616,66577:66617,66578:66618,66579:66619,66580:66620,66581:66621,66582:66622,66583:66623,66584:66624,66585:66625,66586:66626,66587:66627,66588:66628,66589:66629,66590:66630,66591:66631,66592:66632,66593:66633,66594:66634,66595:66635,66596:66636,66597:66637,66598:66638,66599:66639,66600:66560,66601:66561,66602:66562,66603:66563,66604:66564,66605:66565,66606:66566,66607:66567,66608:66568,66609:66569,66610:66570,66611:66571,66612:66572,66613:66573,66614:66574,66615:66575,66616:66576,66617:66577,66618:66578,66619:66579,66620:66580,66621:66581,66622:66582,66623:66583,66624:66584,66625:66585,66626:66586,66627:66587,66628:66588,66629:66589,66630:66590,66631:66591,66632:66592,66633:66593,66634:66594,66635:66595,66636:66596,66637:66597,66638:66598,66639:66599,71840:71872,71841:71873,71842:71874,71843:71875,71844:71876,71845:71877,71846:71878,71847:71879,71848:71880,71849:71881,71850:71882,71851:71883,71852:71884,71853:71885,71854:71886,71855:71887,71856:71888,71857:71889,71858:71890,71859:71891,71860:71892,71861:71893,71862:71894,71863:71895,71864:71896,71865:71897,71866:71898,71867:71899,71868:71900,71869:71901,71870:71902,71871:71903,71872:71840,71873:71841,71874:71842,71875:71843,71876:71844,71877:71845,71878:71846,71879:71847,71880:71848,71881:71849,71882:71850,71883:71851,71884:71852,71885:71853,71886:71854,71887:71855,71888:71856,71889:71857,71890:71858,71891:71859,71892:71860,71893:71861,71894:71862,71895:71863,71896:71864,71897:71865,71898:71866,71899:71867,71900:71868,71901:71869,71902:71870,71903:71871}},{}],177:[function(require,module,exports){(function(global){(function(root){var freeExports=typeof exports=="object"&&exports;var freeModule=typeof module=="object"&&module&&module.exports==freeExports&&module;var freeGlobal=typeof global=="object"&&global;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal){root=freeGlobal}var ERRORS={rangeOrder:"A range’s `stop` value must be greater than or equal "+"to the `start` value.",codePointRange:"Invalid code point value. Code points range from "+"U+000000 to U+10FFFF."};var HIGH_SURROGATE_MIN=55296;var HIGH_SURROGATE_MAX=56319;var LOW_SURROGATE_MIN=56320;var LOW_SURROGATE_MAX=57343;var regexNull=/\\x00([^0123456789]|$)/g;var object={};var hasOwnProperty=object.hasOwnProperty;var extend=function(destination,source){var key;for(key in source){if(hasOwnProperty.call(source,key)){destination[key]=source[key]}}return destination};var forEach=function(array,callback){var index=-1;var length=array.length;while(++index<length){callback(array[index],index)}};var toString=object.toString;var isArray=function(value){return toString.call(value)=="[object Array]"};var isNumber=function(value){return typeof value=="number"||toString.call(value)=="[object Number]"};var zeroes="0000";var pad=function(number,totalCharacters){var string=String(number);return string.length<totalCharacters?(zeroes+string).slice(-totalCharacters):string};var hex=function(number){return Number(number).toString(16).toUpperCase()};var slice=[].slice;var dataFromCodePoints=function(codePoints){var index=-1;var length=codePoints.length;var max=length-1;var result=[];var isStart=true;var tmp;var previous=0;while(++index<length){tmp=codePoints[index];if(isStart){result.push(tmp);previous=tmp;isStart=false}else{if(tmp==previous+1){if(index!=max){previous=tmp;continue}else{isStart=true;result.push(tmp+1)}}else{result.push(previous+1,tmp);previous=tmp}}}if(!isStart){result.push(tmp+1)}return result};var dataRemove=function(data,codePoint){var index=0;var start;var end;var length=data.length;while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){if(codePoint==start){if(end==start+1){data.splice(index,2);return data}else{data[index]=codePoint+1;return data}}else if(codePoint==end-1){data[index+1]=codePoint;return data}else{data.splice(index,2,start,codePoint,codePoint+1,end);return data}}index+=2}return data};var dataRemoveRange=function(data,rangeStart,rangeEnd){if(rangeEnd<rangeStart){throw Error(ERRORS.rangeOrder)}var index=0;var start;var end;while(index<data.length){start=data[index];end=data[index+1]-1;if(start>rangeEnd){return data}if(rangeStart<=start&&rangeEnd>=end){data.splice(index,2);continue}if(rangeStart>=start&&rangeEnd<end){if(rangeStart==start){data[index]=rangeEnd+1;data[index+1]=end+1;return data}data.splice(index,2,start,rangeStart,rangeEnd+1,end+1);return data}if(rangeStart>=start&&rangeStart<=end){data[index+1]=rangeStart}else if(rangeEnd>=start&&rangeEnd<=end){data[index]=rangeEnd+1;return data}index+=2}return data};var dataAdd=function(data,codePoint){var index=0;var start;var end;var lastIndex=null;var length=data.length;if(codePoint<0||codePoint>1114111){throw RangeError(ERRORS.codePointRange)}while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){return data}if(codePoint==start-1){data[index]=codePoint;return data}if(start>codePoint){data.splice(lastIndex!=null?lastIndex+2:0,0,codePoint,codePoint+1);return data}if(codePoint==end){if(codePoint+1==data[index+2]){data.splice(index,4,start,data[index+3]);return data}data[index+1]=codePoint+1;return data}lastIndex=index;index+=2}data.push(codePoint,codePoint+1);return data};var dataAddData=function(dataA,dataB){var index=0;var start;var end;var data=dataA.slice();var length=dataB.length;while(index<length){start=dataB[index];end=dataB[index+1]-1;if(start==end){data=dataAdd(data,start)}else{data=dataAddRange(data,start,end)}index+=2}return data};var dataRemoveData=function(dataA,dataB){var index=0;var start;var end;var data=dataA.slice();var length=dataB.length;while(index<length){start=dataB[index];end=dataB[index+1]-1;if(start==end){data=dataRemove(data,start)}else{data=dataRemoveRange(data,start,end)}index+=2}return data};var dataAddRange=function(data,rangeStart,rangeEnd){if(rangeEnd<rangeStart){throw Error(ERRORS.rangeOrder)}if(rangeStart<0||rangeStart>1114111||rangeEnd<0||rangeEnd>1114111){throw RangeError(ERRORS.codePointRange)}var index=0;var start;var end;var added=false;var length=data.length;while(index<length){start=data[index];end=data[index+1];if(added){if(start==rangeEnd+1){data.splice(index-1,2);return data}if(start>rangeEnd){return data}if(start>=rangeStart&&start<=rangeEnd){if(end>rangeStart&&end-1<=rangeEnd){data.splice(index,2);index-=2}else{data.splice(index-1,2);index-=2}}}else if(start==rangeEnd+1){data[index]=rangeStart;return data}else if(start>rangeEnd){data.splice(index,0,rangeStart,rangeEnd+1);return data}else if(rangeStart>=start&&rangeStart<end&&rangeEnd+1<=end){return data}else if(rangeStart>=start&&rangeStart<end||end==rangeStart){data[index+1]=rangeEnd+1;added=true}else if(rangeStart<=start&&rangeEnd+1>=end){data[index]=rangeStart;data[index+1]=rangeEnd+1;added=true}index+=2}if(!added){data.push(rangeStart,rangeEnd+1)}return data};var dataContains=function(data,codePoint){var index=0;var length=data.length;var start=data[index];var end=data[length-1];if(length>=2){if(codePoint<start||codePoint>end){return false}}while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){return true}index+=2}return false};var dataIntersection=function(data,codePoints){var index=0;var length=codePoints.length;var codePoint;var result=[];while(index<length){codePoint=codePoints[index];if(dataContains(data,codePoint)){result.push(codePoint)}++index}return dataFromCodePoints(result)};var dataIsEmpty=function(data){return!data.length};var dataIsSingleton=function(data){return data.length==2&&data[0]+1==data[1]};var dataToArray=function(data){var index=0;var start;var end;var result=[];var length=data.length;while(index<length){start=data[index];end=data[index+1];while(start<end){result.push(start);++start}index+=2}return result};var floor=Math.floor;var highSurrogate=function(codePoint){return parseInt(floor((codePoint-65536)/1024)+HIGH_SURROGATE_MIN,10)};var lowSurrogate=function(codePoint){return parseInt((codePoint-65536)%1024+LOW_SURROGATE_MIN,10)};var stringFromCharCode=String.fromCharCode;var codePointToString=function(codePoint){var string;if(codePoint==9){string="\\t"}else if(codePoint==10){string="\\n"}else if(codePoint==12){string="\\f"}else if(codePoint==13){string="\\r"}else if(codePoint==92){string="\\\\"}else if(codePoint==36||codePoint>=40&&codePoint<=43||codePoint==45||codePoint==46||codePoint==63||codePoint>=91&&codePoint<=94||codePoint>=123&&codePoint<=125){string="\\"+stringFromCharCode(codePoint)}else if(codePoint>=32&&codePoint<=126){string=stringFromCharCode(codePoint)}else if(codePoint<=255){string="\\x"+pad(hex(codePoint),2)}else{string="\\u"+pad(hex(codePoint),4)}return string};var symbolToCodePoint=function(symbol){var length=symbol.length;var first=symbol.charCodeAt(0);var second;if(first>=HIGH_SURROGATE_MIN&&first<=HIGH_SURROGATE_MAX&&length>1){second=symbol.charCodeAt(1);return(first-HIGH_SURROGATE_MIN)*1024+second-LOW_SURROGATE_MIN+65536}return first};var createBMPCharacterClasses=function(data){var result="";var index=0;var start;var end;var length=data.length;if(dataIsSingleton(data)){return codePointToString(data[0])}while(index<length){start=data[index];end=data[index+1]-1;if(start==end){result+=codePointToString(start)}else if(start+1==end){result+=codePointToString(start)+codePointToString(end)}else{result+=codePointToString(start)+"-"+codePointToString(end)}index+=2}return"["+result+"]"};var splitAtBMP=function(data){var loneHighSurrogates=[];var loneLowSurrogates=[];var bmp=[];var astral=[];var index=0;var start;var end;var length=data.length;while(index<length){start=data[index];end=data[index+1]-1;if(start<HIGH_SURROGATE_MIN){if(end<HIGH_SURROGATE_MIN){bmp.push(start,end+1)}if(end>=HIGH_SURROGATE_MIN&&end<=HIGH_SURROGATE_MAX){bmp.push(start,HIGH_SURROGATE_MIN);loneHighSurrogates.push(HIGH_SURROGATE_MIN,end+1)}if(end>=LOW_SURROGATE_MIN&&end<=LOW_SURROGATE_MAX){bmp.push(start,HIGH_SURROGATE_MIN);loneHighSurrogates.push(HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1);loneLowSurrogates.push(LOW_SURROGATE_MIN,end+1)}if(end>LOW_SURROGATE_MAX){bmp.push(start,HIGH_SURROGATE_MIN);loneHighSurrogates.push(HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1);loneLowSurrogates.push(LOW_SURROGATE_MIN,LOW_SURROGATE_MAX+1);if(end<=65535){bmp.push(LOW_SURROGATE_MAX+1,end+1)}else{bmp.push(LOW_SURROGATE_MAX+1,65535+1);astral.push(65535+1,end+1)}}}else if(start>=HIGH_SURROGATE_MIN&&start<=HIGH_SURROGATE_MAX){if(end>=HIGH_SURROGATE_MIN&&end<=HIGH_SURROGATE_MAX){loneHighSurrogates.push(start,end+1)}if(end>=LOW_SURROGATE_MIN&&end<=LOW_SURROGATE_MAX){loneHighSurrogates.push(start,HIGH_SURROGATE_MAX+1);loneLowSurrogates.push(LOW_SURROGATE_MIN,end+1)}if(end>LOW_SURROGATE_MAX){loneHighSurrogates.push(start,HIGH_SURROGATE_MAX+1);loneLowSurrogates.push(LOW_SURROGATE_MIN,LOW_SURROGATE_MAX+1);if(end<=65535){bmp.push(LOW_SURROGATE_MAX+1,end+1)}else{bmp.push(LOW_SURROGATE_MAX+1,65535+1);astral.push(65535+1,end+1)}}}else if(start>=LOW_SURROGATE_MIN&&start<=LOW_SURROGATE_MAX){if(end>=LOW_SURROGATE_MIN&&end<=LOW_SURROGATE_MAX){loneLowSurrogates.push(start,end+1)}if(end>LOW_SURROGATE_MAX){loneLowSurrogates.push(start,LOW_SURROGATE_MAX+1);if(end<=65535){bmp.push(LOW_SURROGATE_MAX+1,end+1)}else{bmp.push(LOW_SURROGATE_MAX+1,65535+1);astral.push(65535+1,end+1)}}}else if(start>LOW_SURROGATE_MAX&&start<=65535){if(end<=65535){bmp.push(start,end+1)}else{bmp.push(start,65535+1);astral.push(65535+1,end+1)}}else{astral.push(start,end+1)}index+=2}return{loneHighSurrogates:loneHighSurrogates,loneLowSurrogates:loneLowSurrogates,bmp:bmp,astral:astral}};var optimizeSurrogateMappings=function(surrogateMappings){var result=[];var tmpLow=[];var addLow=false;var mapping;var nextMapping;var highSurrogates;var lowSurrogates;var nextHighSurrogates;var nextLowSurrogates;var index=-1;var length=surrogateMappings.length;while(++index<length){mapping=surrogateMappings[index];nextMapping=surrogateMappings[index+1];if(!nextMapping){result.push(mapping);continue}highSurrogates=mapping[0];lowSurrogates=mapping[1];nextHighSurrogates=nextMapping[0];nextLowSurrogates=nextMapping[1];tmpLow=lowSurrogates;while(nextHighSurrogates&&highSurrogates[0]==nextHighSurrogates[0]&&highSurrogates[1]==nextHighSurrogates[1]){if(dataIsSingleton(nextLowSurrogates)){tmpLow=dataAdd(tmpLow,nextLowSurrogates[0])}else{tmpLow=dataAddRange(tmpLow,nextLowSurrogates[0],nextLowSurrogates[1]-1)}++index;mapping=surrogateMappings[index];highSurrogates=mapping[0];lowSurrogates=mapping[1];nextMapping=surrogateMappings[index+1];nextHighSurrogates=nextMapping&&nextMapping[0];nextLowSurrogates=nextMapping&&nextMapping[1];addLow=true}result.push([highSurrogates,addLow?tmpLow:lowSurrogates]);addLow=false}return optimizeByLowSurrogates(result)};var optimizeByLowSurrogates=function(surrogateMappings){if(surrogateMappings.length==1){return surrogateMappings}var index=-1;var innerIndex=-1;while(++index<surrogateMappings.length){var mapping=surrogateMappings[index];var lowSurrogates=mapping[1];var lowSurrogateStart=lowSurrogates[0];var lowSurrogateEnd=lowSurrogates[1];innerIndex=index;while(++innerIndex<surrogateMappings.length){var otherMapping=surrogateMappings[innerIndex];var otherLowSurrogates=otherMapping[1];var otherLowSurrogateStart=otherLowSurrogates[0];var otherLowSurrogateEnd=otherLowSurrogates[1];if(lowSurrogateStart==otherLowSurrogateStart&&lowSurrogateEnd==otherLowSurrogateEnd){if(dataIsSingleton(otherMapping[0])){mapping[0]=dataAdd(mapping[0],otherMapping[0][0])}else{mapping[0]=dataAddRange(mapping[0],otherMapping[0][0],otherMapping[0][1]-1)}surrogateMappings.splice(innerIndex,1);--innerIndex}}}return surrogateMappings};var surrogateSet=function(data){if(!data.length){return[]}var index=0;var start;var end;var startHigh;var startLow;var prevStartHigh=0;var prevEndHigh=0;var tmpLow=[];var endHigh;var endLow;var surrogateMappings=[];var length=data.length;var dataHigh=[];while(index<length){start=data[index];end=data[index+1]-1;startHigh=highSurrogate(start);startLow=lowSurrogate(start);endHigh=highSurrogate(end);endLow=lowSurrogate(end);var startsWithLowestLowSurrogate=startLow==LOW_SURROGATE_MIN;var endsWithHighestLowSurrogate=endLow==LOW_SURROGATE_MAX;var complete=false;if(startHigh==endHigh||startsWithLowestLowSurrogate&&endsWithHighestLowSurrogate){surrogateMappings.push([[startHigh,endHigh+1],[startLow,endLow+1]]);complete=true}else{surrogateMappings.push([[startHigh,startHigh+1],[startLow,LOW_SURROGATE_MAX+1]])}if(!complete&&startHigh+1<endHigh){if(endsWithHighestLowSurrogate){surrogateMappings.push([[startHigh+1,endHigh+1],[LOW_SURROGATE_MIN,endLow+1]]);complete=true}else{surrogateMappings.push([[startHigh+1,endHigh],[LOW_SURROGATE_MIN,LOW_SURROGATE_MAX+1]])}}if(!complete){surrogateMappings.push([[endHigh,endHigh+1],[LOW_SURROGATE_MIN,endLow+1]])}prevStartHigh=startHigh;prevEndHigh=endHigh;index+=2}return optimizeSurrogateMappings(surrogateMappings)};var createSurrogateCharacterClasses=function(surrogateMappings){var result=[];forEach(surrogateMappings,function(surrogateMapping){var highSurrogates=surrogateMapping[0];var lowSurrogates=surrogateMapping[1];result.push(createBMPCharacterClasses(highSurrogates)+createBMPCharacterClasses(lowSurrogates))});return result.join("|")};var createCharacterClassesFromData=function(data,bmpOnly){var result=[];var parts=splitAtBMP(data);var loneHighSurrogates=parts.loneHighSurrogates;var loneLowSurrogates=parts.loneLowSurrogates;var bmp=parts.bmp;var astral=parts.astral;var hasAstral=!dataIsEmpty(parts.astral);var hasLoneHighSurrogates=!dataIsEmpty(loneHighSurrogates);var hasLoneLowSurrogates=!dataIsEmpty(loneLowSurrogates);var surrogateMappings=surrogateSet(astral);if(bmpOnly){bmp=dataAddData(bmp,loneHighSurrogates);hasLoneHighSurrogates=false;bmp=dataAddData(bmp,loneLowSurrogates);hasLoneLowSurrogates=false}if(!dataIsEmpty(bmp)){result.push(createBMPCharacterClasses(bmp))}if(surrogateMappings.length){result.push(createSurrogateCharacterClasses(surrogateMappings))}if(hasLoneHighSurrogates){result.push(createBMPCharacterClasses(loneHighSurrogates)+"(?![\\uDC00-\\uDFFF])")}if(hasLoneLowSurrogates){result.push("(?:[^\\uD800-\\uDBFF]|^)"+createBMPCharacterClasses(loneLowSurrogates))}return result.join("|")};var regenerate=function(value){if(arguments.length>1){value=slice.call(arguments)}if(this instanceof regenerate){this.data=[];return value?this.add(value):this}return(new regenerate).add(value)};regenerate.version="1.2.0";var proto=regenerate.prototype;extend(proto,{add:function(value){var $this=this;if(value==null){return $this}if(value instanceof regenerate){$this.data=dataAddData($this.data,value.data);return $this}if(arguments.length>1){value=slice.call(arguments)}if(isArray(value)){forEach(value,function(item){$this.add(item)});return $this}$this.data=dataAdd($this.data,isNumber(value)?value:symbolToCodePoint(value));return $this},remove:function(value){var $this=this;if(value==null){return $this}if(value instanceof regenerate){$this.data=dataRemoveData($this.data,value.data);return $this}if(arguments.length>1){value=slice.call(arguments)}if(isArray(value)){forEach(value,function(item){$this.remove(item)});return $this}$this.data=dataRemove($this.data,isNumber(value)?value:symbolToCodePoint(value));return $this},addRange:function(start,end){var $this=this;$this.data=dataAddRange($this.data,isNumber(start)?start:symbolToCodePoint(start),isNumber(end)?end:symbolToCodePoint(end));return $this},removeRange:function(start,end){var $this=this;var startCodePoint=isNumber(start)?start:symbolToCodePoint(start);var endCodePoint=isNumber(end)?end:symbolToCodePoint(end);$this.data=dataRemoveRange($this.data,startCodePoint,endCodePoint);return $this},intersection:function(argument){var $this=this;var array=argument instanceof regenerate?dataToArray(argument.data):argument;$this.data=dataIntersection($this.data,array);return $this},contains:function(codePoint){return dataContains(this.data,isNumber(codePoint)?codePoint:symbolToCodePoint(codePoint))},clone:function(){var set=new regenerate;set.data=this.data.slice(0);return set},toString:function(options){var result=createCharacterClassesFromData(this.data,options?options.bmpOnly:false);return result.replace(regexNull,"\\0$1")},toRegExp:function(flags){return RegExp(this.toString(),flags||"")},valueOf:function(){return dataToArray(this.data)}});proto.toArray=proto.valueOf;if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return regenerate})}else if(freeExports&&!freeExports.nodeType){if(freeModule){freeModule.exports=regenerate}else{freeExports.regenerate=regenerate}}else{root.regenerate=regenerate}})(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],178:[function(require,module,exports){(function(global){(function(){"use strict";var objectTypes={"function":true,object:true};var root=objectTypes[typeof window]&&window||this;var oldRoot=root;var freeExports=objectTypes[typeof exports]&&exports;var freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module;var freeGlobal=freeExports&&freeModule&&typeof global=="object"&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal)){root=freeGlobal}var stringFromCharCode=String.fromCharCode;var floor=Math.floor;function fromCodePoint(){var MAX_SIZE=16384;var codeUnits=[];var highSurrogate;var lowSurrogate;var index=-1;var length=arguments.length;if(!length){return""}var result="";while(++index<length){var codePoint=Number(arguments[index]);if(!isFinite(codePoint)||codePoint<0||codePoint>1114111||floor(codePoint)!=codePoint){throw RangeError("Invalid code point: "+codePoint)}if(codePoint<=65535){codeUnits.push(codePoint)}else{codePoint-=65536;highSurrogate=(codePoint>>10)+55296;lowSurrogate=codePoint%1024+56320;codeUnits.push(highSurrogate,lowSurrogate)}if(index+1==length||codeUnits.length>MAX_SIZE){result+=stringFromCharCode.apply(null,codeUnits);codeUnits.length=0}}return result}function assertType(type,expected){if(expected.indexOf("|")==-1){if(type==expected){return}throw Error("Invalid node type: "+type)}expected=assertType.hasOwnProperty(expected)?assertType[expected]:assertType[expected]=RegExp("^(?:"+expected+")$");if(expected.test(type)){return}throw Error("Invalid node type: "+type)}function generate(node){var type=node.type;if(generate.hasOwnProperty(type)&&typeof generate[type]=="function"){return generate[type](node)}throw Error("Invalid node type: "+type)}function generateAlternative(node){assertType(node.type,"alternative");var terms=node.body,length=terms?terms.length:0;if(length==1){return generateTerm(terms[0])}else{var i=-1,result="";while(++i<length){result+=generateTerm(terms[i])}return result}}function generateAnchor(node){assertType(node.type,"anchor");switch(node.kind){case"start":return"^";case"end":return"$";case"boundary":return"\\b";case"not-boundary":return"\\B";default:throw Error("Invalid assertion")}}function generateAtom(node){assertType(node.type,"anchor|characterClass|characterClassEscape|dot|group|reference|value");return generate(node)}function generateCharacterClass(node){assertType(node.type,"characterClass");var classRanges=node.body,length=classRanges?classRanges.length:0;var i=-1,result="[";if(node.negative){result+="^"}while(++i<length){result+=generateClassAtom(classRanges[i])}result+="]";return result}function generateCharacterClassEscape(node){assertType(node.type,"characterClassEscape");return"\\"+node.value}function generateCharacterClassRange(node){assertType(node.type,"characterClassRange");var min=node.min,max=node.max;if(min.type=="characterClassRange"||max.type=="characterClassRange"){throw Error("Invalid character class range")}return generateClassAtom(min)+"-"+generateClassAtom(max)}function generateClassAtom(node){assertType(node.type,"anchor|characterClassEscape|characterClassRange|dot|value");return generate(node)}function generateDisjunction(node){assertType(node.type,"disjunction");var body=node.body,length=body?body.length:0;if(length==0){throw Error("No body")}else if(length==1){return generate(body[0])}else{var i=-1,result="";while(++i<length){if(i!=0){result+="|"}result+=generate(body[i])}return result}}function generateDot(node){assertType(node.type,"dot");return"."}function generateGroup(node){assertType(node.type,"group");var result="(";switch(node.behavior){case"normal":break;case"ignore":result+="?:";break;case"lookahead":result+="?=";break;case"negativeLookahead":result+="?!";break;default:throw Error("Invalid behaviour: "+node.behaviour)}var body=node.body,length=body?body.length:0;if(length==1){result+=generate(body[0])}else{var i=-1;while(++i<length){result+=generate(body[i])}}result+=")";return result}function generateQuantifier(node){assertType(node.type,"quantifier");var quantifier="",min=node.min,max=node.max;switch(max){case undefined:case null:switch(min){case 0:quantifier="*";break;case 1:quantifier="+";break;default:quantifier="{"+min+",}";break}break;default:if(min==max){quantifier="{"+min+"}"}else if(min==0&&max==1){quantifier="?"}else{quantifier="{"+min+","+max+"}"}break}if(!node.greedy){quantifier+="?"}return generateAtom(node.body[0])+quantifier}function generateReference(node){assertType(node.type,"reference");return"\\"+node.matchIndex}function generateTerm(node){assertType(node.type,"anchor|characterClass|characterClassEscape|empty|group|quantifier|reference|value");return generate(node)}function generateValue(node){assertType(node.type,"value");var kind=node.kind,codePoint=node.codePoint;switch(kind){case"controlLetter":return"\\c"+fromCodePoint(codePoint+64);case"hexadecimalEscape":return"\\x"+("00"+codePoint.toString(16).toUpperCase()).slice(-2);case"identifier":return"\\"+fromCodePoint(codePoint);case"null":return"\\"+codePoint;case"octal":return"\\"+codePoint.toString(8);case"singleEscape":switch(codePoint){case 8:return"\\b";case 9:return"\\t";
case 10:return"\\n";case 11:return"\\v";case 12:return"\\f";case 13:return"\\r";default:throw Error("Invalid codepoint: "+codePoint)}case"symbol":return fromCodePoint(codePoint);case"unicodeEscape":return"\\u"+("0000"+codePoint.toString(16).toUpperCase()).slice(-4);case"unicodeCodePointEscape":return"\\u{"+codePoint.toString(16).toUpperCase()+"}";default:throw Error("Unsupported node kind: "+kind)}}generate.alternative=generateAlternative;generate.anchor=generateAnchor;generate.characterClass=generateCharacterClass;generate.characterClassEscape=generateCharacterClassEscape;generate.characterClassRange=generateCharacterClassRange;generate.disjunction=generateDisjunction;generate.dot=generateDot;generate.group=generateGroup;generate.quantifier=generateQuantifier;generate.reference=generateReference;generate.value=generateValue;if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return{generate:generate}})}else if(freeExports&&freeModule){freeExports.generate=generate}else{root.regjsgen={generate:generate}}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],179:[function(require,module,exports){(function(){function parse(str,flags){var hasUnicodeFlag=(flags||"").indexOf("u")!==-1;var pos=0;var closedCaptureCounter=0;function addRaw(node){node.raw=str.substring(node.range[0],node.range[1]);return node}function updateRawStart(node,start){node.range[0]=start;return addRaw(node)}function createAnchor(kind,rawLength){return addRaw({type:"anchor",kind:kind,range:[pos-rawLength,pos]})}function createValue(kind,codePoint,from,to){return addRaw({type:"value",kind:kind,codePoint:codePoint,range:[from,to]})}function createEscaped(kind,codePoint,value,fromOffset){fromOffset=fromOffset||0;return createValue(kind,codePoint,pos-(value.length+fromOffset),pos)}function createCharacter(matches){var _char=matches[0];var first=_char.charCodeAt(0);if(hasUnicodeFlag){var second;if(_char.length===1&&first>=55296&&first<=56319){second=lookahead().charCodeAt(0);if(second>=56320&&second<=57343){pos++;return createValue("symbol",(first-55296)*1024+second-56320+65536,pos-2,pos)}}}return createValue("symbol",first,pos-1,pos)}function createDisjunction(alternatives,from,to){return addRaw({type:"disjunction",body:alternatives,range:[from,to]})}function createDot(){return addRaw({type:"dot",range:[pos-1,pos]})}function createCharacterClassEscape(value){return addRaw({type:"characterClassEscape",value:value,range:[pos-2,pos]})}function createReference(matchIndex){return addRaw({type:"reference",matchIndex:parseInt(matchIndex,10),range:[pos-1-matchIndex.length,pos]})}function createGroup(behavior,disjunction,from,to){return addRaw({type:"group",behavior:behavior,body:disjunction,range:[from,to]})}function createQuantifier(min,max,from,to){if(to==null){from=pos-1;to=pos}return addRaw({type:"quantifier",min:min,max:max,greedy:true,body:null,range:[from,to]})}function createAlternative(terms,from,to){return addRaw({type:"alternative",body:terms,range:[from,to]})}function createCharacterClass(classRanges,negative,from,to){return addRaw({type:"characterClass",body:classRanges,negative:negative,range:[from,to]})}function createClassRange(min,max,from,to){if(min.codePoint>max.codePoint){throw SyntaxError("invalid range in character class")}return addRaw({type:"characterClassRange",min:min,max:max,range:[from,to]})}function flattenBody(body){if(body.type==="alternative"){return body.body}else{return[body]}}function isEmpty(obj){return obj.type==="empty"}function incr(amount){amount=amount||1;var res=str.substring(pos,pos+amount);pos+=amount||1;return res}function skip(value){if(!match(value)){throw SyntaxError("character: "+value)}}function match(value){if(str.indexOf(value,pos)===pos){return incr(value.length)}}function lookahead(){return str[pos]}function current(value){return str.indexOf(value,pos)===pos}function next(value){return str[pos+1]===value}function matchReg(regExp){var subStr=str.substring(pos);var res=subStr.match(regExp);if(res){res.range=[];res.range[0]=pos;incr(res[0].length);res.range[1]=pos}return res}function parseDisjunction(){var res=[],from=pos;res.push(parseAlternative());while(match("|")){res.push(parseAlternative())}if(res.length===1){return res[0]}return createDisjunction(res,from,pos)}function parseAlternative(){var res=[],from=pos;var term;while(term=parseTerm()){res.push(term)}if(res.length===1){return res[0]}return createAlternative(res,from,pos)}function parseTerm(){if(pos>=str.length||current("|")||current(")")){return null}var anchor=parseAnchor();if(anchor){return anchor}var atom=parseAtom();if(!atom){throw SyntaxError("Expected atom")}var quantifier=parseQuantifier()||false;if(quantifier){quantifier.body=flattenBody(atom);updateRawStart(quantifier,atom.range[0]);return quantifier}return atom}function parseGroup(matchA,typeA,matchB,typeB){var type=null,from=pos;if(match(matchA)){type=typeA}else if(match(matchB)){type=typeB}else{return false}var body=parseDisjunction();if(!body){throw SyntaxError("Expected disjunction")}skip(")");var group=createGroup(type,flattenBody(body),from,pos);if(type=="normal"){closedCaptureCounter++}return group}function parseAnchor(){var res,from=pos;if(match("^")){return createAnchor("start",1)}else if(match("$")){return createAnchor("end",1)}else if(match("\\b")){return createAnchor("boundary",2)}else if(match("\\B")){return createAnchor("not-boundary",2)}else{return parseGroup("(?=","lookahead","(?!","negativeLookahead")}}function parseQuantifier(){var res;var quantifier;var min,max;if(match("*")){quantifier=createQuantifier(0)}else if(match("+")){quantifier=createQuantifier(1)}else if(match("?")){quantifier=createQuantifier(0,1)}else if(res=matchReg(/^\{([0-9]+)\}/)){min=parseInt(res[1],10);quantifier=createQuantifier(min,min,res.range[0],res.range[1])}else if(res=matchReg(/^\{([0-9]+),\}/)){min=parseInt(res[1],10);quantifier=createQuantifier(min,undefined,res.range[0],res.range[1])}else if(res=matchReg(/^\{([0-9]+),([0-9]+)\}/)){min=parseInt(res[1],10);max=parseInt(res[2],10);if(min>max){throw SyntaxError("numbers out of order in {} quantifier")}quantifier=createQuantifier(min,max,res.range[0],res.range[1])}if(quantifier){if(match("?")){quantifier.greedy=false;quantifier.range[1]+=1}}return quantifier}function parseAtom(){var res;if(res=matchReg(/^[^^$\\.*+?(){[|]/)){return createCharacter(res)}else if(match(".")){return createDot()}else if(match("\\")){res=parseAtomEscape();if(!res){throw SyntaxError("atomEscape")}return res}else if(res=parseCharacterClass()){return res}else{return parseGroup("(?:","ignore","(","normal")}}function parseUnicodeSurrogatePairEscape(firstEscape){if(hasUnicodeFlag){var first,second;if(firstEscape.kind=="unicodeEscape"&&(first=firstEscape.codePoint)>=55296&&first<=56319&¤t("\\")&&next("u")){var prevPos=pos;pos++;var secondEscape=parseClassEscape();if(secondEscape.kind=="unicodeEscape"&&(second=secondEscape.codePoint)>=56320&&second<=57343){firstEscape.range[1]=secondEscape.range[1];firstEscape.codePoint=(first-55296)*1024+second-56320+65536;firstEscape.type="value";firstEscape.kind="unicodeCodePointEscape";addRaw(firstEscape)}else{pos=prevPos}}}return firstEscape}function parseClassEscape(){return parseAtomEscape(true)}function parseAtomEscape(insideCharacterClass){var res;res=parseDecimalEscape();if(res){return res}if(insideCharacterClass){if(match("b")){return createEscaped("singleEscape",8,"\\b")}else if(match("B")){throw SyntaxError("\\B not possible inside of CharacterClass")}}res=parseCharacterEscape();return res}function parseDecimalEscape(){var res,match;if(res=matchReg(/^(?!0)\d+/)){match=res[0];var refIdx=parseInt(res[0],10);if(refIdx<=closedCaptureCounter){return createReference(res[0])}else{incr(-res[0].length);if(res=matchReg(/^[0-7]{1,3}/)){return createEscaped("octal",parseInt(res[0],8),res[0],1)}else{res=createCharacter(matchReg(/^[89]/));return updateRawStart(res,res.range[0]-1)}}}else if(res=matchReg(/^[0-7]{1,3}/)){match=res[0];if(/^0{1,3}$/.test(match)){return createEscaped("null",0,"0",match.length+1)}else{return createEscaped("octal",parseInt(match,8),match,1)}}else if(res=matchReg(/^[dDsSwW]/)){return createCharacterClassEscape(res[0])}return false}function parseCharacterEscape(){var res;if(res=matchReg(/^[fnrtv]/)){var codePoint=0;switch(res[0]){case"t":codePoint=9;break;case"n":codePoint=10;break;case"v":codePoint=11;break;case"f":codePoint=12;break;case"r":codePoint=13;break}return createEscaped("singleEscape",codePoint,"\\"+res[0])}else if(res=matchReg(/^c([a-zA-Z])/)){return createEscaped("controlLetter",res[1].charCodeAt(0)%32,res[1],2)}else if(res=matchReg(/^x([0-9a-fA-F]{2})/)){return createEscaped("hexadecimalEscape",parseInt(res[1],16),res[1],2)}else if(res=matchReg(/^u([0-9a-fA-F]{4})/)){return parseUnicodeSurrogatePairEscape(createEscaped("unicodeEscape",parseInt(res[1],16),res[1],2))}else if(hasUnicodeFlag&&(res=matchReg(/^u\{([0-9a-fA-F]{1,})\}/))){return createEscaped("unicodeCodePointEscape",parseInt(res[1],16),res[1],4)}else{return parseIdentityEscape()}}function isIdentifierPart(ch){var NonAsciiIdentifierPart=new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԯԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠ-ࢲࣤ-ॣ०-९ॱ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఀ-ఃఅ-ఌఎ-ఐఒ-నప-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಁ-ಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲഁ-ഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟ෦-෯ෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤞᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧ᪰-᪽ᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶ᳸᳹ᴀ-᷵᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚝꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꧠ-ꧾꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︭︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]");return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=48&&ch<=57||ch===92||ch>=128&&NonAsciiIdentifierPart.test(String.fromCharCode(ch))}function parseIdentityEscape(){var ZWJ="";var ZWNJ="";var res;var tmp;if(!isIdentifierPart(lookahead())){tmp=incr();return createEscaped("identifier",tmp.charCodeAt(0),tmp,1)}if(match(ZWJ)){return createEscaped("identifier",8204,ZWJ)}else if(match(ZWNJ)){return createEscaped("identifier",8205,ZWNJ)}return null}function parseCharacterClass(){var res,from=pos;if(res=matchReg(/^\[\^/)){res=parseClassRanges();skip("]");return createCharacterClass(res,true,from,pos)}else if(match("[")){res=parseClassRanges();skip("]");return createCharacterClass(res,false,from,pos)}return null}function parseClassRanges(){var res;if(current("]")){return[]}else{res=parseNonemptyClassRanges();if(!res){throw SyntaxError("nonEmptyClassRanges")}return res}}function parseHelperClassRanges(atom){var from,to,res;if(current("-")&&!next("]")){skip("-");res=parseClassAtom();if(!res){throw SyntaxError("classAtom")}to=pos;var classRanges=parseClassRanges();if(!classRanges){throw SyntaxError("classRanges")}from=atom.range[0];if(classRanges.type==="empty"){return[createClassRange(atom,res,from,to)]}return[createClassRange(atom,res,from,to)].concat(classRanges)}res=parseNonemptyClassRangesNoDash();if(!res){throw SyntaxError("nonEmptyClassRangesNoDash")}return[atom].concat(res)}function parseNonemptyClassRanges(){var atom=parseClassAtom();if(!atom){throw SyntaxError("classAtom")}if(current("]")){return[atom]}return parseHelperClassRanges(atom)}function parseNonemptyClassRangesNoDash(){var res=parseClassAtom();if(!res){throw SyntaxError("classAtom")}if(current("]")){return res}return parseHelperClassRanges(res)}function parseClassAtom(){if(match("-")){return createCharacter("-")}else{return parseClassAtomNoDash()}}function parseClassAtomNoDash(){var res;if(res=matchReg(/^[^\\\]-]/)){return createCharacter(res[0])}else if(match("\\")){res=parseClassEscape();if(!res){throw SyntaxError("classEscape")}return parseUnicodeSurrogatePairEscape(res)}}str=String(str);if(str===""){str="(?:)"}var result=parseDisjunction();if(result.range[1]!==str.length){throw SyntaxError("Could not parse entire input - got stuck: "+str)}return result}var regjsparser={parse:parse};if(typeof module!=="undefined"&&module.exports){module.exports=regjsparser}else{window.regjsparser=regjsparser}})()},{}],180:[function(require,module,exports){var generate=require("regjsgen").generate;var parse=require("regjsparser").parse;var regenerate=require("regenerate");var iuMappings=require("./data/iu-mappings.json");var ESCAPE_SETS=require("./data/character-class-escape-sets.js");function getCharacterClassEscapeSet(character){if(unicode){if(ignoreCase){return ESCAPE_SETS.UNICODE_IGNORE_CASE[character]}return ESCAPE_SETS.UNICODE[character]}return ESCAPE_SETS.REGULAR[character]}var object={};var hasOwnProperty=object.hasOwnProperty;function has(object,property){return hasOwnProperty.call(object,property)}var UNICODE_SET=regenerate().addRange(0,1114111);var BMP_SET=regenerate().addRange(0,65535);var DOT_SET_UNICODE=UNICODE_SET.clone().remove(10,13,8232,8233);var DOT_SET=DOT_SET_UNICODE.clone().intersection(BMP_SET);regenerate.prototype.iuAddRange=function(min,max){var $this=this;do{var folded=caseFold(min);if(folded){$this.add(folded)}}while(++min<=max);return $this};function assign(target,source){for(var key in source){target[key]=source[key]}}function update(item,pattern){var tree=parse(pattern,"");switch(tree.type){case"characterClass":case"group":case"value":break;default:tree=wrap(tree,pattern)}assign(item,tree)}function wrap(tree,pattern){return{type:"group",behavior:"ignore",body:[tree],raw:"(?:"+pattern+")"}}function caseFold(codePoint){return has(iuMappings,codePoint)?iuMappings[codePoint]:false}var ignoreCase=false;var unicode=false;function processCharacterClass(characterClassItem){var set=regenerate();var body=characterClassItem.body.forEach(function(item){switch(item.type){case"value":set.add(item.codePoint);if(ignoreCase&&unicode){var folded=caseFold(item.codePoint);if(folded){set.add(folded)}}break;case"characterClassRange":var min=item.min.codePoint;var max=item.max.codePoint;set.addRange(min,max);if(ignoreCase&&unicode){set.iuAddRange(min,max)}break;case"characterClassEscape":set.add(getCharacterClassEscapeSet(item.value));break;default:throw Error("Unknown term type: "+item.type)}});if(characterClassItem.negative){set=(unicode?UNICODE_SET:BMP_SET).clone().remove(set)}update(characterClassItem,set.toString());return characterClassItem}function processTerm(item){switch(item.type){case"dot":update(item,(unicode?DOT_SET_UNICODE:DOT_SET).toString());break;case"characterClass":item=processCharacterClass(item);break;case"characterClassEscape":update(item,getCharacterClassEscapeSet(item.value).toString());break;case"alternative":case"disjunction":case"group":case"quantifier":item.body=item.body.map(processTerm);break;case"value":var codePoint=item.codePoint;var set=regenerate(codePoint);if(ignoreCase&&unicode){var folded=caseFold(codePoint);if(folded){set.add(folded)}}update(item,set.toString());break;case"anchor":case"empty":case"group":case"reference":break;default:throw Error("Unknown term type: "+item.type)}return item}module.exports=function(pattern,flags){var tree=parse(pattern,flags);ignoreCase=flags?flags.indexOf("i")>-1:false;unicode=flags?flags.indexOf("u")>-1:false;assign(tree,processTerm(tree));return generate(tree)}},{"./data/character-class-escape-sets.js":175,"./data/iu-mappings.json":176,regenerate:177,regjsgen:178,regjsparser:179}],181:[function(require,module,exports){exports.SourceMapGenerator=require("./source-map/source-map-generator").SourceMapGenerator;exports.SourceMapConsumer=require("./source-map/source-map-consumer").SourceMapConsumer;exports.SourceNode=require("./source-map/source-node").SourceNode},{"./source-map/source-map-consumer":187,"./source-map/source-map-generator":188,"./source-map/source-node":189}],182:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var util=require("./util");function ArraySet(){this._array=[];this._set={}}ArraySet.fromArray=function ArraySet_fromArray(aArray,aAllowDuplicates){var set=new ArraySet;for(var i=0,len=aArray.length;i<len;i++){set.add(aArray[i],aAllowDuplicates)}return set};ArraySet.prototype.add=function ArraySet_add(aStr,aAllowDuplicates){var isDuplicate=this.has(aStr);var idx=this._array.length;if(!isDuplicate||aAllowDuplicates){this._array.push(aStr)}if(!isDuplicate){this._set[util.toSetString(aStr)]=idx}};ArraySet.prototype.has=function ArraySet_has(aStr){return Object.prototype.hasOwnProperty.call(this._set,util.toSetString(aStr))};ArraySet.prototype.indexOf=function ArraySet_indexOf(aStr){if(this.has(aStr)){return this._set[util.toSetString(aStr)]}throw new Error('"'+aStr+'" is not in the set.')};ArraySet.prototype.at=function ArraySet_at(aIdx){if(aIdx>=0&&aIdx<this._array.length){return this._array[aIdx]}throw new Error("No element indexed by "+aIdx)};ArraySet.prototype.toArray=function ArraySet_toArray(){return this._array.slice()};exports.ArraySet=ArraySet})},{"./util":190,amdefine:191}],183:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var base64=require("./base64");var VLQ_BASE_SHIFT=5;var VLQ_BASE=1<<VLQ_BASE_SHIFT;var VLQ_BASE_MASK=VLQ_BASE-1;var VLQ_CONTINUATION_BIT=VLQ_BASE;function toVLQSigned(aValue){return aValue<0?(-aValue<<1)+1:(aValue<<1)+0}function fromVLQSigned(aValue){var isNegative=(aValue&1)===1;var shifted=aValue>>1;return isNegative?-shifted:shifted}exports.encode=function base64VLQ_encode(aValue){var encoded="";var digit;var vlq=toVLQSigned(aValue);do{digit=vlq&VLQ_BASE_MASK;vlq>>>=VLQ_BASE_SHIFT;if(vlq>0){digit|=VLQ_CONTINUATION_BIT}encoded+=base64.encode(digit)}while(vlq>0);return encoded};exports.decode=function base64VLQ_decode(aStr,aOutParam){var i=0;var strLen=aStr.length;var result=0;var shift=0;var continuation,digit;do{if(i>=strLen){throw new Error("Expected more digits in base 64 VLQ value.")}digit=base64.decode(aStr.charAt(i++));continuation=!!(digit&VLQ_CONTINUATION_BIT);digit&=VLQ_BASE_MASK;result=result+(digit<<shift);shift+=VLQ_BASE_SHIFT}while(continuation);aOutParam.value=fromVLQSigned(result);aOutParam.rest=aStr.slice(i)}})},{"./base64":184,amdefine:191}],184:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var charToIntMap={};var intToCharMap={};"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").forEach(function(ch,index){charToIntMap[ch]=index;intToCharMap[index]=ch});exports.encode=function base64_encode(aNumber){if(aNumber in intToCharMap){return intToCharMap[aNumber]}throw new TypeError("Must be between 0 and 63: "+aNumber)};exports.decode=function base64_decode(aChar){if(aChar in charToIntMap){return charToIntMap[aChar]}throw new TypeError("Not a valid base 64 digit: "+aChar)}})},{amdefine:191}],185:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){function recursiveSearch(aLow,aHigh,aNeedle,aHaystack,aCompare){var mid=Math.floor((aHigh-aLow)/2)+aLow;var cmp=aCompare(aNeedle,aHaystack[mid],true);if(cmp===0){return mid}else if(cmp>0){if(aHigh-mid>1){return recursiveSearch(mid,aHigh,aNeedle,aHaystack,aCompare)}return mid}else{if(mid-aLow>1){return recursiveSearch(aLow,mid,aNeedle,aHaystack,aCompare)}return aLow<0?-1:aLow}}exports.search=function search(aNeedle,aHaystack,aCompare){if(aHaystack.length===0){return-1}return recursiveSearch(-1,aHaystack.length,aNeedle,aHaystack,aCompare)}})},{amdefine:191}],186:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var util=require("./util");function generatedPositionAfter(mappingA,mappingB){var lineA=mappingA.generatedLine;var lineB=mappingB.generatedLine;var columnA=mappingA.generatedColumn;var columnB=mappingB.generatedColumn;return lineB>lineA||lineB==lineA&&columnB>=columnA||util.compareByGeneratedPositions(mappingA,mappingB)<=0}function MappingList(){this._array=[];this._sorted=true;this._last={generatedLine:-1,generatedColumn:0}}MappingList.prototype.unsortedForEach=function MappingList_forEach(aCallback,aThisArg){this._array.forEach(aCallback,aThisArg)};MappingList.prototype.add=function MappingList_add(aMapping){var mapping;if(generatedPositionAfter(this._last,aMapping)){this._last=aMapping;this._array.push(aMapping)}else{this._sorted=false;this._array.push(aMapping)}};MappingList.prototype.toArray=function MappingList_toArray(){if(!this._sorted){this._array.sort(util.compareByGeneratedPositions);this._sorted=true}return this._array};exports.MappingList=MappingList})},{"./util":190,amdefine:191}],187:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var util=require("./util");var binarySearch=require("./binary-search");var ArraySet=require("./array-set").ArraySet;var base64VLQ=require("./base64-vlq");function SourceMapConsumer(aSourceMap){var sourceMap=aSourceMap;if(typeof aSourceMap==="string"){sourceMap=JSON.parse(aSourceMap.replace(/^\)\]\}'/,""))}var version=util.getArg(sourceMap,"version");var sources=util.getArg(sourceMap,"sources");var names=util.getArg(sourceMap,"names",[]);var sourceRoot=util.getArg(sourceMap,"sourceRoot",null);var sourcesContent=util.getArg(sourceMap,"sourcesContent",null);var mappings=util.getArg(sourceMap,"mappings");var file=util.getArg(sourceMap,"file",null);if(version!=this._version){throw new Error("Unsupported version: "+version)}sources=sources.map(util.normalize);this._names=ArraySet.fromArray(names,true);this._sources=ArraySet.fromArray(sources,true);this.sourceRoot=sourceRoot;this.sourcesContent=sourcesContent;this._mappings=mappings;this.file=file}SourceMapConsumer.fromSourceMap=function SourceMapConsumer_fromSourceMap(aSourceMap){var smc=Object.create(SourceMapConsumer.prototype);smc._names=ArraySet.fromArray(aSourceMap._names.toArray(),true);smc._sources=ArraySet.fromArray(aSourceMap._sources.toArray(),true);smc.sourceRoot=aSourceMap._sourceRoot;smc.sourcesContent=aSourceMap._generateSourcesContent(smc._sources.toArray(),smc.sourceRoot);smc.file=aSourceMap._file;smc.__generatedMappings=aSourceMap._mappings.toArray().slice();smc.__originalMappings=aSourceMap._mappings.toArray().slice().sort(util.compareByOriginalPositions);return smc};SourceMapConsumer.prototype._version=3;Object.defineProperty(SourceMapConsumer.prototype,"sources",{get:function(){return this._sources.toArray().map(function(s){return this.sourceRoot!=null?util.join(this.sourceRoot,s):s},this)}});SourceMapConsumer.prototype.__generatedMappings=null;Object.defineProperty(SourceMapConsumer.prototype,"_generatedMappings",{get:function(){if(!this.__generatedMappings){this.__generatedMappings=[];this.__originalMappings=[];this._parseMappings(this._mappings,this.sourceRoot)}return this.__generatedMappings}});SourceMapConsumer.prototype.__originalMappings=null;Object.defineProperty(SourceMapConsumer.prototype,"_originalMappings",{get:function(){if(!this.__originalMappings){this.__generatedMappings=[];this.__originalMappings=[];this._parseMappings(this._mappings,this.sourceRoot)}return this.__originalMappings}});SourceMapConsumer.prototype._nextCharIsMappingSeparator=function SourceMapConsumer_nextCharIsMappingSeparator(aStr){var c=aStr.charAt(0);return c===";"||c===","};SourceMapConsumer.prototype._parseMappings=function SourceMapConsumer_parseMappings(aStr,aSourceRoot){var generatedLine=1;var previousGeneratedColumn=0;var previousOriginalLine=0;var previousOriginalColumn=0;var previousSource=0;var previousName=0;var str=aStr;var temp={};var mapping;while(str.length>0){if(str.charAt(0)===";"){generatedLine++;str=str.slice(1);previousGeneratedColumn=0}else if(str.charAt(0)===","){str=str.slice(1)}else{mapping={};mapping.generatedLine=generatedLine;base64VLQ.decode(str,temp);mapping.generatedColumn=previousGeneratedColumn+temp.value;previousGeneratedColumn=mapping.generatedColumn;str=temp.rest;if(str.length>0&&!this._nextCharIsMappingSeparator(str)){base64VLQ.decode(str,temp);mapping.source=this._sources.at(previousSource+temp.value);previousSource+=temp.value;str=temp.rest;if(str.length===0||this._nextCharIsMappingSeparator(str)){throw new Error("Found a source, but no line and column")}base64VLQ.decode(str,temp);mapping.originalLine=previousOriginalLine+temp.value;previousOriginalLine=mapping.originalLine;mapping.originalLine+=1;str=temp.rest;if(str.length===0||this._nextCharIsMappingSeparator(str)){throw new Error("Found a source and line, but no column")}base64VLQ.decode(str,temp);mapping.originalColumn=previousOriginalColumn+temp.value;previousOriginalColumn=mapping.originalColumn;str=temp.rest;if(str.length>0&&!this._nextCharIsMappingSeparator(str)){base64VLQ.decode(str,temp);mapping.name=this._names.at(previousName+temp.value);previousName+=temp.value;str=temp.rest}}this.__generatedMappings.push(mapping);if(typeof mapping.originalLine==="number"){this.__originalMappings.push(mapping)}}}this.__generatedMappings.sort(util.compareByGeneratedPositions);this.__originalMappings.sort(util.compareByOriginalPositions)};SourceMapConsumer.prototype._findMapping=function SourceMapConsumer_findMapping(aNeedle,aMappings,aLineName,aColumnName,aComparator){if(aNeedle[aLineName]<=0){throw new TypeError("Line must be greater than or equal to 1, got "+aNeedle[aLineName])}if(aNeedle[aColumnName]<0){throw new TypeError("Column must be greater than or equal to 0, got "+aNeedle[aColumnName])}return binarySearch.search(aNeedle,aMappings,aComparator)};SourceMapConsumer.prototype.computeColumnSpans=function SourceMapConsumer_computeColumnSpans(){for(var index=0;index<this._generatedMappings.length;++index){var mapping=this._generatedMappings[index];if(index+1<this._generatedMappings.length){var nextMapping=this._generatedMappings[index+1];if(mapping.generatedLine===nextMapping.generatedLine){mapping.lastGeneratedColumn=nextMapping.generatedColumn-1;continue}}mapping.lastGeneratedColumn=Infinity}};SourceMapConsumer.prototype.originalPositionFor=function SourceMapConsumer_originalPositionFor(aArgs){var needle={generatedLine:util.getArg(aArgs,"line"),generatedColumn:util.getArg(aArgs,"column")};var index=this._findMapping(needle,this._generatedMappings,"generatedLine","generatedColumn",util.compareByGeneratedPositions);if(index>=0){var mapping=this._generatedMappings[index];if(mapping.generatedLine===needle.generatedLine){var source=util.getArg(mapping,"source",null);if(source!=null&&this.sourceRoot!=null){source=util.join(this.sourceRoot,source)}return{source:source,line:util.getArg(mapping,"originalLine",null),column:util.getArg(mapping,"originalColumn",null),name:util.getArg(mapping,"name",null)}}}return{source:null,line:null,column:null,name:null}};SourceMapConsumer.prototype.sourceContentFor=function SourceMapConsumer_sourceContentFor(aSource){if(!this.sourcesContent){return null}if(this.sourceRoot!=null){aSource=util.relative(this.sourceRoot,aSource)}if(this._sources.has(aSource)){return this.sourcesContent[this._sources.indexOf(aSource)]}var url;if(this.sourceRoot!=null&&(url=util.urlParse(this.sourceRoot))){var fileUriAbsPath=aSource.replace(/^file:\/\//,"");if(url.scheme=="file"&&this._sources.has(fileUriAbsPath)){return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]}if((!url.path||url.path=="/")&&this._sources.has("/"+aSource)){return this.sourcesContent[this._sources.indexOf("/"+aSource)]}}throw new Error('"'+aSource+'" is not in the SourceMap.')};SourceMapConsumer.prototype.generatedPositionFor=function SourceMapConsumer_generatedPositionFor(aArgs){var needle={source:util.getArg(aArgs,"source"),originalLine:util.getArg(aArgs,"line"),originalColumn:util.getArg(aArgs,"column")};if(this.sourceRoot!=null){needle.source=util.relative(this.sourceRoot,needle.source)}var index=this._findMapping(needle,this._originalMappings,"originalLine","originalColumn",util.compareByOriginalPositions);if(index>=0){var mapping=this._originalMappings[index];return{line:util.getArg(mapping,"generatedLine",null),column:util.getArg(mapping,"generatedColumn",null),lastColumn:util.getArg(mapping,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}};SourceMapConsumer.prototype.allGeneratedPositionsFor=function SourceMapConsumer_allGeneratedPositionsFor(aArgs){var needle={source:util.getArg(aArgs,"source"),originalLine:util.getArg(aArgs,"line"),originalColumn:Infinity};if(this.sourceRoot!=null){needle.source=util.relative(this.sourceRoot,needle.source)}var mappings=[];var index=this._findMapping(needle,this._originalMappings,"originalLine","originalColumn",util.compareByOriginalPositions);if(index>=0){var mapping=this._originalMappings[index];while(mapping&&mapping.originalLine===needle.originalLine){mappings.push({line:util.getArg(mapping,"generatedLine",null),column:util.getArg(mapping,"generatedColumn",null),lastColumn:util.getArg(mapping,"lastGeneratedColumn",null)});mapping=this._originalMappings[--index]}}return mappings.reverse()};SourceMapConsumer.GENERATED_ORDER=1;SourceMapConsumer.ORIGINAL_ORDER=2;SourceMapConsumer.prototype.eachMapping=function SourceMapConsumer_eachMapping(aCallback,aContext,aOrder){var context=aContext||null;var order=aOrder||SourceMapConsumer.GENERATED_ORDER;var mappings;switch(order){case SourceMapConsumer.GENERATED_ORDER:mappings=this._generatedMappings;break;case SourceMapConsumer.ORIGINAL_ORDER:mappings=this._originalMappings;break;default:throw new Error("Unknown order of iteration.")}var sourceRoot=this.sourceRoot;mappings.map(function(mapping){var source=mapping.source;if(source!=null&&sourceRoot!=null){source=util.join(sourceRoot,source)}return{source:source,generatedLine:mapping.generatedLine,generatedColumn:mapping.generatedColumn,originalLine:mapping.originalLine,originalColumn:mapping.originalColumn,name:mapping.name}}).forEach(aCallback,context)};exports.SourceMapConsumer=SourceMapConsumer})},{"./array-set":182,"./base64-vlq":183,"./binary-search":185,"./util":190,amdefine:191}],188:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var base64VLQ=require("./base64-vlq");var util=require("./util");var ArraySet=require("./array-set").ArraySet;var MappingList=require("./mapping-list").MappingList;function SourceMapGenerator(aArgs){if(!aArgs){aArgs={}}this._file=util.getArg(aArgs,"file",null);this._sourceRoot=util.getArg(aArgs,"sourceRoot",null);this._skipValidation=util.getArg(aArgs,"skipValidation",false);this._sources=new ArraySet;this._names=new ArraySet;this._mappings=new MappingList;this._sourcesContents=null}SourceMapGenerator.prototype._version=3;SourceMapGenerator.fromSourceMap=function SourceMapGenerator_fromSourceMap(aSourceMapConsumer){var sourceRoot=aSourceMapConsumer.sourceRoot;var generator=new SourceMapGenerator({file:aSourceMapConsumer.file,sourceRoot:sourceRoot});aSourceMapConsumer.eachMapping(function(mapping){var newMapping={generated:{line:mapping.generatedLine,column:mapping.generatedColumn}};if(mapping.source!=null){newMapping.source=mapping.source;if(sourceRoot!=null){newMapping.source=util.relative(sourceRoot,newMapping.source)}newMapping.original={line:mapping.originalLine,column:mapping.originalColumn};
if(mapping.name!=null){newMapping.name=mapping.name}}generator.addMapping(newMapping)});aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){generator.setSourceContent(sourceFile,content)}});return generator};SourceMapGenerator.prototype.addMapping=function SourceMapGenerator_addMapping(aArgs){var generated=util.getArg(aArgs,"generated");var original=util.getArg(aArgs,"original",null);var source=util.getArg(aArgs,"source",null);var name=util.getArg(aArgs,"name",null);if(!this._skipValidation){this._validateMapping(generated,original,source,name)}if(source!=null&&!this._sources.has(source)){this._sources.add(source)}if(name!=null&&!this._names.has(name)){this._names.add(name)}this._mappings.add({generatedLine:generated.line,generatedColumn:generated.column,originalLine:original!=null&&original.line,originalColumn:original!=null&&original.column,source:source,name:name})};SourceMapGenerator.prototype.setSourceContent=function SourceMapGenerator_setSourceContent(aSourceFile,aSourceContent){var source=aSourceFile;if(this._sourceRoot!=null){source=util.relative(this._sourceRoot,source)}if(aSourceContent!=null){if(!this._sourcesContents){this._sourcesContents={}}this._sourcesContents[util.toSetString(source)]=aSourceContent}else if(this._sourcesContents){delete this._sourcesContents[util.toSetString(source)];if(Object.keys(this._sourcesContents).length===0){this._sourcesContents=null}}};SourceMapGenerator.prototype.applySourceMap=function SourceMapGenerator_applySourceMap(aSourceMapConsumer,aSourceFile,aSourceMapPath){var sourceFile=aSourceFile;if(aSourceFile==null){if(aSourceMapConsumer.file==null){throw new Error("SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, "+'or the source map\'s "file" property. Both were omitted.')}sourceFile=aSourceMapConsumer.file}var sourceRoot=this._sourceRoot;if(sourceRoot!=null){sourceFile=util.relative(sourceRoot,sourceFile)}var newSources=new ArraySet;var newNames=new ArraySet;this._mappings.unsortedForEach(function(mapping){if(mapping.source===sourceFile&&mapping.originalLine!=null){var original=aSourceMapConsumer.originalPositionFor({line:mapping.originalLine,column:mapping.originalColumn});if(original.source!=null){mapping.source=original.source;if(aSourceMapPath!=null){mapping.source=util.join(aSourceMapPath,mapping.source)}if(sourceRoot!=null){mapping.source=util.relative(sourceRoot,mapping.source)}mapping.originalLine=original.line;mapping.originalColumn=original.column;if(original.name!=null){mapping.name=original.name}}}var source=mapping.source;if(source!=null&&!newSources.has(source)){newSources.add(source)}var name=mapping.name;if(name!=null&&!newNames.has(name)){newNames.add(name)}},this);this._sources=newSources;this._names=newNames;aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){if(aSourceMapPath!=null){sourceFile=util.join(aSourceMapPath,sourceFile)}if(sourceRoot!=null){sourceFile=util.relative(sourceRoot,sourceFile)}this.setSourceContent(sourceFile,content)}},this)};SourceMapGenerator.prototype._validateMapping=function SourceMapGenerator_validateMapping(aGenerated,aOriginal,aSource,aName){if(aGenerated&&"line"in aGenerated&&"column"in aGenerated&&aGenerated.line>0&&aGenerated.column>=0&&!aOriginal&&!aSource&&!aName){return}else if(aGenerated&&"line"in aGenerated&&"column"in aGenerated&&aOriginal&&"line"in aOriginal&&"column"in aOriginal&&aGenerated.line>0&&aGenerated.column>=0&&aOriginal.line>0&&aOriginal.column>=0&&aSource){return}else{throw new Error("Invalid mapping: "+JSON.stringify({generated:aGenerated,source:aSource,original:aOriginal,name:aName}))}};SourceMapGenerator.prototype._serializeMappings=function SourceMapGenerator_serializeMappings(){var previousGeneratedColumn=0;var previousGeneratedLine=1;var previousOriginalColumn=0;var previousOriginalLine=0;var previousName=0;var previousSource=0;var result="";var mapping;var mappings=this._mappings.toArray();for(var i=0,len=mappings.length;i<len;i++){mapping=mappings[i];if(mapping.generatedLine!==previousGeneratedLine){previousGeneratedColumn=0;while(mapping.generatedLine!==previousGeneratedLine){result+=";";previousGeneratedLine++}}else{if(i>0){if(!util.compareByGeneratedPositions(mapping,mappings[i-1])){continue}result+=","}}result+=base64VLQ.encode(mapping.generatedColumn-previousGeneratedColumn);previousGeneratedColumn=mapping.generatedColumn;if(mapping.source!=null){result+=base64VLQ.encode(this._sources.indexOf(mapping.source)-previousSource);previousSource=this._sources.indexOf(mapping.source);result+=base64VLQ.encode(mapping.originalLine-1-previousOriginalLine);previousOriginalLine=mapping.originalLine-1;result+=base64VLQ.encode(mapping.originalColumn-previousOriginalColumn);previousOriginalColumn=mapping.originalColumn;if(mapping.name!=null){result+=base64VLQ.encode(this._names.indexOf(mapping.name)-previousName);previousName=this._names.indexOf(mapping.name)}}}return result};SourceMapGenerator.prototype._generateSourcesContent=function SourceMapGenerator_generateSourcesContent(aSources,aSourceRoot){return aSources.map(function(source){if(!this._sourcesContents){return null}if(aSourceRoot!=null){source=util.relative(aSourceRoot,source)}var key=util.toSetString(source);return Object.prototype.hasOwnProperty.call(this._sourcesContents,key)?this._sourcesContents[key]:null},this)};SourceMapGenerator.prototype.toJSON=function SourceMapGenerator_toJSON(){var map={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};if(this._file!=null){map.file=this._file}if(this._sourceRoot!=null){map.sourceRoot=this._sourceRoot}if(this._sourcesContents){map.sourcesContent=this._generateSourcesContent(map.sources,map.sourceRoot)}return map};SourceMapGenerator.prototype.toString=function SourceMapGenerator_toString(){return JSON.stringify(this)};exports.SourceMapGenerator=SourceMapGenerator})},{"./array-set":182,"./base64-vlq":183,"./mapping-list":186,"./util":190,amdefine:191}],189:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var SourceMapGenerator=require("./source-map-generator").SourceMapGenerator;var util=require("./util");var REGEX_NEWLINE=/(\r?\n)/;var NEWLINE_CODE=10;var isSourceNode="$$$isSourceNode$$$";function SourceNode(aLine,aColumn,aSource,aChunks,aName){this.children=[];this.sourceContents={};this.line=aLine==null?null:aLine;this.column=aColumn==null?null:aColumn;this.source=aSource==null?null:aSource;this.name=aName==null?null:aName;this[isSourceNode]=true;if(aChunks!=null)this.add(aChunks)}SourceNode.fromStringWithSourceMap=function SourceNode_fromStringWithSourceMap(aGeneratedCode,aSourceMapConsumer,aRelativePath){var node=new SourceNode;var remainingLines=aGeneratedCode.split(REGEX_NEWLINE);var shiftNextLine=function(){var lineContents=remainingLines.shift();var newLine=remainingLines.shift()||"";return lineContents+newLine};var lastGeneratedLine=1,lastGeneratedColumn=0;var lastMapping=null;aSourceMapConsumer.eachMapping(function(mapping){if(lastMapping!==null){if(lastGeneratedLine<mapping.generatedLine){var code="";addMappingWithCode(lastMapping,shiftNextLine());lastGeneratedLine++;lastGeneratedColumn=0}else{var nextLine=remainingLines[0];var code=nextLine.substr(0,mapping.generatedColumn-lastGeneratedColumn);remainingLines[0]=nextLine.substr(mapping.generatedColumn-lastGeneratedColumn);lastGeneratedColumn=mapping.generatedColumn;addMappingWithCode(lastMapping,code);lastMapping=mapping;return}}while(lastGeneratedLine<mapping.generatedLine){node.add(shiftNextLine());lastGeneratedLine++}if(lastGeneratedColumn<mapping.generatedColumn){var nextLine=remainingLines[0];node.add(nextLine.substr(0,mapping.generatedColumn));remainingLines[0]=nextLine.substr(mapping.generatedColumn);lastGeneratedColumn=mapping.generatedColumn}lastMapping=mapping},this);if(remainingLines.length>0){if(lastMapping){addMappingWithCode(lastMapping,shiftNextLine())}node.add(remainingLines.join(""))}aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){if(aRelativePath!=null){sourceFile=util.join(aRelativePath,sourceFile)}node.setSourceContent(sourceFile,content)}});return node;function addMappingWithCode(mapping,code){if(mapping===null||mapping.source===undefined){node.add(code)}else{var source=aRelativePath?util.join(aRelativePath,mapping.source):mapping.source;node.add(new SourceNode(mapping.originalLine,mapping.originalColumn,source,code,mapping.name))}}};SourceNode.prototype.add=function SourceNode_add(aChunk){if(Array.isArray(aChunk)){aChunk.forEach(function(chunk){this.add(chunk)},this)}else if(aChunk[isSourceNode]||typeof aChunk==="string"){if(aChunk){this.children.push(aChunk)}}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+aChunk)}return this};SourceNode.prototype.prepend=function SourceNode_prepend(aChunk){if(Array.isArray(aChunk)){for(var i=aChunk.length-1;i>=0;i--){this.prepend(aChunk[i])}}else if(aChunk[isSourceNode]||typeof aChunk==="string"){this.children.unshift(aChunk)}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+aChunk)}return this};SourceNode.prototype.walk=function SourceNode_walk(aFn){var chunk;for(var i=0,len=this.children.length;i<len;i++){chunk=this.children[i];if(chunk[isSourceNode]){chunk.walk(aFn)}else{if(chunk!==""){aFn(chunk,{source:this.source,line:this.line,column:this.column,name:this.name})}}}};SourceNode.prototype.join=function SourceNode_join(aSep){var newChildren;var i;var len=this.children.length;if(len>0){newChildren=[];for(i=0;i<len-1;i++){newChildren.push(this.children[i]);newChildren.push(aSep)}newChildren.push(this.children[i]);this.children=newChildren}return this};SourceNode.prototype.replaceRight=function SourceNode_replaceRight(aPattern,aReplacement){var lastChild=this.children[this.children.length-1];if(lastChild[isSourceNode]){lastChild.replaceRight(aPattern,aReplacement)}else if(typeof lastChild==="string"){this.children[this.children.length-1]=lastChild.replace(aPattern,aReplacement)}else{this.children.push("".replace(aPattern,aReplacement))}return this};SourceNode.prototype.setSourceContent=function SourceNode_setSourceContent(aSourceFile,aSourceContent){this.sourceContents[util.toSetString(aSourceFile)]=aSourceContent};SourceNode.prototype.walkSourceContents=function SourceNode_walkSourceContents(aFn){for(var i=0,len=this.children.length;i<len;i++){if(this.children[i][isSourceNode]){this.children[i].walkSourceContents(aFn)}}var sources=Object.keys(this.sourceContents);for(var i=0,len=sources.length;i<len;i++){aFn(util.fromSetString(sources[i]),this.sourceContents[sources[i]])}};SourceNode.prototype.toString=function SourceNode_toString(){var str="";this.walk(function(chunk){str+=chunk});return str};SourceNode.prototype.toStringWithSourceMap=function SourceNode_toStringWithSourceMap(aArgs){var generated={code:"",line:1,column:0};var map=new SourceMapGenerator(aArgs);var sourceMappingActive=false;var lastOriginalSource=null;var lastOriginalLine=null;var lastOriginalColumn=null;var lastOriginalName=null;this.walk(function(chunk,original){generated.code+=chunk;if(original.source!==null&&original.line!==null&&original.column!==null){if(lastOriginalSource!==original.source||lastOriginalLine!==original.line||lastOriginalColumn!==original.column||lastOriginalName!==original.name){map.addMapping({source:original.source,original:{line:original.line,column:original.column},generated:{line:generated.line,column:generated.column},name:original.name})}lastOriginalSource=original.source;lastOriginalLine=original.line;lastOriginalColumn=original.column;lastOriginalName=original.name;sourceMappingActive=true}else if(sourceMappingActive){map.addMapping({generated:{line:generated.line,column:generated.column}});lastOriginalSource=null;sourceMappingActive=false}for(var idx=0,length=chunk.length;idx<length;idx++){if(chunk.charCodeAt(idx)===NEWLINE_CODE){generated.line++;generated.column=0;if(idx+1===length){lastOriginalSource=null;sourceMappingActive=false}else if(sourceMappingActive){map.addMapping({source:original.source,original:{line:original.line,column:original.column},generated:{line:generated.line,column:generated.column},name:original.name})}}else{generated.column++}}});this.walkSourceContents(function(sourceFile,sourceContent){map.setSourceContent(sourceFile,sourceContent)});return{code:generated.code,map:map}};exports.SourceNode=SourceNode})},{"./source-map-generator":188,"./util":190,amdefine:191}],190:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){function getArg(aArgs,aName,aDefaultValue){if(aName in aArgs){return aArgs[aName]}else if(arguments.length===3){return aDefaultValue}else{throw new Error('"'+aName+'" is a required argument.')}}exports.getArg=getArg;var urlRegexp=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;var dataUrlRegexp=/^data:.+\,.+$/;function urlParse(aUrl){var match=aUrl.match(urlRegexp);if(!match){return null}return{scheme:match[1],auth:match[2],host:match[3],port:match[4],path:match[5]}}exports.urlParse=urlParse;function urlGenerate(aParsedUrl){var url="";if(aParsedUrl.scheme){url+=aParsedUrl.scheme+":"}url+="//";if(aParsedUrl.auth){url+=aParsedUrl.auth+"@"}if(aParsedUrl.host){url+=aParsedUrl.host}if(aParsedUrl.port){url+=":"+aParsedUrl.port}if(aParsedUrl.path){url+=aParsedUrl.path}return url}exports.urlGenerate=urlGenerate;function normalize(aPath){var path=aPath;var url=urlParse(aPath);if(url){if(!url.path){return aPath}path=url.path}var isAbsolute=path.charAt(0)==="/";var parts=path.split(/\/+/);for(var part,up=0,i=parts.length-1;i>=0;i--){part=parts[i];if(part==="."){parts.splice(i,1)}else if(part===".."){up++}else if(up>0){if(part===""){parts.splice(i+1,up);up=0}else{parts.splice(i,2);up--}}}path=parts.join("/");if(path===""){path=isAbsolute?"/":"."}if(url){url.path=path;return urlGenerate(url)}return path}exports.normalize=normalize;function join(aRoot,aPath){if(aRoot===""){aRoot="."}if(aPath===""){aPath="."}var aPathUrl=urlParse(aPath);var aRootUrl=urlParse(aRoot);if(aRootUrl){aRoot=aRootUrl.path||"/"}if(aPathUrl&&!aPathUrl.scheme){if(aRootUrl){aPathUrl.scheme=aRootUrl.scheme}return urlGenerate(aPathUrl)}if(aPathUrl||aPath.match(dataUrlRegexp)){return aPath}if(aRootUrl&&!aRootUrl.host&&!aRootUrl.path){aRootUrl.host=aPath;return urlGenerate(aRootUrl)}var joined=aPath.charAt(0)==="/"?aPath:normalize(aRoot.replace(/\/+$/,"")+"/"+aPath);if(aRootUrl){aRootUrl.path=joined;return urlGenerate(aRootUrl)}return joined}exports.join=join;function relative(aRoot,aPath){if(aRoot===""){aRoot="."}aRoot=aRoot.replace(/\/$/,"");var url=urlParse(aRoot);if(aPath.charAt(0)=="/"&&url&&url.path=="/"){return aPath.slice(1)}return aPath.indexOf(aRoot+"/")===0?aPath.substr(aRoot.length+1):aPath}exports.relative=relative;function toSetString(aStr){return"$"+aStr}exports.toSetString=toSetString;function fromSetString(aStr){return aStr.substr(1)}exports.fromSetString=fromSetString;function strcmp(aStr1,aStr2){var s1=aStr1||"";var s2=aStr2||"";return(s1>s2)-(s1<s2)}function compareByOriginalPositions(mappingA,mappingB,onlyCompareOriginal){var cmp;cmp=strcmp(mappingA.source,mappingB.source);if(cmp){return cmp}cmp=mappingA.originalLine-mappingB.originalLine;if(cmp){return cmp}cmp=mappingA.originalColumn-mappingB.originalColumn;if(cmp||onlyCompareOriginal){return cmp}cmp=strcmp(mappingA.name,mappingB.name);if(cmp){return cmp}cmp=mappingA.generatedLine-mappingB.generatedLine;if(cmp){return cmp}return mappingA.generatedColumn-mappingB.generatedColumn}exports.compareByOriginalPositions=compareByOriginalPositions;function compareByGeneratedPositions(mappingA,mappingB,onlyCompareGenerated){var cmp;cmp=mappingA.generatedLine-mappingB.generatedLine;if(cmp){return cmp}cmp=mappingA.generatedColumn-mappingB.generatedColumn;if(cmp||onlyCompareGenerated){return cmp}cmp=strcmp(mappingA.source,mappingB.source);if(cmp){return cmp}cmp=mappingA.originalLine-mappingB.originalLine;if(cmp){return cmp}cmp=mappingA.originalColumn-mappingB.originalColumn;if(cmp){return cmp}return strcmp(mappingA.name,mappingB.name)}exports.compareByGeneratedPositions=compareByGeneratedPositions})},{amdefine:191}],191:[function(require,module,exports){(function(process,__filename){"use strict";function amdefine(module,requireFn){"use strict";var defineCache={},loaderCache={},alreadyCalled=false,path=require("path"),makeRequire,stringRequire;function trimDots(ary){var i,part;for(i=0;ary[i];i+=1){part=ary[i];if(part==="."){ary.splice(i,1);i-=1}else if(part===".."){if(i===1&&(ary[2]===".."||ary[0]==="..")){break}else if(i>0){ary.splice(i-1,2);i-=2}}}}function normalize(name,baseName){var baseParts;if(name&&name.charAt(0)==="."){if(baseName){baseParts=baseName.split("/");baseParts=baseParts.slice(0,baseParts.length-1);baseParts=baseParts.concat(name.split("/"));trimDots(baseParts);name=baseParts.join("/")}}return name}function makeNormalize(relName){return function(name){return normalize(name,relName)}}function makeLoad(id){function load(value){loaderCache[id]=value}load.fromText=function(id,text){throw new Error("amdefine does not implement load.fromText")};return load}makeRequire=function(systemRequire,exports,module,relId){function amdRequire(deps,callback){if(typeof deps==="string"){return stringRequire(systemRequire,exports,module,deps,relId)}else{deps=deps.map(function(depName){return stringRequire(systemRequire,exports,module,depName,relId)});process.nextTick(function(){callback.apply(null,deps)})}}amdRequire.toUrl=function(filePath){if(filePath.indexOf(".")===0){return normalize(filePath,path.dirname(module.filename))}else{return filePath}};return amdRequire};requireFn=requireFn||function req(){return module.require.apply(module,arguments)};function runFactory(id,deps,factory){var r,e,m,result;if(id){e=loaderCache[id]={};m={id:id,uri:__filename,exports:e};r=makeRequire(requireFn,e,m,id)}else{if(alreadyCalled){throw new Error("amdefine with no module ID cannot be called more than once per file.")}alreadyCalled=true;e=module.exports;m=module;r=makeRequire(requireFn,e,m,module.id)}if(deps){deps=deps.map(function(depName){return r(depName)})}if(typeof factory==="function"){result=factory.apply(m.exports,deps)}else{result=factory}if(result!==undefined){m.exports=result;if(id){loaderCache[id]=m.exports}}}stringRequire=function(systemRequire,exports,module,id,relId){var index=id.indexOf("!"),originalId=id,prefix,plugin;if(index===-1){id=normalize(id,relId);if(id==="require"){return makeRequire(systemRequire,exports,module,relId)}else if(id==="exports"){return exports}else if(id==="module"){return module}else if(loaderCache.hasOwnProperty(id)){return loaderCache[id]}else if(defineCache[id]){runFactory.apply(null,defineCache[id]);return loaderCache[id]}else{if(systemRequire){return systemRequire(originalId)}else{throw new Error("No module with ID: "+id)}}}else{prefix=id.substring(0,index);id=id.substring(index+1,id.length);plugin=stringRequire(systemRequire,exports,module,prefix,relId);if(plugin.normalize){id=plugin.normalize(id,makeNormalize(relId))}else{id=normalize(id,relId)}if(loaderCache[id]){return loaderCache[id]}else{plugin.load(id,makeRequire(systemRequire,exports,module,relId),makeLoad(id),{});return loaderCache[id]}}};function define(id,deps,factory){if(Array.isArray(id)){factory=deps;deps=id;id=undefined}else if(typeof id!=="string"){factory=id;id=deps=undefined}if(deps&&!Array.isArray(deps)){factory=deps;deps=undefined}if(!deps){deps=["require","exports","module"]}if(id){defineCache[id]=[id,deps,factory]}else{runFactory(id,deps,factory)}}define.require=function(id){if(loaderCache[id]){return loaderCache[id]}if(defineCache[id]){runFactory.apply(null,defineCache[id]);return loaderCache[id]}};define.amd={};return define}module.exports=amdefine}).call(this,require("_process"),"/node_modules/source-map/node_modules/amdefine/amdefine.js")},{_process:130,path:129}],192:[function(require,module,exports){(function(process){"use strict";var argv=process.argv;module.exports=function(){if(argv.indexOf("--no-color")!==-1||argv.indexOf("--no-colors")!==-1||argv.indexOf("--color=false")!==-1){return false}if(argv.indexOf("--color")!==-1||argv.indexOf("--colors")!==-1||argv.indexOf("--color=true")!==-1||argv.indexOf("--color=always")!==-1){return true}if(process.stdout&&!process.stdout.isTTY){return false}if(process.platform==="win32"){return true}if("COLORTERM"in process.env){return true}if(process.env.TERM==="dumb"){return false}if(/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)){return true}return false}()}).call(this,require("_process"))},{_process:130}],193:[function(require,module,exports){module.exports={name:"6to5",description:"Turn ES6 code into readable vanilla ES5 with source maps",version:"3.0.1",author:"Sebastian McKenzie <[email protected]>",homepage:"https://6to5.org/",repository:"6to5/6to5",preferGlobal:true,main:"lib/6to5/index.js",bin:{"6to5":"./bin/6to5/index.js","6to5-node":"./bin/6to5-node"},browser:{"./lib/6to5/index.js":"./lib/6to5/browser.js","./lib/6to5/register.js":"./lib/6to5/register-browser.js"},keywords:["harmony","classes","modules","let","const","var","es6","transpile","transpiler","6to5"],scripts:{bench:"make bench",test:"make test"},dependencies:{"acorn-6to5":"0.11.1-25","ast-types":"~0.6.1",chalk:"^0.5.1",chokidar:"0.12.6",commander:"2.6.0","core-js":"0.4.6","detect-indent":"^3.0.0",estraverse:"1.9.1",esutils:"1.1.6",esvalid:"1.1.0","fs-readdir-recursive":"0.1.0","js-tokenizer":"^1.3.3",lodash:"3.0.0","output-file-sync":"^1.1.0","private":"0.1.6","regenerator-6to5":"0.8.9-6",regexpu:"1.1.0",roadrunner:"1.0.4","source-map":"0.1.43","source-map-support":"0.2.9","supports-color":"^1.2.0"},devDependencies:{browserify:"8.1.1",chai:"1.10.0",istanbul:"0.3.5",jscs:"^1.10.0",jshint:"2.6.0","jshint-stylish":"1.0.0",matcha:"0.6.0",mocha:"2.1.0",rimraf:"2.2.8","uglify-js":"2.4.16"},optionalDependencies:{kexec:"1.0.0"}}},{}],194:[function(require,module,exports){module.exports={"abstract-expression-call":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceGet",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"abstract-expression-delete":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceDelete",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"abstract-expression-get":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceGet",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"abstract-expression-set":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceSet",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"apply-constructor":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"args",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instance",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"create",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instance",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"args",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!=",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"object",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"||",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"function",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instance",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"array-comprehension-container":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ArrayExpression",start:null,end:null,loc:null,range:null,elements:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"array-from":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"from",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"array-push":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"push",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"STATEMENT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"async-to-generator":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"fn",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"gen",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"fn",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"NewExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Promise",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"resolve",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"reject",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callNext",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"bind",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"gen",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callThrow",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"bind",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"gen",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"throw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"FunctionDeclaration",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arg",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"TryStatement",start:null,end:null,loc:null,range:null,block:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"info",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arg",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"info",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},handler:{type:"CatchClause",start:null,end:null,loc:null,range:null,param:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"error",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},guard:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"reject",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"error",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},guardedHandlers:[],finalizer:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"info",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"resolve",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Promise",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"resolve",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"then",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callNext",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callThrow",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"callNext",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},bind:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Function",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"bind",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},call:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CONTEXT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"class-super-constructor-call-loose":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"SUPER_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!=",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"SUPER_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"class-super-constructor-call":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getPrototypeOf",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CLASS_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getPrototypeOf",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CLASS_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"corejs-iterator":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CORE_ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"$for",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getIterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"default-parameter":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VARIABLE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENT_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"DEFAULT_VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENT_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},defaults:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defaults",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ForInStatement",start:null,end:null,loc:null,range:null,left:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defaults",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defaults",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"define-property":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"enumerable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"configurable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"writable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"exports-assign":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"exports-default-assign":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"module",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"exports-module-declaration":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"__esModule",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"extends":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Literal",start:null,end:null,loc:null,range:null,value:1,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"<",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:{type:"UpdateExpression",start:null,end:null,loc:null,range:null,operator:"++",prefix:false,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"source",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ForInStatement",start:null,end:null,loc:null,range:null,left:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"source",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"hasOwnProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"source",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"source",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"for-of-loose":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"IS_ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isArray",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Literal",start:null,end:null,loc:null,range:null,value:0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"IS_ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:null,update:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"IS_ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:">=",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BreakStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"UpdateExpression",start:null,end:null,loc:null,range:null,operator:"++",prefix:false,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BreakStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"for-of":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ITERATOR_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"STEP_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"!",prefix:true,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"STEP_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ITERATOR_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},get:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"get",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getOwnPropertyDescriptor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getPrototypeOf",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"get",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Literal",start:null,end:null,loc:null,range:null,value:"value",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},operator:"in",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"writable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"get",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"has-own":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"hasOwnProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},inherits:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"function",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ThrowStatement",start:null,end:null,loc:null,range:null,argument:{type:"NewExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"TypeError",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Literal",start:null,end:null,loc:null,range:null,value:"Super expression must either be null or a function, not ",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},operator:"+",right:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"create",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"enumerable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:false,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"writable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"configurable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"__proto__",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"interop-require-wildcard":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"__esModule",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"default",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"interop-require":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"__esModule",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"default",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"let-scoping-return":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"RETURN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"object",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"RETURN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"v",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"object-without-properties":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"keys",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ForInStatement",start:null,end:null,loc:null,range:null,left:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"keys",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"indexOf",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:">=",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ContinueStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"!",prefix:true,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"hasOwnProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ContinueStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"property-method-assignment-wrapper":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},generator:false,expression:false,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"toString",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"toString",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"prototype-identifier":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CLASS_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"prototype-properties":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"child",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"staticProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instanceProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"staticProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperties",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"child",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"staticProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instanceProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperties",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"child",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instanceProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"require-assign-key":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VARIABLE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"require",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},require:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"require",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},rest:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LEN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY_LEN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"START",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"<",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LEN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:{type:"UpdateExpression",start:null,end:null,loc:null,range:null,operator:"++",prefix:false,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"self-global":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"global",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"undefined",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"self",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"global",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},slice:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"slice",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"sliced-to-array":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isArray",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ArrayExpression",start:null,end:null,loc:null,range:null,elements:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"!",prefix:true,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"push",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BreakStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},system:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"System",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"register",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_DEPENDENCIES",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"EXPORT_IDENTIFIER",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"setters",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"SETTERS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"execute",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"EXECUTE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"tagged-template-literal-loose":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"tagged-template-literal":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"freeze",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperties",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"freeze",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"test-exports":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"undefined",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"test-module":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"module",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"undefined",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"to-array":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isArray",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"from",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"typeof":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Literal",start:null,end:null,loc:null,range:null,value:"symbol",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},alternate:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"umd-runner-body":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,generator:false,expression:false,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"factory",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"define",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"function",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"define",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"amd",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"define",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"AMD_ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"factory",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"COMMON_TEST",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"factory",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"COMMON_ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}}
},{}]},{},[1])(1)}); | cur.consequent.push(parseStatement(true))}}if(cur)finishNode(cur,"SwitchCase");next();labels.pop();return finishNode(node,"SwitchStatement")}function parseThrowStatement(node){next();if(newline.test(input.slice(lastEnd,tokStart)))raise(lastEnd,"Illegal newline after throw");node.argument=parseExpression();semicolon();return finishNode(node,"ThrowStatement")}function parseTryStatement(node){next();node.block=parseBlock();node.handler=null;if(tokType===_catch){var clause=startNode();next();expect(_parenL);clause.param=parseAssignableAtom();checkLVal(clause.param,true);expect(_parenR);clause.guard=null;clause.body=parseBlock();node.handler=finishNode(clause,"CatchClause")}node.guardedHandlers=empty;node.finalizer=eat(_finally)?parseBlock():null;if(!node.handler&&!node.finalizer)raise(node.start,"Missing catch or finally clause");return finishNode(node,"TryStatement")}function parseVarStatement(node,kind){next();parseVar(node,false,kind);semicolon();return finishNode(node,"VariableDeclaration")}function parseWhileStatement(node){next();node.test=parseParenExpression();labels.push(loopLabel);node.body=parseStatement(false);labels.pop();return finishNode(node,"WhileStatement")}function parseWithStatement(node){if(strict)raise(tokStart,"'with' in strict mode");next();node.object=parseParenExpression();node.body=parseStatement(false);return finishNode(node,"WithStatement")}function parseEmptyStatement(node){next();return finishNode(node,"EmptyStatement")}function parseLabeledStatement(node,maybeName,expr){for(var i=0;i<labels.length;++i)if(labels[i].name===maybeName)raise(expr.start,"Label '"+maybeName+"' is already declared");var kind=tokType.isLoop?"loop":tokType===_switch?"switch":null;labels.push({name:maybeName,kind:kind});node.body=parseStatement(true);labels.pop();node.label=expr;return finishNode(node,"LabeledStatement")}function parseExpressionStatement(node,expr){node.expression=expr;semicolon();return finishNode(node,"ExpressionStatement")}function parseParenExpression(){expect(_parenL);var val=parseExpression();expect(_parenR);return val}function parseBlock(allowStrict){var node=startNode(),first=true,oldStrict;node.body=[];expect(_braceL);while(!eat(_braceR)){var stmt=parseStatement(true);node.body.push(stmt);if(first&&allowStrict&&isUseStrict(stmt)){oldStrict=strict;setStrict(strict=true)}first=false}if(oldStrict===false)setStrict(false);return finishNode(node,"BlockStatement")}function parseFor(node,init){node.init=init;expect(_semi);node.test=tokType===_semi?null:parseExpression();expect(_semi);node.update=tokType===_parenR?null:parseExpression();expect(_parenR);node.body=parseStatement(false);labels.pop();return finishNode(node,"ForStatement")}function parseForIn(node,init){var type=tokType===_in?"ForInStatement":"ForOfStatement";next();node.left=init;node.right=parseExpression();expect(_parenR);node.body=parseStatement(false);labels.pop();return finishNode(node,type)}function parseVar(node,noIn,kind){node.declarations=[];node.kind=kind;for(;;){var decl=startNode();decl.id=parseAssignableAtom();checkLVal(decl.id,true);if(tokType===_colon){decl.id.typeAnnotation=parseTypeAnnotation();finishNode(decl.id,decl.id.type)}decl.init=eat(_eq)?parseMaybeAssign(noIn):kind===_const.keyword?unexpected():null;node.declarations.push(finishNode(decl,"VariableDeclarator"));if(!eat(_comma))break}return node}function parseExpression(noIn,refShorthandDefaultPos){var start=storeCurrentPos();var expr=parseMaybeAssign(noIn,refShorthandDefaultPos);if(tokType===_comma){var node=startNodeAt(start);node.expressions=[expr];while(eat(_comma))node.expressions.push(parseMaybeAssign(noIn,refShorthandDefaultPos));return finishNode(node,"SequenceExpression")}return expr}function parseMaybeAssign(noIn,refShorthandDefaultPos,afterLeftParse){var failOnShorthandAssign;if(!refShorthandDefaultPos){refShorthandDefaultPos={start:0};failOnShorthandAssign=true}else{failOnShorthandAssign=false}var start=storeCurrentPos();var left=parseMaybeConditional(noIn,refShorthandDefaultPos);if(afterLeftParse)afterLeftParse(left);if(tokType.isAssign){var node=startNodeAt(start);node.operator=tokVal;node.left=tokType===_eq?toAssignable(left):left;refShorthandDefaultPos.start=0;checkLVal(left);next();node.right=parseMaybeAssign(noIn);return finishNode(node,"AssignmentExpression")}else if(failOnShorthandAssign&&refShorthandDefaultPos.start){unexpected(refShorthandDefaultPos.start)}return left}function parseMaybeConditional(noIn,refShorthandDefaultPos){var start=storeCurrentPos();var expr=parseExprOps(noIn,refShorthandDefaultPos);if(refShorthandDefaultPos&&refShorthandDefaultPos.start)return expr;if(eat(_question)){var node=startNodeAt(start);if(options.playground&&eat(_eq)){var left=node.left=toAssignable(expr);if(left.type!=="MemberExpression")raise(left.start,"You can only use member expressions in memoization assignment");node.right=parseMaybeAssign(noIn);node.operator="?=";return finishNode(node,"AssignmentExpression")}node.test=expr;node.consequent=parseMaybeAssign();expect(_colon);node.alternate=parseMaybeAssign(noIn);return finishNode(node,"ConditionalExpression")}return expr}function parseExprOps(noIn,refShorthandDefaultPos){var start=storeCurrentPos();var expr=parseMaybeUnary(refShorthandDefaultPos);if(refShorthandDefaultPos&&refShorthandDefaultPos.start)return expr;return parseExprOp(expr,start,-1,noIn)}function parseExprOp(left,leftStart,minPrec,noIn){var prec=tokType.binop;if(prec!=null&&(!noIn||tokType!==_in)){if(prec>minPrec){var node=startNodeAt(leftStart);node.left=left;node.operator=tokVal;var op=tokType;next();var start=storeCurrentPos();node.right=parseExprOp(parseMaybeUnary(),start,op.rightAssociative?prec-1:prec,noIn);finishNode(node,op===_logicalOR||op===_logicalAND?"LogicalExpression":"BinaryExpression");return parseExprOp(node,leftStart,minPrec,noIn)}}return left}function parseMaybeUnary(refShorthandDefaultPos){if(tokType.prefix){var node=startNode(),update=tokType.isUpdate;node.operator=tokVal;node.prefix=true;next();node.argument=parseMaybeUnary();if(refShorthandDefaultPos&&refShorthandDefaultPos.start)unexpected(refShorthandDefaultPos.start);if(update)checkLVal(node.argument);else if(strict&&node.operator==="delete"&&node.argument.type==="Identifier")raise(node.start,"Deleting local variable in strict mode");return finishNode(node,update?"UpdateExpression":"UnaryExpression")}var start=storeCurrentPos();var expr=parseExprSubscripts(refShorthandDefaultPos);if(refShorthandDefaultPos&&refShorthandDefaultPos.start)return expr;while(tokType.postfix&&!canInsertSemicolon()){var node=startNodeAt(start);node.operator=tokVal;node.prefix=false;node.argument=expr;checkLVal(expr);next();expr=finishNode(node,"UpdateExpression")}return expr}function parseExprSubscripts(refShorthandDefaultPos){var start=storeCurrentPos();var expr=parseExprAtom(refShorthandDefaultPos);if(refShorthandDefaultPos&&refShorthandDefaultPos.start)return expr;return parseSubscripts(expr,start)}function parseSubscripts(base,start,noCalls){if(options.playground&&eat(_hash)){var node=startNodeAt(start);node.object=base;node.property=parseIdent(true);if(eat(_parenL)){node.arguments=parseExprList(_parenR,false)}else{node.arguments=[]}return parseSubscripts(finishNode(node,"BindMemberExpression"),start,noCalls)}else if(eat(_paamayimNekudotayim)){var node=startNodeAt(start);node.object=base;node.property=parseIdent(true);return parseSubscripts(finishNode(node,"VirtualPropertyExpression"),start,noCalls)}else if(eat(_dot)){var node=startNodeAt(start);node.object=base;node.property=parseIdent(true);node.computed=false;return parseSubscripts(finishNode(node,"MemberExpression"),start,noCalls)}else if(eat(_bracketL)){var node=startNodeAt(start);node.object=base;node.property=parseExpression();node.computed=true;expect(_bracketR);return parseSubscripts(finishNode(node,"MemberExpression"),start,noCalls)}else if(!noCalls&&eat(_parenL)){var node=startNodeAt(start);node.callee=base;node.arguments=parseExprList(_parenR,false);return parseSubscripts(finishNode(node,"CallExpression"),start,noCalls)}else if(tokType===_backQuote){var node=startNodeAt(start);node.tag=base;node.quasi=parseTemplate();return parseSubscripts(finishNode(node,"TaggedTemplateExpression"),start,noCalls)}return base}function parseExprAtom(refShorthandDefaultPos){switch(tokType){case _this:var node=startNode();next();return finishNode(node,"ThisExpression");case _at:var start=storeCurrentPos();var node=startNode();var thisNode=startNode();next();node.object=finishNode(thisNode,"ThisExpression");node.property=parseSubscripts(parseIdent(),start);node.computed=false;return finishNode(node,"MemberExpression");case _yield:if(inGenerator)return parseYield();case _name:var start=storeCurrentPos();var node=startNode();var id=parseIdent(tokType!==_name);if(options.ecmaVersion>=7){if(id.name==="async"){if(tokType===_parenL){next();var exprList;if(tokType!==_parenR){var val=parseExpression();exprList=val.type==="SequenceExpression"?val.expressions:[val]}else{exprList=[]}expect(_parenR);if(eat(_arrow)){return parseArrowExpression(node,exprList,true)}else{node.callee=id;node.arguments=exprList;return parseSubscripts(finishNode(node,"CallExpression"),start)}}else if(tokType===_name){id=parseIdent();if(eat(_arrow)){return parseArrowExpression(node,[id],true)}return id}if(tokType===_function&&!canInsertSemicolon()){next();return parseFunction(node,false,true)}}else if(id.name==="await"){if(inAsync)return parseAwait(node)}}if(eat(_arrow)){return parseArrowExpression(node,[id])}return id;case _regexp:var node=startNode();node.regex={pattern:tokVal.pattern,flags:tokVal.flags};node.value=tokVal.value;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"Literal");case _num:case _string:case _jsxText:var node=startNode();node.value=tokVal;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"Literal");case _null:case _true:case _false:var node=startNode();node.value=tokType.atomValue;node.raw=tokType.keyword;next();return finishNode(node,"Literal");case _parenL:return parseParenAndDistinguishExpression();case _bracketL:var node=startNode();next();if(options.ecmaVersion>=7&&tokType===_for){return parseComprehension(node,false)}node.elements=parseExprList(_bracketR,true,true,refShorthandDefaultPos);return finishNode(node,"ArrayExpression");case _braceL:return parseObj(false,refShorthandDefaultPos);case _function:var node=startNode();next();return parseFunction(node,false,false);case _class:return parseClass(startNode(),false);case _new:return parseNew();case _backQuote:return parseTemplate();case _hash:return parseBindFunctionExpression();case _jsxTagStart:return parseJSXElement();default:unexpected()}}function parseBindFunctionExpression(){var node=startNode();next();var start=storeCurrentPos();node.callee=parseSubscripts(parseExprAtom(),start,true);if(eat(_parenL)){node.arguments=parseExprList(_parenR,false)}else{node.arguments=[]}return finishNode(node,"BindFunctionExpression")}function parseParenAndDistinguishExpression(){var start=storeCurrentPos(),val;if(options.ecmaVersion>=6){next();if(options.ecmaVersion>=7&&tokType===_for){return parseComprehension(startNodeAt(start),true)}var innerStart=storeCurrentPos(),exprList=[],first=true;var refShorthandDefaultPos={start:0},spreadStart,innerParenStart,typeStart;var parseParenItem=function(node){if(tokType===_colon){typeStart=typeStart||tokStart;node.returnType=parseTypeAnnotation()}return node};while(tokType!==_parenR){first?first=false:expect(_comma);if(tokType===_ellipsis){spreadStart=tokStart;exprList.push(parseParenItem(parseRest()));break}else{if(tokType===_parenL&&!innerParenStart){innerParenStart=tokStart}exprList.push(parseMaybeAssign(false,refShorthandDefaultPos,parseParenItem))}}var innerEnd=storeCurrentPos();expect(_parenR);if(eat(_arrow)){if(innerParenStart)unexpected(innerParenStart);return parseArrowExpression(startNodeAt(start),exprList)}if(!exprList.length)unexpected(lastStart);if(typeStart)unexpected(typeStart);if(spreadStart)unexpected(spreadStart);if(refShorthandDefaultPos.start)unexpected(refShorthandDefaultPos.start);if(exprList.length>1){val=startNodeAt(innerStart);val.expressions=exprList;finishNodeAt(val,"SequenceExpression",innerEnd)}else{val=exprList[0]}}else{val=parseParenExpression()}if(options.preserveParens){var par=startNodeAt(start);par.expression=val;return finishNode(par,"ParenthesizedExpression")}else{return val}}function parseNew(){var node=startNode();next();var start=storeCurrentPos();node.callee=parseSubscripts(parseExprAtom(),start,true);if(eat(_parenL))node.arguments=parseExprList(_parenR,false);else node.arguments=empty;return finishNode(node,"NewExpression")}function parseTemplateElement(){var elem=startNode();elem.value={raw:input.slice(tokStart,tokEnd),cooked:tokVal};next();elem.tail=tokType===_backQuote;return finishNode(elem,"TemplateElement")}function parseTemplate(){var node=startNode();next();node.expressions=[];var curElt=parseTemplateElement();node.quasis=[curElt];while(!curElt.tail){expect(_dollarBraceL);node.expressions.push(parseExpression());expect(_braceR);node.quasis.push(curElt=parseTemplateElement())}next();return finishNode(node,"TemplateLiteral")}function parseObj(isPattern,refShorthandDefaultPos){var node=startNode(),first=true,propHash={};node.properties=[];next();while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var prop=startNode(),start,isGenerator=false,isAsync=false;if(options.ecmaVersion>=7&&tokType===_ellipsis){prop=parseSpread();prop.type="SpreadProperty";node.properties.push(prop);continue}if(options.ecmaVersion>=6){prop.method=false;prop.shorthand=false;if(isPattern){start=storeCurrentPos()}else{isGenerator=eat(_star)}}if(options.ecmaVersion>=7&&isContextual("async")){var asyncId=parseIdent();if(tokType===_colon||tokType===_parenL){prop.key=asyncId}else{isAsync=true;parsePropertyName(prop)}}else{parsePropertyName(prop)}var typeParameters;if(isRelational("<")){typeParameters=parseTypeParameterDeclaration();if(tokType!==_parenL)unexpected()}if(eat(_colon)){prop.value=isPattern?parseMaybeDefault(start):parseMaybeAssign(false,refShorthandDefaultPos);prop.kind="init"}else if(options.ecmaVersion>=6&&tokType===_parenL){if(isPattern)unexpected();prop.kind="init";prop.method=true;prop.value=parseMethod(isGenerator,isAsync)}else if(options.ecmaVersion>=5&&!prop.computed&&prop.key.type==="Identifier"&&(prop.key.name==="get"||prop.key.name==="set"||options.playground&&prop.key.name==="memo")&&(tokType!=_comma&&tokType!=_braceR)){if(isGenerator||isAsync||isPattern)unexpected();prop.kind=prop.key.name;parsePropertyName(prop);prop.value=parseMethod(false,false)}else if(options.ecmaVersion>=6&&!prop.computed&&prop.key.type==="Identifier"){prop.kind="init";if(isPattern){prop.value=parseMaybeDefault(start,prop.key)}else if(tokType===_eq&&refShorthandDefaultPos){if(!refShorthandDefaultPos.start)refShorthandDefaultPos.start=tokStart;prop.value=parseMaybeDefault(start,prop.key)}else{prop.value=prop.key}prop.shorthand=true}else unexpected();prop.value.typeParameters=typeParameters;checkPropClash(prop,propHash);node.properties.push(finishNode(prop,"Property"))}return finishNode(node,isPattern?"ObjectPattern":"ObjectExpression")}function parsePropertyName(prop){if(options.ecmaVersion>=6){if(eat(_bracketL)){prop.computed=true;prop.key=parseExpression();expect(_bracketR);return}else{prop.computed=false}}prop.key=tokType===_num||tokType===_string?parseExprAtom():parseIdent(true)}function initFunction(node,isAsync){node.id=null;if(options.ecmaVersion>=6){node.generator=false;node.expression=false}if(options.ecmaVersion>=7){node.async=isAsync}}function parseFunction(node,isStatement,isAsync,allowExpressionBody){initFunction(node,isAsync);if(options.ecmaVersion>=6){node.generator=eat(_star)}if(isStatement||tokType===_name){node.id=parseIdent()}if(isRelational("<")){node.typeParameters=parseTypeParameterDeclaration()}parseFunctionParams(node);parseFunctionBody(node,allowExpressionBody);return finishNode(node,isStatement?"FunctionDeclaration":"FunctionExpression")}function parseMethod(isGenerator,isAsync){var node=startNode();initFunction(node,isAsync);parseFunctionParams(node);var allowExpressionBody;if(options.ecmaVersion>=6){node.generator=isGenerator;allowExpressionBody=true}else{allowExpressionBody=false}parseFunctionBody(node,allowExpressionBody);return finishNode(node,"FunctionExpression")}function parseFunctionParams(node){expect(_parenL);node.params=parseAssignableList(_parenR,false);if(tokType===_colon){node.returnType=parseTypeAnnotation()}}function parseArrowExpression(node,params,isAsync){initFunction(node,isAsync);node.params=toAssignableList(params,true);parseFunctionBody(node,true);return finishNode(node,"ArrowFunctionExpression")}function parseFunctionBody(node,allowExpression){var isExpression=allowExpression&&tokType!==_braceL;var oldInAsync=inAsync;inAsync=node.async;if(isExpression){node.body=parseMaybeAssign();node.expression=true}else{var oldInFunc=inFunction,oldInGen=inGenerator,oldLabels=labels;inFunction=true;inGenerator=node.generator;labels=[];node.body=parseBlock(true);node.expression=false;inFunction=oldInFunc;inGenerator=oldInGen;labels=oldLabels}inAsync=oldInAsync;if(strict||!isExpression&&node.body.body.length&&isUseStrict(node.body.body[0])){var nameHash={};if(node.id)checkFunctionParam(node.id,{});for(var i=0;i<node.params.length;i++)checkFunctionParam(node.params[i],nameHash)}}function parsePrivate(node){node.declarations=[];do{node.declarations.push(parseIdent())}while(eat(_comma));semicolon();return finishNode(node,"PrivateDeclaration")}function parseClass(node,isStatement){next();node.id=tokType===_name?parseIdent():isStatement?unexpected():null;if(isRelational("<")){node.typeParameters=parseTypeParameterDeclaration()}node.superClass=eat(_extends)?parseExprSubscripts():null;if(node.superClass&&isRelational("<")){node.superTypeParameters=parseTypeParameterInstantiation()}if(isContextual("implements")){next();node.implements=parseClassImplements()}var classBody=startNode();classBody.body=[];expect(_braceL);while(!eat(_braceR)){if(eat(_semi))continue;var method=startNode();if(options.ecmaVersion>=7&&isContextual("private")){next();classBody.body.push(parsePrivate(method));continue}var isGenerator=eat(_star);var isAsync=false;parsePropertyName(method);if(tokType!==_parenL&&!method.computed&&method.key.type==="Identifier"&&method.key.name==="static"){if(isGenerator||isAsync)unexpected();method["static"]=true;isGenerator=eat(_star);parsePropertyName(method)}else{method["static"]=false}if(tokType!==_parenL&&!method.computed&&method.key.type==="Identifier"&&method.key.name==="async"){isAsync=true;parsePropertyName(method)}if(tokType!==_parenL&&!method.computed&&method.key.type==="Identifier"&&(method.key.name==="get"||method.key.name==="set")||options.playground&&method.key.name==="memo"){if(isGenerator||isAsync)unexpected();method.kind=method.key.name;parsePropertyName(method)}else{method.kind=""}if(tokType===_colon){method.typeAnnotation=parseTypeAnnotation();semicolon();classBody.body.push(finishNode(method,"ClassProperty"))}else{var typeParameters;if(isRelational("<")){typeParameters=parseTypeParameterDeclaration()}method.value=parseMethod(isGenerator,isAsync);method.value.typeParameters=typeParameters;classBody.body.push(finishNode(method,"MethodDefinition"));eat(_semi)}}node.body=finishNode(classBody,"ClassBody");return finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")}function parseClassImplements(){var implemented=[];do{var node=startNode();node.id=parseIdent();if(isRelational("<")){node.typeParameters=parseTypeParameterInstantiation()}else{node.typeParameters=null}implemented.push(finishNode(node,"ClassImplements"))}while(eat(_comma));return implemented}function parseExprList(close,allowTrailingComma,allowEmpty,refShorthandDefaultPos){var elts=[],first=true;while(!eat(close)){if(!first){expect(_comma);if(allowTrailingComma&&options.allowTrailingCommas&&eat(close))break}else first=false;if(allowEmpty&&tokType===_comma){elts.push(null)}else{if(tokType===_ellipsis)elts.push(parseSpread(refShorthandDefaultPos));else elts.push(parseMaybeAssign(false,refShorthandDefaultPos))}}return elts}function parseIdent(liberal){var node=startNode();if(liberal&&options.forbidReserved=="everywhere")liberal=false;if(tokType===_name){if(!liberal&&(options.forbidReserved&&(options.ecmaVersion===3?isReservedWord3:isReservedWord5)(tokVal)||strict&&isStrictReservedWord(tokVal))&&input.slice(tokStart,tokEnd).indexOf("\\")==-1)raise(tokStart,"The keyword '"+tokVal+"' is reserved");node.name=tokVal}else if(liberal&&tokType.keyword){node.name=tokType.keyword}else{unexpected()}next();return finishNode(node,"Identifier")}function parseExport(node){next();if(tokType===_var||tokType===_const||tokType===_let||tokType===_function||tokType===_class||isContextual("async")){node.declaration=parseStatement(true);node["default"]=false;node.specifiers=null;node.source=null}else if(eat(_default)){var declar=node.declaration=parseMaybeAssign(true);if(declar.id){if(declar.type==="FunctionExpression"){declar.type="FunctionDeclaration"}else if(declar.type==="ClassExpression"){declar.type="ClassDeclaration"}}node["default"]=true;node.specifiers=null;node.source=null;semicolon()}else{var isBatch=tokType===_star;node.declaration=null;node["default"]=false;node.specifiers=parseExportSpecifiers();if(eatContextual("from")){node.source=tokType===_string?parseExprAtom():unexpected()}else{if(isBatch)unexpected();node.source=null}semicolon()}return finishNode(node,"ExportDeclaration")}function parseExportSpecifiers(){var nodes=[],first=true;if(tokType===_star){var node=startNode();next();nodes.push(finishNode(node,"ExportBatchSpecifier"))}else{expect(_braceL);while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var node=startNode();node.id=parseIdent(tokType===_default);node.name=eatContextual("as")?parseIdent(true):null;nodes.push(finishNode(node,"ExportSpecifier"))}}return nodes}function parseImport(node){next();if(tokType===_string){node.specifiers=[];node.source=parseExprAtom()}else{node.specifiers=parseImportSpecifiers();expectContextual("from");node.source=tokType===_string?parseExprAtom():unexpected()}semicolon();return finishNode(node,"ImportDeclaration")}function parseImportSpecifiers(){var nodes=[],first=true;if(tokType===_name){var node=startNode();node.id=parseIdent();checkLVal(node.id,true);node.name=null;node["default"]=true;nodes.push(finishNode(node,"ImportSpecifier"));if(!eat(_comma))return nodes}if(tokType===_star){var node=startNode();next();expectContextual("as");node.name=parseIdent();checkLVal(node.name,true);nodes.push(finishNode(node,"ImportBatchSpecifier"));return nodes}expect(_braceL);while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var node=startNode();node.id=parseIdent(true);node.name=eatContextual("as")?parseIdent():null;checkLVal(node.name||node.id,true);node["default"]=false;nodes.push(finishNode(node,"ImportSpecifier"))}return nodes}function parseYield(){var node=startNode();next();if(eat(_semi)||canInsertSemicolon()){node.delegate=false;node.argument=null}else{node.delegate=eat(_star);node.argument=parseMaybeAssign()}return finishNode(node,"YieldExpression")}function parseAwait(node){if(eat(_semi)||canInsertSemicolon()){unexpected()}node.delegate=eat(_star);node.argument=parseMaybeAssign(true);return finishNode(node,"AwaitExpression")}function parseComprehension(node,isGenerator){node.blocks=[];while(tokType===_for){var block=startNode();next();expect(_parenL);block.left=parseAssignableAtom();checkLVal(block.left,true);expectContextual("of");block.right=parseExpression();expect(_parenR);node.blocks.push(finishNode(block,"ComprehensionBlock"))}node.filter=eat(_if)?parseParenExpression():null;node.body=parseExpression();expect(isGenerator?_parenR:_bracketR);node.generator=isGenerator;return finishNode(node,"ComprehensionExpression")}function getQualifiedJSXName(object){if(object.type==="JSXIdentifier"){return object.name}if(object.type==="JSXNamespacedName"){return object.namespace.name+":"+object.name.name}if(object.type==="JSXMemberExpression"){return getQualifiedJSXName(object.object)+"."+getQualifiedJSXName(object.property)}}function parseJSXIdentifier(){var node=startNode();if(tokType===_jsxName){node.name=tokVal}else if(tokType.keyword){node.name=tokType.keyword}else{unexpected()}next();return finishNode(node,"JSXIdentifier")}function parseJSXNamespacedName(){var start=storeCurrentPos();var name=parseJSXIdentifier();if(!eat(_colon))return name;var node=startNodeAt(start);node.namespace=name;node.name=parseJSXIdentifier();return finishNode(node,"JSXNamespacedName")}function parseJSXElementName(){var start=storeCurrentPos();var node=parseJSXNamespacedName();while(eat(_dot)){var newNode=startNodeAt(start);newNode.object=node;newNode.property=parseJSXIdentifier();node=finishNode(newNode,"JSXMemberExpression")}return node}function parseJSXAttributeValue(){switch(tokType){case _braceL:var node=parseJSXExpressionContainer();if(node.expression.type==="JSXEmptyExpression"){raise(node.start,"JSX attributes must only be assigned a non-empty "+"expression")}return node;case _jsxTagStart:return parseJSXElement();case _jsxText:case _string:return parseExprAtom();default:raise(tokStart,"JSX value should be either an expression or a quoted JSX text")}}function parseJSXEmptyExpression(){if(tokType!==_braceR){unexpected()}var tmp;tmp=tokStart;tokStart=lastEnd;lastEnd=tmp;tmp=tokStartLoc;tokStartLoc=lastEndLoc;lastEndLoc=tmp;return finishNode(startNode(),"JSXEmptyExpression")}function parseJSXExpressionContainer(){var node=startNode();next();node.expression=tokType===_braceR?parseJSXEmptyExpression():parseExpression();expect(_braceR);return finishNode(node,"JSXExpressionContainer")}function parseJSXAttribute(){var node=startNode();if(eat(_braceL)){expect(_ellipsis);node.argument=parseMaybeAssign();expect(_braceR);return finishNode(node,"JSXSpreadAttribute")}node.name=parseJSXNamespacedName();node.value=eat(_eq)?parseJSXAttributeValue():null;return finishNode(node,"JSXAttribute")}function parseJSXOpeningElementAt(start){var node=startNodeAt(start);node.attributes=[];node.name=parseJSXElementName();while(tokType!==_slash&&tokType!==_jsxTagEnd){node.attributes.push(parseJSXAttribute())}node.selfClosing=eat(_slash);expect(_jsxTagEnd);return finishNode(node,"JSXOpeningElement")}function parseJSXClosingElementAt(start){var node=startNodeAt(start);node.name=parseJSXElementName();expect(_jsxTagEnd);return finishNode(node,"JSXClosingElement")}function parseJSXElementAt(start){var node=startNodeAt(start);var children=[];var openingElement=parseJSXOpeningElementAt(start);var closingElement=null;if(!openingElement.selfClosing){contents:for(;;){switch(tokType){case _jsxTagStart:start=storeCurrentPos();next();if(eat(_slash)){closingElement=parseJSXClosingElementAt(start);break contents}children.push(parseJSXElementAt(start));break;case _jsxText:children.push(parseExprAtom());break;case _braceL:children.push(parseJSXExpressionContainer());break;default:unexpected()}}if(getQualifiedJSXName(closingElement.name)!==getQualifiedJSXName(openingElement.name)){raise(closingElement.start,"Expected corresponding JSX closing tag for <"+getQualifiedJSXName(openingElement.name)+">")}}node.openingElement=openingElement;node.closingElement=closingElement;node.children=children;return finishNode(node,"JSXElement")}function isRelational(op){return tokType===_relational&&tokVal===op}function expectRelational(op){if(isRelational(op)){next()}else{unexpected()}}function parseJSXElement(){var start=storeCurrentPos();next();return parseJSXElementAt(start)}function parseDeclareClass(node){next();parseInterfaceish(node,true);return finishNode(node,"DeclareClass")}function parseDeclareFunction(node){next();var id=node.id=parseIdent();var typeNode=startNode();var typeContainer=startNode();if(isRelational("<")){typeNode.typeParameters=parseTypeParameterDeclaration()}else{typeNode.typeParameters=null}expect(_parenL);var tmp=parseFunctionTypeParams();typeNode.params=tmp.params;typeNode.rest=tmp.rest;expect(_parenR);expect(_colon);typeNode.returnType=parseType();typeContainer.typeAnnotation=finishNode(typeNode,"FunctionTypeAnnotation");id.typeAnnotation=finishNode(typeContainer,"TypeAnnotation");finishNode(id,id.type);semicolon();return finishNode(node,"DeclareFunction")}function parseDeclare(node){if(tokType===_class){return parseDeclareClass(node)}else if(tokType===_function){return parseDeclareFunction(node)}else if(tokType===_var){return parseDeclareVariable(node)}else if(isContextual("module")){return parseDeclareModule(node)}else{unexpected()}}function parseDeclareVariable(node){next();node.id=parseTypeAnnotatableIdentifier();semicolon();return finishNode(node,"DeclareVariable")}function parseDeclareModule(node){next();if(tokType===_string){node.id=parseExprAtom()}else{node.id=parseIdent()}var bodyNode=node.body=startNode();var body=bodyNode.body=[];expect(_braceL);while(tokType!==_braceR){var node2=startNode();next();body.push(parseDeclare(node2))}expect(_braceR);finishNode(bodyNode,"BlockStatement");return finishNode(node,"DeclareModule")}function parseInterfaceish(node,allowStatic){node.id=parseIdent();if(isRelational("<")){node.typeParameters=parseTypeParameterDeclaration()}else{node.typeParameters=null}node.extends=[];if(eat(_extends)){do{node.extends.push(parseInterfaceExtends())}while(eat(_comma))}node.body=parseObjectType(allowStatic)}function parseInterfaceExtends(){var node=startNode();node.id=parseIdent();if(isRelational("<")){node.typeParameters=parseTypeParameterInstantiation()}else{node.typeParameters=null}return finishNode(node,"InterfaceExtends")}function parseInterface(node){parseInterfaceish(node,false);return finishNode(node,"InterfaceDeclaration")}function parseTypeAlias(node){node.id=parseIdent();if(isRelational("<")){node.typeParameters=parseTypeParameterDeclaration()}else{node.typeParameters=null}expect(_eq);node.right=parseType();semicolon();return finishNode(node,"TypeAlias")}function parseTypeParameterDeclaration(){var node=startNode();node.params=[];expectRelational("<");while(!isRelational(">")){node.params.push(parseIdent());if(!isRelational(">")){expect(_comma)}}expectRelational(">");return finishNode(node,"TypeParameterDeclaration")}function parseTypeParameterInstantiation(){var node=startNode(),oldInType=inType;node.params=[];inType=true;expectRelational("<");while(!isRelational(">")){node.params.push(parseType());if(!isRelational(">")){expect(_comma)}}expectRelational(">");inType=oldInType;return finishNode(node,"TypeParameterInstantiation")}function parseObjectPropertyKey(){return tokType===_num||tokType===_string?parseExprAtom():parseIdent(true)}function parseObjectTypeIndexer(node,isStatic){node.static=isStatic;expect(_bracketL);node.id=parseObjectPropertyKey();expect(_colon);node.key=parseType();expect(_bracketR);expect(_colon);node.value=parseType();return finishNode(node,"ObjectTypeIndexer")}function parseObjectTypeMethodish(node){node.params=[];node.rest=null;node.typeParameters=null;if(isRelational("<")){node.typeParameters=parseTypeParameterDeclaration()}expect(_parenL);while(tokType===_name){node.params.push(parseFunctionTypeParam());if(tokType!==_parenR){expect(_comma)}}if(eat(_ellipsis)){node.rest=parseFunctionTypeParam()}expect(_parenR);expect(_colon);node.returnType=parseType();return finishNode(node,"FunctionTypeAnnotation")}function parseObjectTypeMethod(start,isStatic,key){var node=startNodeAt(start);node.value=parseObjectTypeMethodish(startNodeAt(start));node.static=isStatic;node.key=key;node.optional=false;return finishNode(node,"ObjectTypeProperty")}function parseObjectTypeCallProperty(node,isStatic){var valueNode=startNode();node.static=isStatic;node.value=parseObjectTypeMethodish(valueNode);
return finishNode(node,"ObjectTypeCallProperty")}function parseObjectType(allowStatic){var nodeStart=startNode();var node;var optional=false;var property;var propertyKey;var propertyTypeAnnotation;var token;var isStatic;nodeStart.callProperties=[];nodeStart.properties=[];nodeStart.indexers=[];expect(_braceL);while(tokType!==_braceR){var start=storeCurrentPos();node=startNode();if(allowStatic&&isContextual("static")){next();isStatic=true}if(tokType===_bracketL){nodeStart.indexers.push(parseObjectTypeIndexer(node,isStatic))}else if(tokType===_parenL||isRelational("<")){nodeStart.callProperties.push(parseObjectTypeCallProperty(node,allowStatic))}else{if(isStatic&&tokType===_colon){propertyKey=parseIdent()}else{propertyKey=parseObjectPropertyKey()}if(isRelational("<")||tokType===_parenL){nodeStart.properties.push(parseObjectTypeMethod(start,isStatic,propertyKey))}else{if(eat(_question)){optional=true}expect(_colon);node.key=propertyKey;node.value=parseType();node.optional=optional;node.static=isStatic;nodeStart.properties.push(finishNode(node,"ObjectTypeProperty"))}}if(!eat(_semi)&&tokType!==_braceR){unexpected()}}expect(_braceR);return finishNode(nodeStart,"ObjectTypeAnnotation")}function parseGenericType(start,id){var node=startNodeAt(start);node.typeParameters=null;node.id=id;while(eat(_dot)){var node2=startNodeAt(start);node2.qualification=node.id;node2.id=parseIdent();node.id=finishNode(node2,"QualifiedTypeIdentifier")}if(isRelational("<")){node.typeParameters=parseTypeParameterInstantiation()}return finishNode(node,"GenericTypeAnnotation")}function parseVoidType(){var node=startNode();expect(keywordTypes["void"]);return finishNode(node,"VoidTypeAnnotation")}function parseTypeofType(){var node=startNode();expect(keywordTypes["typeof"]);node.argument=parsePrimaryType();return finishNode(node,"TypeofTypeAnnotation")}function parseTupleType(){var node=startNode();node.types=[];expect(_bracketL);while(tokPos<inputLen&&tokType!==_bracketR){node.types.push(parseType());if(tokType===_bracketR)break;expect(_comma)}expect(_bracketR);return finishNode(node,"TupleTypeAnnotation")}function parseFunctionTypeParam(){var optional=false;var node=startNode();node.name=parseIdent();if(eat(_question)){optional=true}expect(_colon);node.optional=optional;node.typeAnnotation=parseType();return finishNode(node,"FunctionTypeParam")}function parseFunctionTypeParams(){var ret={params:[],rest:null};while(tokType===_name){ret.params.push(parseFunctionTypeParam());if(tokType!==_parenR){expect(_comma)}}if(eat(_ellipsis)){ret.rest=parseFunctionTypeParam()}return ret}function identToTypeAnnotation(start,node,id){switch(id.name){case"any":return finishNode(node,"AnyTypeAnnotation");case"bool":case"boolean":return finishNode(node,"BooleanTypeAnnotation");case"number":return finishNode(node,"NumberTypeAnnotation");case"string":return finishNode(node,"StringTypeAnnotation");default:return parseGenericType(start,id)}}function parsePrimaryType(){var typeIdentifier=null;var params=null;var returnType=null;var start=storeCurrentPos();var node=startNode();var rest=null;var tmp;var typeParameters;var token;var type;var isGroupedType=false;switch(tokType){case _name:return identToTypeAnnotation(start,node,parseIdent());case _braceL:return parseObjectType();case _bracketL:return parseTupleType();case _relational:if(tokVal==="<"){node.typeParameters=parseTypeParameterDeclaration();expect(_parenL);tmp=parseFunctionTypeParams();node.params=tmp.params;node.rest=tmp.rest;expect(_parenR);expect(_arrow);node.returnType=parseType();return finishNode(node,"FunctionTypeAnnotation")}case _parenL:next();var tmpId;if(tokType!==_parenR&&tokType!==_ellipsis){if(tokType===_name){}else{isGroupedType=true}}if(isGroupedType){if(tmpId&&_parenR){type=tmpId}else{type=parseType();expect(_parenR)}if(eat(_arrow)){raise(node,"Unexpected token =>. It looks like "+"you are trying to write a function type, but you ended up "+"writing a grouped type followed by an =>, which is a syntax "+"error. Remember, function type parameters are named so function "+"types look like (name1: type1, name2: type2) => returnType. You "+"probably wrote (type1) => returnType")}return type}tmp=parseFunctionTypeParams();node.params=tmp.params;node.rest=tmp.rest;expect(_parenR);expect(_arrow);node.returnType=parseType();node.typeParameters=null;return finishNode(node,"FunctionTypeAnnotation");case _string:node.value=tokVal;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"StringLiteralTypeAnnotation");default:if(tokType.keyword){switch(tokType.keyword){case"void":return parseVoidType();case"typeof":return parseTypeofType()}}}unexpected()}function parsePostfixType(){var node=startNode();var type=node.elementType=parsePrimaryType();if(tokType===_bracketL){expect(_bracketL);expect(_bracketR);return finishNode(node,"ArrayTypeAnnotation")}return type}function parsePrefixType(){var node=startNode();if(eat(_question)){node.typeAnnotation=parsePrefixType();return finishNode(node,"NullableTypeAnnotation")}return parsePostfixType()}function parseIntersectionType(){var node=startNode();var type=parsePrefixType();node.types=[type];while(eat(_bitwiseAND)){node.types.push(parsePrefixType())}return node.types.length===1?type:finishNode(node,"IntersectionTypeAnnotation")}function parseUnionType(){var node=startNode();var type=parseIntersectionType();node.types=[type];while(eat(_bitwiseOR)){node.types.push(parseIntersectionType())}return node.types.length===1?type:finishNode(node,"UnionTypeAnnotation")}function parseType(){var oldInType=inType;inType=true;var type=parseUnionType();inType=oldInType;return type}function parseTypeAnnotation(){var node=startNode();var oldInType=inType;inType=true;expect(_colon);node.typeAnnotation=parseType();inType=oldInType;return finishNode(node,"TypeAnnotation")}function parseTypeAnnotatableIdentifier(requireTypeAnnotation,canBeOptionalParam){var node=startNode();var ident=parseIdent();var isOptionalParam=false;if(canBeOptionalParam&&eat(_question)){expect(_question);isOptionalParam=true}if(requireTypeAnnotation||tokType===_colon){ident.typeAnnotation=parseTypeAnnotation();finishNode(ident,ident.type)}if(isOptionalParam){ident.optional=true;finishNode(ident,ident.type)}return ident}})},{}],106:[function(require,module,exports){var types=require("../lib/types");var Type=types.Type;var def=Type.def;var or=Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isNumber=builtin.number;var isBoolean=builtin.boolean;var isRegExp=builtin.RegExp;var shared=require("../lib/shared");var defaults=shared.defaults;var geq=shared.geq;def("Printable").field("loc",or(def("SourceLocation"),null),defaults["null"],true);def("Node").bases("Printable").field("type",isString);def("SourceLocation").build("start","end","source").field("start",def("Position")).field("end",def("Position")).field("source",or(isString,null),defaults["null"]);def("Position").build("line","column").field("line",geq(1)).field("column",geq(0));def("Program").bases("Node").build("body").field("body",[def("Statement")]).field("comments",or([or(def("Block"),def("Line"))],null),defaults["null"],true);def("Function").bases("Node").field("id",or(def("Identifier"),null),defaults["null"]).field("params",[def("Pattern")]).field("body",or(def("BlockStatement"),def("Expression")));def("Statement").bases("Node");def("EmptyStatement").bases("Statement").build();def("BlockStatement").bases("Statement").build("body").field("body",[def("Statement")]);def("ExpressionStatement").bases("Statement").build("expression").field("expression",def("Expression"));def("IfStatement").bases("Statement").build("test","consequent","alternate").field("test",def("Expression")).field("consequent",def("Statement")).field("alternate",or(def("Statement"),null),defaults["null"]);def("LabeledStatement").bases("Statement").build("label","body").field("label",def("Identifier")).field("body",def("Statement"));def("BreakStatement").bases("Statement").build("label").field("label",or(def("Identifier"),null),defaults["null"]);def("ContinueStatement").bases("Statement").build("label").field("label",or(def("Identifier"),null),defaults["null"]);def("WithStatement").bases("Statement").build("object","body").field("object",def("Expression")).field("body",def("Statement"));def("SwitchStatement").bases("Statement").build("discriminant","cases","lexical").field("discriminant",def("Expression")).field("cases",[def("SwitchCase")]).field("lexical",isBoolean,defaults["false"]);def("ReturnStatement").bases("Statement").build("argument").field("argument",or(def("Expression"),null));def("ThrowStatement").bases("Statement").build("argument").field("argument",def("Expression"));def("TryStatement").bases("Statement").build("block","handler","finalizer").field("block",def("BlockStatement")).field("handler",or(def("CatchClause"),null),function(){return this.handlers&&this.handlers[0]||null}).field("handlers",[def("CatchClause")],function(){return this.handler?[this.handler]:[]},true).field("guardedHandlers",[def("CatchClause")],defaults.emptyArray).field("finalizer",or(def("BlockStatement"),null),defaults["null"]);def("CatchClause").bases("Node").build("param","guard","body").field("param",def("Pattern")).field("guard",or(def("Expression"),null),defaults["null"]).field("body",def("BlockStatement"));def("WhileStatement").bases("Statement").build("test","body").field("test",def("Expression")).field("body",def("Statement"));def("DoWhileStatement").bases("Statement").build("body","test").field("body",def("Statement")).field("test",def("Expression"));def("ForStatement").bases("Statement").build("init","test","update","body").field("init",or(def("VariableDeclaration"),def("Expression"),null)).field("test",or(def("Expression"),null)).field("update",or(def("Expression"),null)).field("body",def("Statement"));def("ForInStatement").bases("Statement").build("left","right","body","each").field("left",or(def("VariableDeclaration"),def("Expression"))).field("right",def("Expression")).field("body",def("Statement")).field("each",isBoolean);def("DebuggerStatement").bases("Statement").build();def("Declaration").bases("Statement");def("FunctionDeclaration").bases("Function","Declaration").build("id","params","body").field("id",def("Identifier"));def("FunctionExpression").bases("Function","Expression").build("id","params","body");def("VariableDeclaration").bases("Declaration").build("kind","declarations").field("kind",or("var","let","const")).field("declarations",[or(def("VariableDeclarator"),def("Identifier"))]);def("VariableDeclarator").bases("Node").build("id","init").field("id",def("Pattern")).field("init",or(def("Expression"),null));def("Expression").bases("Node","Pattern");def("ThisExpression").bases("Expression").build();def("ArrayExpression").bases("Expression").build("elements").field("elements",[or(def("Expression"),null)]);def("ObjectExpression").bases("Expression").build("properties").field("properties",[def("Property")]);def("Property").bases("Node").build("kind","key","value").field("kind",or("init","get","set")).field("key",or(def("Literal"),def("Identifier"))).field("value",def("Expression"));def("SequenceExpression").bases("Expression").build("expressions").field("expressions",[def("Expression")]);var UnaryOperator=or("-","+","!","~","typeof","void","delete");def("UnaryExpression").bases("Expression").build("operator","argument","prefix").field("operator",UnaryOperator).field("argument",def("Expression")).field("prefix",isBoolean,defaults["true"]);var BinaryOperator=or("==","!=","===","!==","<","<=",">",">=","<<",">>",">>>","+","-","*","/","%","&","|","^","in","instanceof","..");def("BinaryExpression").bases("Expression").build("operator","left","right").field("operator",BinaryOperator).field("left",def("Expression")).field("right",def("Expression"));var AssignmentOperator=or("=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","|=","^=","&=");def("AssignmentExpression").bases("Expression").build("operator","left","right").field("operator",AssignmentOperator).field("left",def("Pattern")).field("right",def("Expression"));var UpdateOperator=or("++","--");def("UpdateExpression").bases("Expression").build("operator","argument","prefix").field("operator",UpdateOperator).field("argument",def("Expression")).field("prefix",isBoolean);var LogicalOperator=or("||","&&");def("LogicalExpression").bases("Expression").build("operator","left","right").field("operator",LogicalOperator).field("left",def("Expression")).field("right",def("Expression"));def("ConditionalExpression").bases("Expression").build("test","consequent","alternate").field("test",def("Expression")).field("consequent",def("Expression")).field("alternate",def("Expression"));def("NewExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);def("CallExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);def("MemberExpression").bases("Expression").build("object","property","computed").field("object",def("Expression")).field("property",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("Pattern").bases("Node");def("ObjectPattern").bases("Pattern").build("properties").field("properties",[def("PropertyPattern")]);def("PropertyPattern").bases("Pattern").build("key","pattern").field("key",or(def("Literal"),def("Identifier"))).field("pattern",def("Pattern"));def("ArrayPattern").bases("Pattern").build("elements").field("elements",[or(def("Pattern"),null)]);def("SwitchCase").bases("Node").build("test","consequent").field("test",or(def("Expression"),null)).field("consequent",[def("Statement")]);def("Identifier").bases("Node","Expression","Pattern").build("name").field("name",isString);def("Literal").bases("Node","Expression").build("value").field("value",or(isString,isBoolean,null,isNumber,isRegExp));def("Block").bases("Printable").build("loc","value").field("value",isString);def("Line").bases("Printable").build("loc","value").field("value",isString)},{"../lib/shared":117,"../lib/types":118}],107:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isBoolean=builtin.boolean;def("XMLDefaultDeclaration").bases("Declaration").field("namespace",def("Expression"));def("XMLAnyName").bases("Expression");def("XMLQualifiedIdentifier").bases("Expression").field("left",or(def("Identifier"),def("XMLAnyName"))).field("right",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("XMLFunctionQualifiedIdentifier").bases("Expression").field("right",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("XMLAttributeSelector").bases("Expression").field("attribute",def("Expression"));def("XMLFilterExpression").bases("Expression").field("left",def("Expression")).field("right",def("Expression"));def("XMLElement").bases("XML","Expression").field("contents",[def("XML")]);def("XMLList").bases("XML","Expression").field("contents",[def("XML")]);def("XML").bases("Node");def("XMLEscape").bases("XML").field("expression",def("Expression"));def("XMLText").bases("XML").field("text",isString);def("XMLStartTag").bases("XML").field("contents",[def("XML")]);def("XMLEndTag").bases("XML").field("contents",[def("XML")]);def("XMLPointTag").bases("XML").field("contents",[def("XML")]);def("XMLName").bases("XML").field("contents",or(isString,[def("XML")]));def("XMLAttribute").bases("XML").field("value",isString);def("XMLCdata").bases("XML").field("contents",isString);def("XMLComment").bases("XML").field("contents",isString);def("XMLProcessingInstruction").bases("XML").field("target",isString).field("contents",or(isString,null))},{"../lib/types":118,"./core":106}],108:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isBoolean=builtin.boolean;var isObject=builtin.object;var isString=builtin.string;var defaults=require("../lib/shared").defaults;def("Function").field("generator",isBoolean,defaults["false"]).field("expression",isBoolean,defaults["false"]).field("defaults",[or(def("Expression"),null)],defaults.emptyArray).field("rest",or(def("Identifier"),null),defaults["null"]);def("FunctionDeclaration").build("id","params","body","generator","expression");def("FunctionExpression").build("id","params","body","generator","expression");def("ArrowFunctionExpression").bases("Function","Expression").build("params","body","expression").field("id",null,defaults["null"]).field("generator",false);def("YieldExpression").bases("Expression").build("argument","delegate").field("argument",or(def("Expression"),null)).field("delegate",isBoolean,defaults["false"]);def("GeneratorExpression").bases("Expression").build("body","blocks","filter").field("body",def("Expression")).field("blocks",[def("ComprehensionBlock")]).field("filter",or(def("Expression"),null));def("ComprehensionExpression").bases("Expression").build("body","blocks","filter").field("body",def("Expression")).field("blocks",[def("ComprehensionBlock")]).field("filter",or(def("Expression"),null));def("ComprehensionBlock").bases("Node").build("left","right","each").field("left",def("Pattern")).field("right",def("Expression")).field("each",isBoolean);def("ModuleSpecifier").bases("Literal").build("value").field("value",isString);def("Property").field("key",or(def("Literal"),def("Identifier"),def("Expression"))).field("method",isBoolean,defaults["false"]).field("shorthand",isBoolean,defaults["false"]).field("computed",isBoolean,defaults["false"]);def("PropertyPattern").field("key",or(def("Literal"),def("Identifier"),def("Expression"))).field("computed",isBoolean,defaults["false"]);def("MethodDefinition").bases("Declaration").build("kind","key","value").field("kind",or("init","get","set","")).field("key",or(def("Literal"),def("Identifier"),def("Expression"))).field("value",def("Function")).field("computed",isBoolean,defaults["false"]);def("SpreadElement").bases("Node").build("argument").field("argument",def("Expression"));def("ArrayExpression").field("elements",[or(def("Expression"),def("SpreadElement"),null)]);def("NewExpression").field("arguments",[or(def("Expression"),def("SpreadElement"))]);def("CallExpression").field("arguments",[or(def("Expression"),def("SpreadElement"))]);def("SpreadElementPattern").bases("Pattern").build("argument").field("argument",def("Pattern"));var ClassBodyElement=or(def("MethodDefinition"),def("VariableDeclarator"),def("ClassPropertyDefinition"),def("ClassProperty"));def("ClassProperty").bases("Declaration").build("key").field("key",or(def("Literal"),def("Identifier"),def("Expression"))).field("computed",isBoolean,defaults["false"]);def("ClassPropertyDefinition").bases("Declaration").build("definition").field("definition",ClassBodyElement);def("ClassBody").bases("Declaration").build("body").field("body",[ClassBodyElement]);def("ClassDeclaration").bases("Declaration").build("id","body","superClass").field("id",def("Identifier")).field("body",def("ClassBody")).field("superClass",or(def("Expression"),null),defaults["null"]);def("ClassExpression").bases("Expression").build("id","body","superClass").field("id",or(def("Identifier"),null),defaults["null"]).field("body",def("ClassBody")).field("superClass",or(def("Expression"),null),defaults["null"]).field("implements",[def("ClassImplements")],defaults.emptyArray);def("ClassImplements").bases("Node").build("id").field("id",def("Identifier")).field("superClass",or(def("Expression"),null),defaults["null"]);def("Specifier").bases("Node");def("NamedSpecifier").bases("Specifier").field("id",def("Identifier")).field("name",or(def("Identifier"),null),defaults["null"]);def("ExportSpecifier").bases("NamedSpecifier").build("id","name");def("ExportBatchSpecifier").bases("Specifier").build();def("ImportSpecifier").bases("NamedSpecifier").build("id","name");def("ImportNamespaceSpecifier").bases("Specifier").build("id").field("id",def("Identifier"));def("ImportDefaultSpecifier").bases("Specifier").build("id").field("id",def("Identifier"));def("ExportDeclaration").bases("Declaration").build("default","declaration","specifiers","source").field("default",isBoolean).field("declaration",or(def("Declaration"),def("Expression"),null)).field("specifiers",[or(def("ExportSpecifier"),def("ExportBatchSpecifier"))],defaults.emptyArray).field("source",or(def("ModuleSpecifier"),null),defaults["null"]);def("ImportDeclaration").bases("Declaration").build("specifiers","source").field("specifiers",[or(def("ImportSpecifier"),def("ImportNamespaceSpecifier"),def("ImportDefaultSpecifier"))],defaults.emptyArray).field("source",def("ModuleSpecifier"));def("TaggedTemplateExpression").bases("Expression").field("tag",def("Expression")).field("quasi",def("TemplateLiteral"));def("TemplateLiteral").bases("Expression").build("quasis","expressions").field("quasis",[def("TemplateElement")]).field("expressions",[def("Expression")]);def("TemplateElement").bases("Node").build("value","tail").field("value",{cooked:isString,raw:isString}).field("tail",isBoolean)},{"../lib/shared":117,"../lib/types":118,"./core":106}],109:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isBoolean=builtin.boolean;var defaults=require("../lib/shared").defaults;def("Function").field("async",isBoolean,defaults["false"]);def("SpreadProperty").bases("Node").build("argument").field("argument",def("Expression"));def("ObjectExpression").field("properties",[or(def("Property"),def("SpreadProperty"))]);def("SpreadPropertyPattern").bases("Pattern").build("argument").field("argument",def("Pattern"));def("ObjectPattern").field("properties",[or(def("PropertyPattern"),def("SpreadPropertyPattern"))]);def("AwaitExpression").bases("Expression").build("argument","all").field("argument",or(def("Expression"),null)).field("all",isBoolean,defaults["false"])},{"../lib/shared":117,"../lib/types":118,"./core":106}],110:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isBoolean=builtin.boolean;var defaults=require("../lib/shared").defaults;def("XJSAttribute").bases("Node").build("name","value").field("name",or(def("XJSIdentifier"),def("XJSNamespacedName"))).field("value",or(def("Literal"),def("XJSExpressionContainer"),null),defaults["null"]);def("XJSIdentifier").bases("Node").build("name").field("name",isString);def("XJSNamespacedName").bases("Node").build("namespace","name").field("namespace",def("XJSIdentifier")).field("name",def("XJSIdentifier"));def("XJSMemberExpression").bases("MemberExpression").build("object","property").field("object",or(def("XJSIdentifier"),def("XJSMemberExpression"))).field("property",def("XJSIdentifier")).field("computed",isBoolean,defaults.false);var XJSElementName=or(def("XJSIdentifier"),def("XJSNamespacedName"),def("XJSMemberExpression"));def("XJSSpreadAttribute").bases("Node").build("argument").field("argument",def("Expression"));var XJSAttributes=[or(def("XJSAttribute"),def("XJSSpreadAttribute"))];def("XJSExpressionContainer").bases("Expression").build("expression").field("expression",def("Expression"));def("XJSElement").bases("Expression").build("openingElement","closingElement","children").field("openingElement",def("XJSOpeningElement")).field("closingElement",or(def("XJSClosingElement"),null),defaults["null"]).field("children",[or(def("XJSElement"),def("XJSExpressionContainer"),def("XJSText"),def("Literal"))],defaults.emptyArray).field("name",XJSElementName,function(){return this.openingElement.name}).field("selfClosing",isBoolean,function(){return this.openingElement.selfClosing}).field("attributes",XJSAttributes,function(){return this.openingElement.attributes});def("XJSOpeningElement").bases("Node").build("name","attributes","selfClosing").field("name",XJSElementName).field("attributes",XJSAttributes,defaults.emptyArray).field("selfClosing",isBoolean,defaults["false"]);def("XJSClosingElement").bases("Node").build("name").field("name",XJSElementName);def("XJSText").bases("Literal").build("value").field("value",isString);def("XJSEmptyExpression").bases("Expression").build();def("Type").bases("Node");def("AnyTypeAnnotation").bases("Type");def("VoidTypeAnnotation").bases("Type");def("NumberTypeAnnotation").bases("Type");def("StringTypeAnnotation").bases("Type");def("StringLiteralTypeAnnotation").bases("Type").build("value","raw").field("value",isString).field("raw",isString);def("BooleanTypeAnnotation").bases("Type");def("TypeAnnotation").bases("Node").build("typeAnnotation").field("typeAnnotation",def("Type"));def("NullableTypeAnnotation").bases("Type").build("typeAnnotation").field("typeAnnotation",def("Type"));def("FunctionTypeAnnotation").bases("Type").build("params","returnType","rest","typeParameters").field("params",[def("FunctionTypeParam")]).field("returnType",def("Type")).field("rest",or(def("FunctionTypeParam"),null)).field("typeParameters",or(def("TypeParameterDeclaration"),null));def("FunctionTypeParam").bases("Node").build("name","typeAnnotation","optional").field("name",def("Identifier")).field("typeAnnotation",def("Type")).field("optional",isBoolean);def("ArrayTypeAnnotation").bases("Type").build("elementType").field("elementType",def("Type"));def("ObjectTypeAnnotation").bases("Type").build("properties").field("properties",[def("ObjectTypeProperty")]).field("indexers",[def("ObjectTypeIndexer")],defaults.emptyArray).field("callProperties",[def("ObjectTypeCallProperty")],defaults.emptyArray);def("ObjectTypeProperty").bases("Node").build("key","value","optional").field("key",or(def("Literal"),def("Identifier"))).field("value",def("Type")).field("optional",isBoolean);def("ObjectTypeIndexer").bases("Node").build("id","key","value").field("id",def("Identifier")).field("key",def("Type")).field("value",def("Type"));def("ObjectTypeCallProperty").bases("Node").build("value").field("value",def("FunctionTypeAnnotation")).field("static",isBoolean,false);def("QualifiedTypeIdentifier").bases("Node").build("qualification","id").field("qualification",or(def("Identifier"),def("QualifiedTypeIdentifier"))).field("id",def("Identifier"));def("GenericTypeAnnotation").bases("Type").build("id","typeParameters").field("id",or(def("Identifier"),def("QualifiedTypeIdentifier"))).field("typeParameters",or(def("TypeParameterInstantiation"),null));def("MemberTypeAnnotation").bases("Type").build("object","property").field("object",def("Identifier")).field("property",or(def("MemberTypeAnnotation"),def("GenericTypeAnnotation")));def("UnionTypeAnnotation").bases("Type").build("types").field("types",[def("Type")]);def("IntersectionTypeAnnotation").bases("Type").build("types").field("types",[def("Type")]);def("TypeofTypeAnnotation").bases("Type").build("argument").field("argument",def("Type"));def("Identifier").field("typeAnnotation",or(def("TypeAnnotation"),null),defaults["null"]);def("TypeParameterDeclaration").bases("Node").build("params").field("params",[def("Identifier")]);def("TypeParameterInstantiation").bases("Node").build("params").field("params",[def("Type")]);def("Function").field("returnType",or(def("TypeAnnotation"),null),defaults["null"]).field("typeParameters",or(def("TypeParameterDeclaration"),null),defaults["null"]);def("ClassProperty").build("key","typeAnnotation").field("typeAnnotation",def("TypeAnnotation")).field("static",isBoolean,false);def("ClassImplements").field("typeParameters",or(def("TypeParameterInstantiation"),null),defaults["null"]);def("InterfaceDeclaration").bases("Statement").build("id","body","extends").field("id",def("Identifier")).field("typeParameters",or(def("TypeParameterDeclaration"),null),defaults["null"]).field("body",def("ObjectTypeAnnotation")).field("extends",[def("InterfaceExtends")]);def("InterfaceExtends").bases("Node").build("id").field("id",def("Identifier")).field("typeParameters",or(def("TypeParameterInstantiation"),null));def("TypeAlias").bases("Statement").build("id","typeParameters","right").field("id",def("Identifier")).field("typeParameters",or(def("TypeParameterDeclaration"),null)).field("right",def("Type"));def("TupleTypeAnnotation").bases("Type").build("types").field("types",[def("Type")]);def("DeclareVariable").bases("Statement").build("id").field("id",def("Identifier"));def("DeclareFunction").bases("Statement").build("id").field("id",def("Identifier"));def("DeclareClass").bases("InterfaceDeclaration").build("id");def("DeclareModule").bases("Statement").build("id","body").field("id",or(def("Identifier"),def("Literal"))).field("body",def("BlockStatement"))},{"../lib/shared":117,"../lib/types":118,"./core":106}],111:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var geq=require("../lib/shared").geq;def("ForOfStatement").bases("Statement").build("left","right","body").field("left",or(def("VariableDeclaration"),def("Expression"))).field("right",def("Expression")).field("body",def("Statement"));def("LetStatement").bases("Statement").build("head","body").field("head",[def("VariableDeclarator")]).field("body",def("Statement"));def("LetExpression").bases("Expression").build("head","body").field("head",[def("VariableDeclarator")]).field("body",def("Expression"));def("GraphExpression").bases("Expression").build("index","expression").field("index",geq(0)).field("expression",def("Literal"));def("GraphIndexExpression").bases("Expression").build("index").field("index",geq(0))},{"../lib/shared":117,"../lib/types":118,"./core":106}],112:[function(require,module,exports){var assert=require("assert");var types=require("../main");var getFieldNames=types.getFieldNames;var getFieldValue=types.getFieldValue;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var isDate=types.builtInTypes.Date;var isRegExp=types.builtInTypes.RegExp;var hasOwn=Object.prototype.hasOwnProperty;function astNodesAreEquivalent(a,b,problemPath){if(isArray.check(problemPath)){problemPath.length=0}else{problemPath=null}return areEquivalent(a,b,problemPath)}astNodesAreEquivalent.assert=function(a,b){var problemPath=[];if(!astNodesAreEquivalent(a,b,problemPath)){if(problemPath.length===0){assert.strictEqual(a,b)}else{assert.ok(false,"Nodes differ in the following path: "+problemPath.map(subscriptForProperty).join(""))}}};function subscriptForProperty(property){if(/[_$a-z][_$a-z0-9]*/i.test(property)){return"."+property}return"["+JSON.stringify(property)+"]"}function areEquivalent(a,b,problemPath){if(a===b){return true}if(isArray.check(a)){return arraysAreEquivalent(a,b,problemPath)}if(isObject.check(a)){return objectsAreEquivalent(a,b,problemPath)}if(isDate.check(a)){return isDate.check(b)&&+a===+b}if(isRegExp.check(a)){return isRegExp.check(b)&&(a.source===b.source&&a.global===b.global&&a.multiline===b.multiline&&a.ignoreCase===b.ignoreCase)}return a==b}function arraysAreEquivalent(a,b,problemPath){isArray.assert(a);var aLength=a.length;if(!isArray.check(b)||b.length!==aLength){if(problemPath){problemPath.push("length")}return false}for(var i=0;i<aLength;++i){if(problemPath){problemPath.push(i)}if(i in a!==i in b){return false}if(!areEquivalent(a[i],b[i],problemPath)){return false}if(problemPath){assert.strictEqual(problemPath.pop(),i)}}return true}function objectsAreEquivalent(a,b,problemPath){isObject.assert(a);if(!isObject.check(b)){return false}if(a.type!==b.type){if(problemPath){problemPath.push("type")}return false}var aNames=getFieldNames(a);var aNameCount=aNames.length;var bNames=getFieldNames(b);var bNameCount=bNames.length;if(aNameCount===bNameCount){for(var i=0;i<aNameCount;++i){var name=aNames[i];var aChild=getFieldValue(a,name);var bChild=getFieldValue(b,name);if(problemPath){problemPath.push(name)
}if(!areEquivalent(aChild,bChild,problemPath)){return false}if(problemPath){assert.strictEqual(problemPath.pop(),name)}}return true}if(!problemPath){return false}var seenNames=Object.create(null);for(i=0;i<aNameCount;++i){seenNames[aNames[i]]=true}for(i=0;i<bNameCount;++i){name=bNames[i];if(!hasOwn.call(seenNames,name)){problemPath.push(name);return false}delete seenNames[name]}for(name in seenNames){problemPath.push(name);break}return false}module.exports=astNodesAreEquivalent},{"../main":119,assert:121}],113:[function(require,module,exports){var assert=require("assert");var types=require("./types");var n=types.namedTypes;var b=types.builders;var isNumber=types.builtInTypes.number;var isArray=types.builtInTypes.array;var Path=require("./path");var Scope=require("./scope");function NodePath(value,parentPath,name){assert.ok(this instanceof NodePath);Path.call(this,value,parentPath,name)}require("util").inherits(NodePath,Path);var NPp=NodePath.prototype;Object.defineProperties(NPp,{node:{get:function(){Object.defineProperty(this,"node",{configurable:true,value:this._computeNode()});return this.node}},parent:{get:function(){Object.defineProperty(this,"parent",{configurable:true,value:this._computeParent()});return this.parent}},scope:{get:function(){Object.defineProperty(this,"scope",{configurable:true,value:this._computeScope()});return this.scope}}});NPp.replace=function(){delete this.node;delete this.parent;delete this.scope;return Path.prototype.replace.apply(this,arguments)};NPp.prune=function(){var remainingNodePath=this.parent;this.replace();return cleanUpNodesAfterPrune(remainingNodePath)};NPp._computeNode=function(){var value=this.value;if(n.Node.check(value)){return value}var pp=this.parentPath;return pp&&pp.node||null};NPp._computeParent=function(){var value=this.value;var pp=this.parentPath;if(!n.Node.check(value)){while(pp&&!n.Node.check(pp.value)){pp=pp.parentPath}if(pp){pp=pp.parentPath}}while(pp&&!n.Node.check(pp.value)){pp=pp.parentPath}return pp||null};NPp._computeScope=function(){var value=this.value;var pp=this.parentPath;var scope=pp&&pp.scope;if(n.Node.check(value)&&Scope.isEstablishedBy(value)){scope=new Scope(this,scope)}return scope||null};NPp.getValueProperty=function(name){return types.getFieldValue(this.value,name)};NPp.needsParens=function(assumeExpressionContext){var pp=this.parentPath;if(!pp){return false}var node=this.value;if(!n.Expression.check(node)){return false}if(node.type==="Identifier"){return false}while(!n.Node.check(pp.value)){pp=pp.parentPath;if(!pp){return false}}var parent=pp.value;switch(node.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return parent.type==="MemberExpression"&&this.name==="object"&&parent.object===node;case"BinaryExpression":case"LogicalExpression":switch(parent.type){case"CallExpression":return this.name==="callee"&&parent.callee===node;case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return true;case"MemberExpression":return this.name==="object"&&parent.object===node;case"BinaryExpression":case"LogicalExpression":var po=parent.operator;var pp=PRECEDENCE[po];var no=node.operator;var np=PRECEDENCE[no];if(pp>np){return true}if(pp===np&&this.name==="right"){assert.strictEqual(parent.right,node);return true}default:return false}case"SequenceExpression":switch(parent.type){case"ForStatement":return false;case"ExpressionStatement":return this.name!=="expression";default:return true}case"YieldExpression":switch(parent.type){case"BinaryExpression":case"LogicalExpression":case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"CallExpression":case"MemberExpression":case"NewExpression":case"ConditionalExpression":case"YieldExpression":return true;default:return false}case"Literal":return parent.type==="MemberExpression"&&isNumber.check(node.value)&&this.name==="object"&&parent.object===node;case"AssignmentExpression":case"ConditionalExpression":switch(parent.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"BinaryExpression":case"LogicalExpression":return true;case"CallExpression":return this.name==="callee"&&parent.callee===node;case"ConditionalExpression":return this.name==="test"&&parent.test===node;case"MemberExpression":return this.name==="object"&&parent.object===node;default:return false}default:if(parent.type==="NewExpression"&&this.name==="callee"&&parent.callee===node){return containsCallExpression(node)}}if(assumeExpressionContext!==true&&!this.canBeFirstInStatement()&&this.firstInStatement())return true;return false};function isBinary(node){return n.BinaryExpression.check(node)||n.LogicalExpression.check(node)}function isUnaryLike(node){return n.UnaryExpression.check(node)||n.SpreadElement&&n.SpreadElement.check(node)||n.SpreadProperty&&n.SpreadProperty.check(node)}var PRECEDENCE={};[["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]].forEach(function(tier,i){tier.forEach(function(op){PRECEDENCE[op]=i})});function containsCallExpression(node){if(n.CallExpression.check(node)){return true}if(isArray.check(node)){return node.some(containsCallExpression)}if(n.Node.check(node)){return types.someField(node,function(name,child){return containsCallExpression(child)})}return false}NPp.canBeFirstInStatement=function(){var node=this.node;return!n.FunctionExpression.check(node)&&!n.ObjectExpression.check(node)};NPp.firstInStatement=function(){return firstInStatement(this)};function firstInStatement(path){for(var node,parent;path.parent;path=path.parent){node=path.node;parent=path.parent.node;if(n.BlockStatement.check(parent)&&path.parent.name==="body"&&path.name===0){assert.strictEqual(parent.body[0],node);return true}if(n.ExpressionStatement.check(parent)&&path.name==="expression"){assert.strictEqual(parent.expression,node);return true}if(n.SequenceExpression.check(parent)&&path.parent.name==="expressions"&&path.name===0){assert.strictEqual(parent.expressions[0],node);continue}if(n.CallExpression.check(parent)&&path.name==="callee"){assert.strictEqual(parent.callee,node);continue}if(n.MemberExpression.check(parent)&&path.name==="object"){assert.strictEqual(parent.object,node);continue}if(n.ConditionalExpression.check(parent)&&path.name==="test"){assert.strictEqual(parent.test,node);continue}if(isBinary(parent)&&path.name==="left"){assert.strictEqual(parent.left,node);continue}if(n.UnaryExpression.check(parent)&&!parent.prefix&&path.name==="argument"){assert.strictEqual(parent.argument,node);continue}return false}return true}function cleanUpNodesAfterPrune(remainingNodePath){if(n.VariableDeclaration.check(remainingNodePath.node)){var declarations=remainingNodePath.get("declarations").value;if(!declarations||declarations.length===0){return remainingNodePath.prune()}}else if(n.ExpressionStatement.check(remainingNodePath.node)){if(!remainingNodePath.get("expression").value){return remainingNodePath.prune()}}else if(n.IfStatement.check(remainingNodePath.node)){cleanUpIfStatementAfterPrune(remainingNodePath)}return remainingNodePath}function cleanUpIfStatementAfterPrune(ifStatement){var testExpression=ifStatement.get("test").value;var alternate=ifStatement.get("alternate").value;var consequent=ifStatement.get("consequent").value;if(!consequent&&!alternate){var testExpressionStatement=b.expressionStatement(testExpression);ifStatement.replace(testExpressionStatement)}else if(!consequent&&alternate){var negatedTestExpression=b.unaryExpression("!",testExpression,true);if(n.UnaryExpression.check(testExpression)&&testExpression.operator==="!"){negatedTestExpression=testExpression.argument}ifStatement.get("test").replace(negatedTestExpression);ifStatement.get("consequent").replace(alternate);ifStatement.get("alternate").replace()}}module.exports=NodePath},{"./path":115,"./scope":116,"./types":118,assert:121,util:145}],114:[function(require,module,exports){var assert=require("assert");var types=require("./types");var NodePath=require("./node-path");var Node=types.namedTypes.Node;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var isFunction=types.builtInTypes.function;var hasOwn=Object.prototype.hasOwnProperty;var undefined;function PathVisitor(){assert.ok(this instanceof PathVisitor);this._reusableContextStack=[];this._methodNameTable=computeMethodNameTable(this);this.Context=makeContextConstructor(this);this._visiting=false;this._changeReported=false}function computeMethodNameTable(visitor){var typeNames=Object.create(null);for(var methodName in visitor){if(/^visit[A-Z]/.test(methodName)){typeNames[methodName.slice("visit".length)]=true}}var supertypeTable=types.computeSupertypeLookupTable(typeNames);var methodNameTable=Object.create(null);var typeNames=Object.keys(supertypeTable);var typeNameCount=typeNames.length;for(var i=0;i<typeNameCount;++i){var typeName=typeNames[i];methodName="visit"+supertypeTable[typeName];if(isFunction.check(visitor[methodName])){methodNameTable[typeName]=methodName}}return methodNameTable}PathVisitor.fromMethodsObject=function fromMethodsObject(methods){if(methods instanceof PathVisitor){return methods}if(!isObject.check(methods)){return new PathVisitor}function Visitor(){assert.ok(this instanceof Visitor);PathVisitor.call(this)}var Vp=Visitor.prototype=Object.create(PVp);Vp.constructor=Visitor;extend(Vp,methods);extend(Visitor,PathVisitor);isFunction.assert(Visitor.fromMethodsObject);isFunction.assert(Visitor.visit);return new Visitor};function extend(target,source){for(var property in source){if(hasOwn.call(source,property)){target[property]=source[property]}}return target}PathVisitor.visit=function visit(node,methods){return PathVisitor.fromMethodsObject(methods).visit(node)};var PVp=PathVisitor.prototype;var recursiveVisitWarning=["Recursively calling visitor.visit(path) resets visitor state.","Try this.visit(path) or this.traverse(path) instead."].join(" ");PVp.visit=function(){assert.ok(!this._visiting,recursiveVisitWarning);this._visiting=true;this._changeReported=false;var argc=arguments.length;var args=new Array(argc);for(var i=0;i<argc;++i){args[i]=arguments[i]}if(!(args[0]instanceof NodePath)){args[0]=new NodePath({root:args[0]}).get("root")}this.reset.apply(this,args);try{return this.visitWithoutReset(args[0])}finally{this._visiting=false}};PVp.reset=function(path){};PVp.visitWithoutReset=function(path){if(this instanceof this.Context){return this.visitor.visitWithoutReset(path)}assert.ok(path instanceof NodePath);var value=path.value;var methodName=Node.check(value)&&this._methodNameTable[value.type];if(methodName){var context=this.acquireContext(path);try{return context.invokeVisitorMethod(methodName)}finally{this.releaseContext(context)}}else{return visitChildren(path,this)}};function visitChildren(path,visitor){assert.ok(path instanceof NodePath);assert.ok(visitor instanceof PathVisitor);var value=path.value;if(isArray.check(value)){path.each(visitor.visitWithoutReset,visitor)}else if(!isObject.check(value)){}else{var childNames=types.getFieldNames(value);var childCount=childNames.length;var childPaths=[];for(var i=0;i<childCount;++i){var childName=childNames[i];if(!hasOwn.call(value,childName)){value[childName]=types.getFieldValue(value,childName)}childPaths.push(path.get(childName))}for(var i=0;i<childCount;++i){visitor.visitWithoutReset(childPaths[i])}}return path.value}PVp.acquireContext=function(path){if(this._reusableContextStack.length===0){return new this.Context(path)}return this._reusableContextStack.pop().reset(path)};PVp.releaseContext=function(context){assert.ok(context instanceof this.Context);this._reusableContextStack.push(context);context.currentPath=null};PVp.reportChanged=function(){this._changeReported=true};PVp.wasChangeReported=function(){return this._changeReported};function makeContextConstructor(visitor){function Context(path){assert.ok(this instanceof Context);assert.ok(this instanceof PathVisitor);assert.ok(path instanceof NodePath);Object.defineProperty(this,"visitor",{value:visitor,writable:false,enumerable:true,configurable:false});this.currentPath=path;this.needToCallTraverse=true;Object.seal(this)}assert.ok(visitor instanceof PathVisitor);var Cp=Context.prototype=Object.create(visitor);Cp.constructor=Context;extend(Cp,sharedContextProtoMethods);return Context}var sharedContextProtoMethods=Object.create(null);sharedContextProtoMethods.reset=function reset(path){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);this.currentPath=path;this.needToCallTraverse=true;return this};sharedContextProtoMethods.invokeVisitorMethod=function invokeVisitorMethod(methodName){assert.ok(this instanceof this.Context);assert.ok(this.currentPath instanceof NodePath);var result=this.visitor[methodName].call(this,this.currentPath);if(result===false){this.needToCallTraverse=false}else if(result!==undefined){this.currentPath=this.currentPath.replace(result)[0];if(this.needToCallTraverse){this.traverse(this.currentPath)}}assert.strictEqual(this.needToCallTraverse,false,"Must either call this.traverse or return false in "+methodName);var path=this.currentPath;return path&&path.value};sharedContextProtoMethods.traverse=function traverse(path,newVisitor){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);assert.ok(this.currentPath instanceof NodePath);this.needToCallTraverse=false;return visitChildren(path,PathVisitor.fromMethodsObject(newVisitor||this.visitor))};sharedContextProtoMethods.visit=function visit(path,newVisitor){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);assert.ok(this.currentPath instanceof NodePath);this.needToCallTraverse=false;return PathVisitor.fromMethodsObject(newVisitor||this.visitor).visitWithoutReset(path)};sharedContextProtoMethods.reportChanged=function reportChanged(){this.visitor.reportChanged()};module.exports=PathVisitor},{"./node-path":113,"./types":118,assert:121}],115:[function(require,module,exports){var assert=require("assert");var Op=Object.prototype;var hasOwn=Op.hasOwnProperty;var types=require("./types");var isArray=types.builtInTypes.array;var isNumber=types.builtInTypes.number;var Ap=Array.prototype;var slice=Ap.slice;var map=Ap.map;function Path(value,parentPath,name){assert.ok(this instanceof Path);if(parentPath){assert.ok(parentPath instanceof Path)}else{parentPath=null;name=null}this.value=value;this.parentPath=parentPath;this.name=name;this.__childCache=null}var Pp=Path.prototype;function getChildCache(path){return path.__childCache||(path.__childCache=Object.create(null))}function getChildPath(path,name){var cache=getChildCache(path);var actualChildValue=path.getValueProperty(name);var childPath=cache[name];if(!hasOwn.call(cache,name)||childPath.value!==actualChildValue){childPath=cache[name]=new path.constructor(actualChildValue,path,name)}return childPath}Pp.getValueProperty=function getValueProperty(name){return this.value[name]};Pp.get=function get(name){var path=this;var names=arguments;var count=names.length;for(var i=0;i<count;++i){path=getChildPath(path,names[i])}return path};Pp.each=function each(callback,context){var childPaths=[];var len=this.value.length;var i=0;for(var i=0;i<len;++i){if(hasOwn.call(this.value,i)){childPaths[i]=this.get(i)}}context=context||this;for(i=0;i<len;++i){if(hasOwn.call(childPaths,i)){callback.call(context,childPaths[i])}}};Pp.map=function map(callback,context){var result=[];this.each(function(childPath){result.push(callback.call(this,childPath))},context);return result};Pp.filter=function filter(callback,context){var result=[];this.each(function(childPath){if(callback.call(this,childPath)){result.push(childPath)}},context);return result};function emptyMoves(){}function getMoves(path,offset,start,end){isArray.assert(path.value);if(offset===0){return emptyMoves}var length=path.value.length;if(length<1){return emptyMoves}var argc=arguments.length;if(argc===2){start=0;end=length}else if(argc===3){start=Math.max(start,0);end=length}else{start=Math.max(start,0);end=Math.min(end,length)}isNumber.assert(start);isNumber.assert(end);var moves=Object.create(null);var cache=getChildCache(path);for(var i=start;i<end;++i){if(hasOwn.call(path.value,i)){var childPath=path.get(i);assert.strictEqual(childPath.name,i);var newIndex=i+offset;childPath.name=newIndex;moves[newIndex]=childPath;delete cache[i]}}delete cache.length;return function(){for(var newIndex in moves){var childPath=moves[newIndex];assert.strictEqual(childPath.name,+newIndex);cache[newIndex]=childPath;path.value[newIndex]=childPath.value}}}Pp.shift=function shift(){var move=getMoves(this,-1);var result=this.value.shift();move();return result};Pp.unshift=function unshift(node){var move=getMoves(this,arguments.length);var result=this.value.unshift.apply(this.value,arguments);move();return result};Pp.push=function push(node){isArray.assert(this.value);delete getChildCache(this).length;return this.value.push.apply(this.value,arguments)};Pp.pop=function pop(){isArray.assert(this.value);var cache=getChildCache(this);delete cache[this.value.length-1];delete cache.length;return this.value.pop()};Pp.insertAt=function insertAt(index,node){var argc=arguments.length;var move=getMoves(this,argc-1,index);if(move===emptyMoves){return this}index=Math.max(index,0);for(var i=1;i<argc;++i){this.value[index+i-1]=arguments[i]}move();return this};Pp.insertBefore=function insertBefore(node){var pp=this.parentPath;var argc=arguments.length;var insertAtArgs=[this.name];for(var i=0;i<argc;++i){insertAtArgs.push(arguments[i])}return pp.insertAt.apply(pp,insertAtArgs)};Pp.insertAfter=function insertAfter(node){var pp=this.parentPath;var argc=arguments.length;var insertAtArgs=[this.name+1];for(var i=0;i<argc;++i){insertAtArgs.push(arguments[i])}return pp.insertAt.apply(pp,insertAtArgs)};function repairRelationshipWithParent(path){assert.ok(path instanceof Path);var pp=path.parentPath;if(!pp){return path}var parentValue=pp.value;var parentCache=getChildCache(pp);if(parentValue[path.name]===path.value){parentCache[path.name]=path}else if(isArray.check(parentValue)){var i=parentValue.indexOf(path.value);if(i>=0){parentCache[path.name=i]=path}}else{parentValue[path.name]=path.value;parentCache[path.name]=path}assert.strictEqual(parentValue[path.name],path.value);assert.strictEqual(path.parentPath.get(path.name),path);return path}Pp.replace=function replace(replacement){var results=[];var parentValue=this.parentPath.value;var parentCache=getChildCache(this.parentPath);var count=arguments.length;repairRelationshipWithParent(this);if(isArray.check(parentValue)){var originalLength=parentValue.length;var move=getMoves(this.parentPath,count-1,this.name+1);var spliceArgs=[this.name,1];for(var i=0;i<count;++i){spliceArgs.push(arguments[i])}var splicedOut=parentValue.splice.apply(parentValue,spliceArgs);assert.strictEqual(splicedOut[0],this.value);assert.strictEqual(parentValue.length,originalLength-1+count);move();if(count===0){delete this.value;delete parentCache[this.name];this.__childCache=null}else{assert.strictEqual(parentValue[this.name],replacement);if(this.value!==replacement){this.value=replacement;this.__childCache=null}for(i=0;i<count;++i){results.push(this.parentPath.get(this.name+i))}assert.strictEqual(results[0],this)}}else if(count===1){if(this.value!==replacement){this.__childCache=null}this.value=parentValue[this.name]=replacement;results.push(this)}else if(count===0){delete parentValue[this.name];delete this.value;this.__childCache=null}else{assert.ok(false,"Could not replace path")}return results};module.exports=Path},{"./types":118,assert:121}],116:[function(require,module,exports){var assert=require("assert");var types=require("./types");var Type=types.Type;var namedTypes=types.namedTypes;var Node=namedTypes.Node;var Expression=namedTypes.Expression;var isArray=types.builtInTypes.array;var hasOwn=Object.prototype.hasOwnProperty;var b=types.builders;function Scope(path,parentScope){assert.ok(this instanceof Scope);assert.ok(path instanceof require("./node-path"));ScopeType.assert(path.value);var depth;if(parentScope){assert.ok(parentScope instanceof Scope);depth=parentScope.depth+1}else{parentScope=null;depth=0}Object.defineProperties(this,{path:{value:path},node:{value:path.value},isGlobal:{value:!parentScope,enumerable:true},depth:{value:depth},parent:{value:parentScope},bindings:{value:{}}})}var scopeTypes=[namedTypes.Program,namedTypes.Function,namedTypes.CatchClause];var ScopeType=Type.or.apply(Type,scopeTypes);Scope.isEstablishedBy=function(node){return ScopeType.check(node)};var Sp=Scope.prototype;Sp.didScan=false;Sp.declares=function(name){this.scan();return hasOwn.call(this.bindings,name)};Sp.declareTemporary=function(prefix){if(prefix){assert.ok(/^[a-z$_]/i.test(prefix),prefix)}else{prefix="t$"}prefix+=this.depth.toString(36)+"$";this.scan();var index=0;while(this.declares(prefix+index)){++index}var name=prefix+index;return this.bindings[name]=types.builders.identifier(name)};Sp.injectTemporary=function(identifier,init){identifier||(identifier=this.declareTemporary());var bodyPath=this.path.get("body");if(namedTypes.BlockStatement.check(bodyPath.value)){bodyPath=bodyPath.get("body")}bodyPath.unshift(b.variableDeclaration("var",[b.variableDeclarator(identifier,init||null)]));return identifier};Sp.scan=function(force){if(force||!this.didScan){for(var name in this.bindings){delete this.bindings[name]}scanScope(this.path,this.bindings);this.didScan=true}};Sp.getBindings=function(){this.scan();return this.bindings};function scanScope(path,bindings){var node=path.value;ScopeType.assert(node);if(namedTypes.CatchClause.check(node)){addPattern(path.get("param"),bindings)}else{recursiveScanScope(path,bindings)}}function recursiveScanScope(path,bindings){var node=path.value;if(path.parent&&namedTypes.FunctionExpression.check(path.parent.node)&&path.parent.node.id){addPattern(path.parent.get("id"),bindings)}if(!node){}else if(isArray.check(node)){path.each(function(childPath){recursiveScanChild(childPath,bindings)})}else if(namedTypes.Function.check(node)){path.get("params").each(function(paramPath){addPattern(paramPath,bindings)});recursiveScanChild(path.get("body"),bindings)}else if(namedTypes.VariableDeclarator.check(node)){addPattern(path.get("id"),bindings);recursiveScanChild(path.get("init"),bindings)}else if(node.type==="ImportSpecifier"||node.type==="ImportNamespaceSpecifier"||node.type==="ImportDefaultSpecifier"){addPattern(node.name?path.get("name"):path.get("id"),bindings)}else if(Node.check(node)&&!Expression.check(node)){types.eachField(node,function(name,child){var childPath=path.get(name);assert.strictEqual(childPath.value,child);recursiveScanChild(childPath,bindings)})}}function recursiveScanChild(path,bindings){var node=path.value;if(!node||Expression.check(node)){}else if(namedTypes.FunctionDeclaration.check(node)){addPattern(path.get("id"),bindings)}else if(namedTypes.ClassDeclaration&&namedTypes.ClassDeclaration.check(node)){addPattern(path.get("id"),bindings)}else if(ScopeType.check(node)){if(namedTypes.CatchClause.check(node)){var catchParamName=node.param.name;var hadBinding=hasOwn.call(bindings,catchParamName);recursiveScanScope(path.get("body"),bindings);if(!hadBinding){delete bindings[catchParamName]}}}else{recursiveScanScope(path,bindings)}}function addPattern(patternPath,bindings){var pattern=patternPath.value;namedTypes.Pattern.assert(pattern);if(namedTypes.Identifier.check(pattern)){if(hasOwn.call(bindings,pattern.name)){bindings[pattern.name].push(patternPath)}else{bindings[pattern.name]=[patternPath]}}else if(namedTypes.SpreadElement&&namedTypes.SpreadElement.check(pattern)){addPattern(patternPath.get("argument"),bindings)}}Sp.lookup=function(name){for(var scope=this;scope;scope=scope.parent)if(scope.declares(name))break;return scope};Sp.getGlobalScope=function(){var scope=this;while(!scope.isGlobal)scope=scope.parent;return scope};module.exports=Scope},{"./node-path":113,"./types":118,assert:121}],117:[function(require,module,exports){var types=require("../lib/types");var Type=types.Type;var builtin=types.builtInTypes;var isNumber=builtin.number;exports.geq=function(than){return new Type(function(value){return isNumber.check(value)&&value>=than},isNumber+" >= "+than)};exports.defaults={"null":function(){return null},emptyArray:function(){return[]},"false":function(){return false},"true":function(){return true},undefined:function(){}};var naiveIsPrimitive=Type.or(builtin.string,builtin.number,builtin.boolean,builtin.null,builtin.undefined);exports.isPrimitive=new Type(function(value){if(value===null)return true;var type=typeof value;return!(type==="object"||type==="function")},naiveIsPrimitive.toString())},{"../lib/types":118}],118:[function(require,module,exports){var assert=require("assert");var Ap=Array.prototype;var slice=Ap.slice;var map=Ap.map;var each=Ap.forEach;var Op=Object.prototype;var objToStr=Op.toString;var funObjStr=objToStr.call(function(){});var strObjStr=objToStr.call("");var hasOwn=Op.hasOwnProperty;function Type(check,name){var self=this;assert.ok(self instanceof Type,self);assert.strictEqual(objToStr.call(check),funObjStr,check+" is not a function");var nameObjStr=objToStr.call(name);assert.ok(nameObjStr===funObjStr||nameObjStr===strObjStr,name+" is neither a function nor a string");Object.defineProperties(self,{name:{value:name},check:{value:function(value,deep){var result=check.call(self,value,deep);if(!result&&deep&&objToStr.call(deep)===funObjStr)deep(self,value);return result}}})}var Tp=Type.prototype;exports.Type=Type;Tp.assert=function(value,deep){if(!this.check(value,deep)){var str=shallowStringify(value);assert.ok(false,str+" does not match type "+this);return false}return true};function shallowStringify(value){if(isObject.check(value))return"{"+Object.keys(value).map(function(key){return key+": "+value[key]}).join(", ")+"}";if(isArray.check(value))return"["+value.map(shallowStringify).join(", ")+"]";return JSON.stringify(value)}Tp.toString=function(){var name=this.name;if(isString.check(name))return name;if(isFunction.check(name))return name.call(this)+"";return name+" type"};var builtInTypes={};exports.builtInTypes=builtInTypes;function defBuiltInType(example,name){var objStr=objToStr.call(example);Object.defineProperty(builtInTypes,name,{enumerable:true,value:new Type(function(value){return objToStr.call(value)===objStr},name)});return builtInTypes[name]}var isString=defBuiltInType("","string");var isFunction=defBuiltInType(function(){},"function");var isArray=defBuiltInType([],"array");var isObject=defBuiltInType({},"object");var isRegExp=defBuiltInType(/./,"RegExp");var isDate=defBuiltInType(new Date,"Date");var isNumber=defBuiltInType(3,"number");var isBoolean=defBuiltInType(true,"boolean");var isNull=defBuiltInType(null,"null");var isUndefined=defBuiltInType(void 0,"undefined");function toType(from,name){if(from instanceof Type)return from;if(from instanceof Def)return from.type;if(isArray.check(from))return Type.fromArray(from);if(isObject.check(from))return Type.fromObject(from);if(isFunction.check(from))return new Type(from,name);return new Type(function(value){return value===from},isUndefined.check(name)?function(){return from+""}:name)}Type.or=function(){var types=[];var len=arguments.length;for(var i=0;i<len;++i)types.push(toType(arguments[i]));return new Type(function(value,deep){for(var i=0;i<len;++i)if(types[i].check(value,deep))return true;return false},function(){return types.join(" | ")})};Type.fromArray=function(arr){assert.ok(isArray.check(arr));assert.strictEqual(arr.length,1,"only one element type is permitted for typed arrays");return toType(arr[0]).arrayOf()};Tp.arrayOf=function(){var elemType=this;return new Type(function(value,deep){return isArray.check(value)&&value.every(function(elem){return elemType.check(elem,deep)})},function(){return"["+elemType+"]"})};Type.fromObject=function(obj){var fields=Object.keys(obj).map(function(name){return new Field(name,obj[name])});return new Type(function(value,deep){return isObject.check(value)&&fields.every(function(field){return field.type.check(value[field.name],deep)})},function(){return"{ "+fields.join(", ")+" }"})};function Field(name,type,defaultFn,hidden){var self=this;assert.ok(self instanceof Field);isString.assert(name);type=toType(type);var properties={name:{value:name},type:{value:type},hidden:{value:!!hidden}};if(isFunction.check(defaultFn)){properties.defaultFn={value:defaultFn}}Object.defineProperties(self,properties)}var Fp=Field.prototype;Fp.toString=function(){return JSON.stringify(this.name)+": "+this.type};Fp.getValue=function(obj){var value=obj[this.name];if(!isUndefined.check(value))return value;if(this.defaultFn)value=this.defaultFn.call(obj);return value};Type.def=function(typeName){isString.assert(typeName);return hasOwn.call(defCache,typeName)?defCache[typeName]:defCache[typeName]=new Def(typeName)};var defCache=Object.create(null);function Def(typeName){var self=this;assert.ok(self instanceof Def);Object.defineProperties(self,{typeName:{value:typeName},baseNames:{value:[]},ownFields:{value:Object.create(null)},allSupertypes:{value:Object.create(null)},supertypeList:{value:[]},allFields:{value:Object.create(null)},fieldNames:{value:[]},type:{value:new Type(function(value,deep){return self.check(value,deep)},typeName)}})}Def.fromValue=function(value){if(value&&typeof value==="object"){var type=value.type;if(typeof type==="string"&&hasOwn.call(defCache,type)){var d=defCache[type];if(d.finalized){return d}}}return null};var Dp=Def.prototype;Dp.isSupertypeOf=function(that){if(that instanceof Def){assert.strictEqual(this.finalized,true);assert.strictEqual(that.finalized,true);return hasOwn.call(that.allSupertypes,this.typeName)}else{assert.ok(false,that+" is not a Def")}};exports.getSupertypeNames=function(typeName){assert.ok(hasOwn.call(defCache,typeName));var d=defCache[typeName];assert.strictEqual(d.finalized,true);return d.supertypeList.slice(1)};exports.computeSupertypeLookupTable=function(candidates){var table={};var typeNames=Object.keys(defCache);var typeNameCount=typeNames.length;for(var i=0;i<typeNameCount;++i){var typeName=typeNames[i];var d=defCache[typeName];assert.strictEqual(d.finalized,true);for(var j=0;j<d.supertypeList.length;++j){var superTypeName=d.supertypeList[j];if(hasOwn.call(candidates,superTypeName)){table[typeName]=superTypeName;break}}}return table};Dp.checkAllFields=function(value,deep){var allFields=this.allFields;assert.strictEqual(this.finalized,true);function checkFieldByName(name){var field=allFields[name];var type=field.type;var child=field.getValue(value);return type.check(child,deep)}return isObject.check(value)&&Object.keys(allFields).every(checkFieldByName)};Dp.check=function(value,deep){assert.strictEqual(this.finalized,true,"prematurely checking unfinalized type "+this.typeName);if(!isObject.check(value))return false;var vDef=Def.fromValue(value);if(!vDef){if(this.typeName==="SourceLocation"||this.typeName==="Position"){return this.checkAllFields(value,deep)}return false}if(deep&&vDef===this)return this.checkAllFields(value,deep);if(!this.isSupertypeOf(vDef))return false;if(!deep)return true;return vDef.checkAllFields(value,deep)&&this.checkAllFields(value,false)};Dp.bases=function(){var bases=this.baseNames;assert.strictEqual(this.finalized,false);each.call(arguments,function(baseName){isString.assert(baseName);if(bases.indexOf(baseName)<0)bases.push(baseName)});return this};Object.defineProperty(Dp,"buildable",{value:false});var builders={};exports.builders=builders;var nodePrototype={};exports.defineMethod=function(name,func){var old=nodePrototype[name];if(isUndefined.check(func)){delete nodePrototype[name]}else{isFunction.assert(func);Object.defineProperty(nodePrototype,name,{enumerable:true,configurable:true,value:func})}return old};Dp.build=function(){var self=this;Object.defineProperty(self,"buildParams",{value:slice.call(arguments),writable:false,enumerable:false,configurable:true});assert.strictEqual(self.finalized,false);
isString.arrayOf().assert(self.buildParams);if(self.buildable){return self}self.field("type",self.typeName,function(){return self.typeName});Object.defineProperty(self,"buildable",{value:true});Object.defineProperty(builders,getBuilderName(self.typeName),{enumerable:true,value:function(){var args=arguments;var argc=args.length;var built=Object.create(nodePrototype);assert.ok(self.finalized,"attempting to instantiate unfinalized type "+self.typeName);function add(param,i){if(hasOwn.call(built,param))return;var all=self.allFields;assert.ok(hasOwn.call(all,param),param);var field=all[param];var type=field.type;var value;if(isNumber.check(i)&&i<argc){value=args[i]}else if(field.defaultFn){value=field.defaultFn.call(built)}else{var message="no value or default function given for field "+JSON.stringify(param)+" of "+self.typeName+"("+self.buildParams.map(function(name){return all[name]}).join(", ")+")";assert.ok(false,message)}if(!type.check(value)){assert.ok(false,shallowStringify(value)+" does not match field "+field+" of type "+self.typeName)}built[param]=value}self.buildParams.forEach(function(param,i){add(param,i)});Object.keys(self.allFields).forEach(function(param){add(param)});assert.strictEqual(built.type,self.typeName);return built}});return self};function getBuilderName(typeName){return typeName.replace(/^[A-Z]+/,function(upperCasePrefix){var len=upperCasePrefix.length;switch(len){case 0:return"";case 1:return upperCasePrefix.toLowerCase();default:return upperCasePrefix.slice(0,len-1).toLowerCase()+upperCasePrefix.charAt(len-1)}})}Dp.field=function(name,type,defaultFn,hidden){assert.strictEqual(this.finalized,false);this.ownFields[name]=new Field(name,type,defaultFn,hidden);return this};var namedTypes={};exports.namedTypes=namedTypes;function getFieldNames(object){var d=Def.fromValue(object);if(d){return d.fieldNames.slice(0)}if("type"in object){assert.ok(false,"did not recognize object of type "+JSON.stringify(object.type))}return Object.keys(object)}exports.getFieldNames=getFieldNames;function getFieldValue(object,fieldName){var d=Def.fromValue(object);if(d){var field=d.allFields[fieldName];if(field){return field.getValue(object)}}return object[fieldName]}exports.getFieldValue=getFieldValue;exports.eachField=function(object,callback,context){getFieldNames(object).forEach(function(name){callback.call(this,name,getFieldValue(object,name))},context)};exports.someField=function(object,callback,context){return getFieldNames(object).some(function(name){return callback.call(this,name,getFieldValue(object,name))},context)};Object.defineProperty(Dp,"finalized",{value:false});Dp.finalize=function(){if(!this.finalized){var allFields=this.allFields;var allSupertypes=this.allSupertypes;this.baseNames.forEach(function(name){var def=defCache[name];def.finalize();extend(allFields,def.allFields);extend(allSupertypes,def.allSupertypes)});extend(allFields,this.ownFields);allSupertypes[this.typeName]=this;this.fieldNames.length=0;for(var fieldName in allFields){if(hasOwn.call(allFields,fieldName)&&!allFields[fieldName].hidden){this.fieldNames.push(fieldName)}}Object.defineProperty(namedTypes,this.typeName,{enumerable:true,value:this.type});Object.defineProperty(this,"finalized",{value:true});populateSupertypeList(this.typeName,this.supertypeList)}};function populateSupertypeList(typeName,list){list.length=0;list.push(typeName);var lastSeen=Object.create(null);for(var pos=0;pos<list.length;++pos){typeName=list[pos];var d=defCache[typeName];assert.strictEqual(d.finalized,true);if(hasOwn.call(lastSeen,typeName)){delete list[lastSeen[typeName]]}lastSeen[typeName]=pos;list.push.apply(list,d.baseNames)}for(var to=0,from=to,len=list.length;from<len;++from){if(hasOwn.call(list,from)){list[to++]=list[from]}}list.length=to}function extend(into,from){Object.keys(from).forEach(function(name){into[name]=from[name]});return into}exports.finalize=function(){Object.keys(defCache).forEach(function(name){defCache[name].finalize()})}},{assert:121}],119:[function(require,module,exports){var types=require("./lib/types");require("./def/core");require("./def/es6");require("./def/es7");require("./def/mozilla");require("./def/e4x");require("./def/fb-harmony");types.finalize();exports.Type=types.Type;exports.builtInTypes=types.builtInTypes;exports.namedTypes=types.namedTypes;exports.builders=types.builders;exports.defineMethod=types.defineMethod;exports.getFieldNames=types.getFieldNames;exports.getFieldValue=types.getFieldValue;exports.eachField=types.eachField;exports.someField=types.someField;exports.getSupertypeNames=types.getSupertypeNames;exports.astNodesAreEquivalent=require("./lib/equiv");exports.finalize=types.finalize;exports.NodePath=require("./lib/node-path");exports.PathVisitor=require("./lib/path-visitor");exports.visit=exports.PathVisitor.visit},{"./def/core":106,"./def/e4x":107,"./def/es6":108,"./def/es7":109,"./def/fb-harmony":110,"./def/mozilla":111,"./lib/equiv":112,"./lib/node-path":113,"./lib/path-visitor":114,"./lib/types":118}],120:[function(require,module,exports){},{}],121:[function(require,module,exports){var util=require("util/");var pSlice=Array.prototype.slice;var hasOwn=Object.prototype.hasOwnProperty;var assert=module.exports=ok;assert.AssertionError=function AssertionError(options){this.name="AssertionError";this.actual=options.actual;this.expected=options.expected;this.operator=options.operator;if(options.message){this.message=options.message;this.generatedMessage=false}else{this.message=getMessage(this);this.generatedMessage=true}var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace){Error.captureStackTrace(this,stackStartFunction)}else{var err=new Error;if(err.stack){var out=err.stack;var fn_name=stackStartFunction.name;var idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}};util.inherits(assert.AssertionError,Error);function replacer(key,value){if(util.isUndefined(value)){return""+value}if(util.isNumber(value)&&!isFinite(value)){return value.toString()}if(util.isFunction(value)||util.isRegExp(value)){return value.toString()}return value}function truncate(s,n){if(util.isString(s)){return s.length<n?s:s.slice(0,n)}else{return s}}function getMessage(self){return truncate(JSON.stringify(self.actual,replacer),128)+" "+self.operator+" "+truncate(JSON.stringify(self.expected,replacer),128)}function fail(actual,expected,message,operator,stackStartFunction){throw new assert.AssertionError({message:message,actual:actual,expected:expected,operator:operator,stackStartFunction:stackStartFunction})}assert.fail=fail;function ok(value,message){if(!value)fail(value,true,message,"==",assert.ok)}assert.ok=ok;assert.equal=function equal(actual,expected,message){if(actual!=expected)fail(actual,expected,message,"==",assert.equal)};assert.notEqual=function notEqual(actual,expected,message){if(actual==expected){fail(actual,expected,message,"!=",assert.notEqual)}};assert.deepEqual=function deepEqual(actual,expected,message){if(!_deepEqual(actual,expected)){fail(actual,expected,message,"deepEqual",assert.deepEqual)}};function _deepEqual(actual,expected){if(actual===expected){return true}else if(util.isBuffer(actual)&&util.isBuffer(expected)){if(actual.length!=expected.length)return false;for(var i=0;i<actual.length;i++){if(actual[i]!==expected[i])return false}return true}else if(util.isDate(actual)&&util.isDate(expected)){return actual.getTime()===expected.getTime()}else if(util.isRegExp(actual)&&util.isRegExp(expected)){return actual.source===expected.source&&actual.global===expected.global&&actual.multiline===expected.multiline&&actual.lastIndex===expected.lastIndex&&actual.ignoreCase===expected.ignoreCase}else if(!util.isObject(actual)&&!util.isObject(expected)){return actual==expected}else{return objEquiv(actual,expected)}}function isArguments(object){return Object.prototype.toString.call(object)=="[object Arguments]"}function objEquiv(a,b){if(util.isNullOrUndefined(a)||util.isNullOrUndefined(b))return false;if(a.prototype!==b.prototype)return false;if(util.isPrimitive(a)||util.isPrimitive(b)){return a===b}var aIsArgs=isArguments(a),bIsArgs=isArguments(b);if(aIsArgs&&!bIsArgs||!aIsArgs&&bIsArgs)return false;if(aIsArgs){a=pSlice.call(a);b=pSlice.call(b);return _deepEqual(a,b)}var ka=objectKeys(a),kb=objectKeys(b),key,i;if(ka.length!=kb.length)return false;ka.sort();kb.sort();for(i=ka.length-1;i>=0;i--){if(ka[i]!=kb[i])return false}for(i=ka.length-1;i>=0;i--){key=ka[i];if(!_deepEqual(a[key],b[key]))return false}return true}assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(_deepEqual(actual,expected)){fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)}};assert.strictEqual=function strictEqual(actual,expected,message){if(actual!==expected){fail(actual,expected,message,"===",assert.strictEqual)}};assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(actual===expected){fail(actual,expected,message,"!==",assert.notStrictEqual)}};function expectedException(actual,expected){if(!actual||!expected){return false}if(Object.prototype.toString.call(expected)=="[object RegExp]"){return expected.test(actual)}else if(actual instanceof expected){return true}else if(expected.call({},actual)===true){return true}return false}function _throws(shouldThrow,block,expected,message){var actual;if(util.isString(expected)){message=expected;expected=null}try{block()}catch(e){actual=e}message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:".");if(shouldThrow&&!actual){fail(actual,expected,"Missing expected exception"+message)}if(!shouldThrow&&expectedException(actual,expected)){fail(actual,expected,"Got unwanted exception"+message)}if(shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual){throw actual}}assert.throws=function(block,error,message){_throws.apply(this,[true].concat(pSlice.call(arguments)))};assert.doesNotThrow=function(block,message){_throws.apply(this,[false].concat(pSlice.call(arguments)))};assert.ifError=function(err){if(err){throw err}};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){if(hasOwn.call(obj,key))keys.push(key)}return keys}},{"util/":145}],122:[function(require,module,exports){var base64=require("base64-js");var ieee754=require("ieee754");var isArray=require("is-array");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;Buffer.poolSize=8192;var kMaxLength=1073741823;var rootParent={};Buffer.TYPED_ARRAY_SUPPORT=function(){try{var buf=new ArrayBuffer(0);var arr=new Uint8Array(buf);arr.foo=function(){return 42};return 42===arr.foo()&&typeof arr.subarray==="function"&&new Uint8Array(1).subarray(1,1).byteLength===0}catch(e){return false}}();function Buffer(subject,encoding,noZero){if(!(this instanceof Buffer))return new Buffer(subject,encoding,noZero);var type=typeof subject;var length;if(type==="number")length=subject>0?subject>>>0:0;else if(type==="string"){length=Buffer.byteLength(subject,encoding)}else if(type==="object"&&subject!==null){if(subject.type==="Buffer"&&isArray(subject.data))subject=subject.data;length=+subject.length>0?Math.floor(+subject.length):0}else throw new TypeError("must start with number, buffer, array or string");if(length>kMaxLength)throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength.toString(16)+" bytes");var buf;if(Buffer.TYPED_ARRAY_SUPPORT){buf=Buffer._augment(new Uint8Array(length))}else{buf=this;buf.length=length;buf._isBuffer=true}var i;if(Buffer.TYPED_ARRAY_SUPPORT&&typeof subject.byteLength==="number"){buf._set(subject)}else if(isArrayish(subject)){if(Buffer.isBuffer(subject)){for(i=0;i<length;i++)buf[i]=subject.readUInt8(i)}else{for(i=0;i<length;i++)buf[i]=(subject[i]%256+256)%256}}else if(type==="string"){buf.write(subject,0,encoding)}else if(type==="number"&&!Buffer.TYPED_ARRAY_SUPPORT&&!noZero){for(i=0;i<length;i++){buf[i]=0}}if(length>0&&length<=Buffer.poolSize)buf.parent=rootParent;return buf}function SlowBuffer(subject,encoding,noZero){if(!(this instanceof SlowBuffer))return new SlowBuffer(subject,encoding,noZero);var buf=new Buffer(subject,encoding,noZero);delete buf.parent;return buf}Buffer.isBuffer=function(b){return!!(b!=null&&b._isBuffer)};Buffer.compare=function(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("Arguments must be Buffers");var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i<len&&a[i]===b[i];i++){}if(i!==len){x=a[i];y=b[i]}if(x<y)return-1;if(y<x)return 1;return 0};Buffer.isEncoding=function(encoding){switch(String(encoding).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return true;default:return false}};Buffer.concat=function(list,totalLength){if(!isArray(list))throw new TypeError("Usage: Buffer.concat(list[, length])");if(list.length===0){return new Buffer(0)}else if(list.length===1){return list[0]}var i;if(totalLength===undefined){totalLength=0;for(i=0;i<list.length;i++){totalLength+=list[i].length}}var buf=new Buffer(totalLength);var pos=0;for(i=0;i<list.length;i++){var item=list[i];item.copy(buf,pos);pos+=item.length}return buf};Buffer.byteLength=function(str,encoding){var ret;str=str+"";switch(encoding||"utf8"){case"ascii":case"binary":case"raw":ret=str.length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=str.length*2;break;case"hex":ret=str.length>>>1;break;case"utf8":case"utf-8":ret=utf8ToBytes(str).length;break;case"base64":ret=base64ToBytes(str).length;break;default:ret=str.length}return ret};Buffer.prototype.length=undefined;Buffer.prototype.parent=undefined;Buffer.prototype.toString=function(encoding,start,end){var loweredCase=false;start=start>>>0;end=end===undefined||end===Infinity?this.length:end>>>0;if(!encoding)encoding="utf8";if(start<0)start=0;if(end>this.length)end=this.length;if(end<=start)return"";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"binary":return binarySlice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}};Buffer.prototype.equals=function(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return Buffer.compare(this,b)===0};Buffer.prototype.inspect=function(){var str="";var max=exports.INSPECT_MAX_BYTES;if(this.length>0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return"<Buffer "+str+">"};Buffer.prototype.compare=function(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return Buffer.compare(this,b)};Buffer.prototype.get=function(offset){console.log(".get() is deprecated. Access using array indexes instead.");return this.readUInt8(offset)};Buffer.prototype.set=function(v,offset){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(v,offset)};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new Error("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i<length;i++){var byte=parseInt(string.substr(i*2,2),16);if(isNaN(byte))throw new Error("Invalid hex string");buf[offset+i]=byte}return i}function utf8Write(buf,string,offset,length){var charsWritten=blitBuffer(utf8ToBytes(string,buf.length-offset),buf,offset,length);return charsWritten}function asciiWrite(buf,string,offset,length){var charsWritten=blitBuffer(asciiToBytes(string),buf,offset,length);return charsWritten}function binaryWrite(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){var charsWritten=blitBuffer(base64ToBytes(string),buf,offset,length);return charsWritten}function utf16leWrite(buf,string,offset,length){var charsWritten=blitBuffer(utf16leToBytes(string,buf.length-offset),buf,offset,length,2);return charsWritten}Buffer.prototype.write=function(string,offset,length,encoding){if(isFinite(offset)){if(!isFinite(length)){encoding=length;length=undefined}}else{var swap=encoding;encoding=offset;offset=length;length=swap}offset=Number(offset)||0;if(length<0||offset<0||offset>this.length)throw new RangeError("attempt to write outside buffer bounds");var remaining=this.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}encoding=String(encoding||"utf8").toLowerCase();var ret;switch(encoding){case"hex":ret=hexWrite(this,string,offset,length);break;case"utf8":case"utf-8":ret=utf8Write(this,string,offset,length);break;case"ascii":ret=asciiWrite(this,string,offset,length);break;case"binary":ret=binaryWrite(this,string,offset,length);break;case"base64":ret=base64Write(this,string,offset,length);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=utf16leWrite(this,string,offset,length);break;default:throw new TypeError("Unknown encoding: "+encoding)}return ret};Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){var res="";var tmp="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){if(buf[i]<=127){res+=decodeUtf8Char(tmp)+String.fromCharCode(buf[i]);tmp=""}else{tmp+="%"+buf[i].toString(16)}}return res+decodeUtf8Char(tmp)}function asciiSlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){ret+=String.fromCharCode(buf[i]&127)}return ret}function binarySlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){ret+=String.fromCharCode(buf[i])}return ret}function hexSlice(buf,start,end){var len=buf.length;if(!start||start<0)start=0;if(!end||end<0||end>len)end=len;var out="";for(var i=start;i<end;i++){out+=toHex(buf[i])}return out}function utf16leSlice(buf,start,end){var bytes=buf.slice(start,end);var res="";for(var i=0;i<bytes.length;i+=2){res+=String.fromCharCode(bytes[i]+bytes[i+1]*256)}return res}Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start;end=end===undefined?len:~~end;if(start<0){start+=len;if(start<0)start=0}else if(start>len){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(end<start)end=start;var newBuf;if(Buffer.TYPED_ARRAY_SUPPORT){newBuf=Buffer._augment(this.subarray(start,end))}else{var sliceLen=end-start;newBuf=new Buffer(sliceLen,undefined,true);for(var i=0;i<sliceLen;i++){newBuf[i]=this[i+start]}}if(newBuf.length)newBuf.parent=this.parent||this;return newBuf};function checkOffset(offset,ext,length){if(offset%1!==0||offset<0)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUIntLE=function(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=256))val+=this[offset+i]*mul;return val};Buffer.prototype.readUIntBE=function(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset+--byteLength];var mul=1;while(byteLength>0&&(mul*=256))val+=this[offset+--byteLength]*mul;return val};Buffer.prototype.readUInt8=function(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i<byteLength&&(mul*=256))val+=this[offset+i]*mul;mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256))val+=this[offset+--i]*mul;mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError("buffer must be a Buffer instance");if(value>max||value<min)throw new RangeError("value is out of bounds");if(offset+ext>buf.length)throw new RangeError("index out of range")}Buffer.prototype.writeUIntLE=function(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength),0);var mul=1;var i=0;this[offset]=value&255;while(++i<byteLength&&(mul*=256))this[offset+i]=value/mul>>>0&255;return offset+byteLength};Buffer.prototype.writeUIntBE=function(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength),0);var i=byteLength-1;var mul=1;this[offset+i]=value&255;while(--i>=0&&(mul*=256))this[offset+i]=value/mul>>>0&255;return offset+byteLength};Buffer.prototype.writeUInt8=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i<j;i++){buf[offset+i]=(value&255<<8*(littleEndian?i:1-i))>>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8}else objectWriteUInt16(this,value,offset,true);return offset+2};Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value}else objectWriteUInt16(this,value,offset,false);return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i<j;i++){buf[offset+i]=value>>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value}else objectWriteUInt32(this,value,offset,true);return offset+4};Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value}else objectWriteUInt32(this,value,offset,false);return offset+4};Buffer.prototype.writeIntLE=function(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength-1)-1,-Math.pow(2,8*byteLength-1))}var i=0;var mul=1;var sub=value<0?1:0;this[offset]=value&255;while(++i<byteLength&&(mul*=256))this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength};Buffer.prototype.writeIntBE=function(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkInt(this,value,offset,byteLength,Math.pow(2,8*byteLength-1)-1,-Math.pow(2,8*byteLength-1))}var i=byteLength-1;var mul=1;var sub=value<0?1:0;this[offset+i]=value&255;while(--i>=0&&(mul*=256))this[offset+i]=(value/mul>>0)-sub&255;return offset+byteLength};Buffer.prototype.writeInt8=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+value+1;this[offset]=value;return offset+1};Buffer.prototype.writeInt16LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8}else objectWriteUInt16(this,value,offset,true);return offset+2};Buffer.prototype.writeInt16BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value}else objectWriteUInt16(this,value,offset,false);return offset+2};Buffer.prototype.writeInt32LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else objectWriteUInt32(this,value,offset,true);return offset+4};Buffer.prototype.writeInt32BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value}else objectWriteUInt32(this,value,offset,false);return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(value>max||value<min)throw new RangeError("value is out of bounds");if(offset+ext>buf.length)throw new RangeError("index out of range");if(offset<0)throw new RangeError("index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert)checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38);ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert)checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308);ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function(target,target_start,start,end){var source=this;if(!start)start=0;if(!end&&end!==0)end=this.length;if(target_start>=target.length)target_start=target.length;if(!target_start)target_start=0;if(end>0&&end<start)end=start;if(end===start)return 0;if(target.length===0||source.length===0)return 0;if(target_start<0)throw new RangeError("targetStart out of bounds");if(start<0||start>=source.length)throw new RangeError("sourceStart out of bounds");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-target_start<end-start)end=target.length-target_start+start;var len=end-start;if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){for(var i=0;i<len;i++){target[i+target_start]=this[i+start]}}else{target._set(this.subarray(start,start+len),target_start)}return len};Buffer.prototype.fill=function(value,start,end){if(!value)value=0;if(!start)start=0;if(!end)end=this.length;if(end<start)throw new RangeError("end < start");if(end===start)return;if(this.length===0)return;if(start<0||start>=this.length)throw new RangeError("start out of bounds");if(end<0||end>this.length)throw new RangeError("end out of bounds");var i;if(typeof value==="number"){for(i=start;i<end;i++){this[i]=value}}else{var bytes=utf8ToBytes(value.toString());var len=bytes.length;for(i=start;i<end;i++){this[i]=bytes[i%len]}}return this};Buffer.prototype.toArrayBuffer=function(){if(typeof Uint8Array!=="undefined"){if(Buffer.TYPED_ARRAY_SUPPORT){return new Buffer(this).buffer}else{var buf=new Uint8Array(this.length);for(var i=0,len=buf.length;i<len;i+=1){buf[i]=this[i]}return buf.buffer}}else{throw new TypeError("Buffer.toArrayBuffer not supported in this browser")}};var BP=Buffer.prototype;Buffer._augment=function(arr){arr.constructor=Buffer;arr._isBuffer=true;arr._get=arr.get;arr._set=arr.set;arr.get=BP.get;arr.set=BP.set;arr.write=BP.write;arr.toString=BP.toString;arr.toLocaleString=BP.toString;arr.toJSON=BP.toJSON;arr.equals=BP.equals;arr.compare=BP.compare;arr.copy=BP.copy;arr.slice=BP.slice;arr.readUIntLE=BP.readUIntLE;arr.readUIntBE=BP.readUIntBE;arr.readUInt8=BP.readUInt8;arr.readUInt16LE=BP.readUInt16LE;arr.readUInt16BE=BP.readUInt16BE;arr.readUInt32LE=BP.readUInt32LE;arr.readUInt32BE=BP.readUInt32BE;arr.readIntLE=BP.readIntLE;arr.readIntBE=BP.readIntBE;arr.readInt8=BP.readInt8;arr.readInt16LE=BP.readInt16LE;arr.readInt16BE=BP.readInt16BE;arr.readInt32LE=BP.readInt32LE;arr.readInt32BE=BP.readInt32BE;arr.readFloatLE=BP.readFloatLE;arr.readFloatBE=BP.readFloatBE;arr.readDoubleLE=BP.readDoubleLE;arr.readDoubleBE=BP.readDoubleBE;arr.writeUInt8=BP.writeUInt8;arr.writeUIntLE=BP.writeUIntLE;arr.writeUIntBE=BP.writeUIntBE;arr.writeUInt16LE=BP.writeUInt16LE;arr.writeUInt16BE=BP.writeUInt16BE;arr.writeUInt32LE=BP.writeUInt32LE;arr.writeUInt32BE=BP.writeUInt32BE;arr.writeIntLE=BP.writeIntLE;arr.writeIntBE=BP.writeIntBE;arr.writeInt8=BP.writeInt8;arr.writeInt16LE=BP.writeInt16LE; |
data_service.py | import iu.i524.S17IRP013.ncdc.weather_services as Services
import iu.i524.S17IRP013.dao.stations_dao as stations
import iu.i524.S17IRP013.dao.weather_dao as weather
import iu.i524.S17IRP013.util.app_util as AppUtil
###############################################################
def load_stations():
limit = 25
offset = 0
nbr_of_records = 0
result = Services.get_stations(offset=offset)
while(result != {}):
nbr_of_records = nbr_of_records + insert_station(result['results'])
offset = offset + limit
result = Services.get_stations(offset=offset)
print str(nbr_of_records) + ' stations loaded successfully !!'
###############################################################
def insert_station(results):
count = 0
for data in results:
cell = stations.get_cell(data)
row_key = str(data['id'])
stations.insert(row_key, cell)
count = count + 1
return count
###############################################################
def load_weather_data():
start_row = ''
st_list = stations.get_station_data(start_row=start_row)
while st_list != {}:
for key, value in st_list.items():
get_weather_data(startDate=value['min_date'], endDate=value['max_date'], stationId=key, station_details=value)
start_row = key
print 'Weather Data loaded till station id = ' + key
st_list = stations.get_station_data(start_row=start_row)
###############################################################
def get_weather_data(station_details, startDate='1968-01-01', endDate='1970-01-01', stationId='GHCND:IN001011001'):
date_range_list = AppUtil.get_year_list(start_date=startDate, end_date=endDate)
for date_range in date_range_list:
limit = 25
offset = 0
result = Services.get_weather_data(startDate=date_range['min_date'], endDate=date_range['max_date'], stationId=stationId, offset=offset)
while(result != {}):
# print result['results']
insert_result(result['results'], station_details) | result = Services.get_weather_data(startDate=date_range['min_date'], endDate=date_range['max_date'], stationId=stationId, offset=offset)
###############################################################
def insert_result(result_list, station_details):
station_id = station_details['station_id']
latitude = station_details['latitude']
longitude = station_details['longitude']
grouped_weather_data = groub_weather_data(result_list)
for key, value in grouped_weather_data.items():
cell = weather.get_cell(value, station_id, latitude, longitude)
if(cell != {}):
weather.insert(key, cell)
###############################################################
def groub_weather_data(result_list):
group_data = dict()
for result in result_list:
year_month = AppUtil.format_date(result['date'], target_format='')
if year_month in group_data.keys():
group_data[year_month].append(result)
else:
data_list = list()
data_list.append(result)
group_data[year_month] = data_list
return group_data | offset = offset + limit |
pool.rs | use std::borrow::Borrow;
use std::collections::VecDeque;
use std::fmt;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::time::Duration as StdDuration;
use crate::time::{Duration, SteadyTime};
use super::super::error::Result as MyResult;
use super::super::error::{DriverError, Error};
use super::GenericConnection;
use super::IsolationLevel;
use super::LocalInfileHandler;
use super::Transaction;
use super::{Conn, Opts, QueryResult, Stmt};
use crate::myc::named_params::parse_named_params;
use crate::myc::row::convert::{from_row, FromRow};
use crate::Params;
use crate::Row;
#[derive(Debug)]
struct InnerPool {
opts: Opts,
pool: VecDeque<Conn>,
}
impl InnerPool {
fn new(min: usize, max: usize, opts: Opts) -> MyResult<InnerPool> {
if min > max || max == 0 {
return Err(Error::DriverError(DriverError::InvalidPoolConstraints));
}
let mut pool = InnerPool {
opts: opts,
pool: VecDeque::with_capacity(max),
};
for _ in 0..min {
pool.new_conn()?;
}
Ok(pool)
}
fn new_conn(&mut self) -> MyResult<()> {
match Conn::new(self.opts.clone()) {
Ok(conn) => {
self.pool.push_back(conn);
Ok(())
}
Err(err) => Err(err),
}
}
}
/// `Pool` serves to provide you with a [`PooledConn`](struct.PooledConn.html)'s.
/// However you can prepare statements directly on `Pool` without
/// invoking [`Pool::get_conn`](struct.Pool.html#method.get_conn).
///
/// `Pool` will hold at least `min` connections and will create as many as `max`
/// connections with possible overhead of one connection per alive thread.
///
/// Example of multithreaded `Pool` usage:
///
/// ```rust
/// use mysql::{Pool, Opts};
/// # use mysql::OptsBuilder;
/// use std::thread;
///
/// fn get_opts() -> Opts {
/// // ...
/// # let user = "root";
/// # let addr = "127.0.0.1";
/// # let pwd: String = ::std::env::var("MYSQL_SERVER_PASS").unwrap_or("password".to_string());
/// # let port: u16 = ::std::env::var("MYSQL_SERVER_PORT").ok()
/// # .map(|my_port| my_port.parse().ok().unwrap_or(3307))
/// # .unwrap_or(3307);
/// # let mut builder = OptsBuilder::default();
/// # builder.user(Some(user))
/// # .pass(Some(pwd))
/// # .ip_or_hostname(Some(addr))
/// # .tcp_port(port);
/// # builder.into()
/// }
///
/// let opts = get_opts();
/// let pool = Pool::new(opts).unwrap();
/// let mut threads = Vec::new();
/// for _ in 0..100 {
/// let pool = pool.clone();
/// threads.push(thread::spawn(move || {
/// let mut result = pool.prep_exec("SELECT 1", ()).unwrap();
/// assert_eq!(result.next().unwrap().unwrap().unwrap(), vec![1.into()]);
/// }));
/// }
/// for t in threads.into_iter() {
/// assert!(t.join().is_ok());
/// }
/// ```
///
/// For more info on how to work with mysql connection please look at
/// [`PooledConn`](struct.PooledConn.html) documentation.
#[derive(Clone)]
pub struct Pool {
inner: Arc<(Mutex<InnerPool>, Condvar)>,
min: Arc<AtomicUsize>,
max: Arc<AtomicUsize>,
count: Arc<AtomicUsize>,
check_health: bool,
use_cache: bool,
}
impl Pool {
/// Will return connection taken from a pool.
///
/// Will verify and fix it via `Conn::ping` and `Conn::reset` if `call_ping` is `true`.
/// Will try to get concrete connection if `id` is `Some(_)`.
/// Will wait til timeout if `timeout_ms` is `Some(_)`
fn _get_conn<T: AsRef<str>>(
&self,
stmt: Option<T>,
timeout_ms: Option<u32>,
call_ping: bool,
) -> MyResult<PooledConn> {
let times = if let Some(timeout_ms) = timeout_ms {
Some((
SteadyTime::now(),
Duration::milliseconds(timeout_ms as i64),
StdDuration::from_millis(timeout_ms as u64),
))
} else {
None
};
let &(ref inner_pool, ref condvar) = &*self.inner;
let conn = if self.use_cache {
if let Some(query) = stmt {
let mut id = None;
let mut pool = inner_pool.lock()?;
for (i, conn) in pool.pool.iter().rev().enumerate() {
if conn.has_stmt(query.as_ref()) {
id = Some(i);
break;
}
}
id.and_then(|id| pool.pool.swap_remove_back(id))
} else {
None
}
} else {
None
};
let mut conn = if let Some(conn) = conn {
conn
} else {
let out_conn;
let mut pool = inner_pool.lock()?;
loop {
if let Some(conn) = pool.pool.pop_front() {
drop(pool);
out_conn = Some(conn);
break;
} else {
if self.count.load(Ordering::Relaxed) < self.max.load(Ordering::Relaxed) {
pool.new_conn()?;
self.count.fetch_add(1, Ordering::SeqCst);
} else {
pool = if let Some((start, timeout, std_timeout)) = times {
if SteadyTime::now() - start > timeout {
return Err(DriverError::Timeout.into());
}
condvar.wait_timeout(pool, std_timeout)?.0
} else {
condvar.wait(pool)?
}
}
}
}
out_conn.unwrap()
};
if call_ping && self.check_health {
if !conn.ping() {
conn.reset()?;
}
}
Ok(PooledConn {
pool: self.clone(),
conn: Some(conn),
})
}
/// Creates new pool with `min = 10` and `max = 100`.
pub fn new<T: Into<Opts>>(opts: T) -> MyResult<Pool> {
Pool::new_manual(10, 100, opts)
}
/// Same as `new` but you can set `min` and `max`.
pub fn new_manual<T: Into<Opts>>(min: usize, max: usize, opts: T) -> MyResult<Pool> {
let pool = InnerPool::new(min, max, opts.into())?;
Ok(Pool {
inner: Arc::new((Mutex::new(pool), Condvar::new())),
min: Arc::new(AtomicUsize::new(min)),
max: Arc::new(AtomicUsize::new(max)),
count: Arc::new(AtomicUsize::new(min)),
use_cache: true,
check_health: true,
})
}
/// A way to turn off searching for cached statement (on by default).
///
/// If turned on, then calls to `Pool::{prepare, prep_exec, first_exec}` will search for cached
/// statement through all connections in the pool. Useless if the value of the `stmt_cache_size`
/// option is 0.
pub fn use_cache(&mut self, use_cache: bool) {
self.use_cache = use_cache;
}
/// A way to turn off connection health check on each call to `get_conn` and `prepare`
/// (`prep_exec` is not affected) (on by default).
pub fn check_health(&mut self, check_health: bool) {
self.check_health = check_health;
}
/// Gives you a [`PooledConn`](struct.PooledConn.html).
///
/// `Pool` will check that connection is alive via
/// [`Conn::ping`](struct.Conn.html#method.ping) and will
/// call [`Conn::reset`](struct.Conn.html#method.reset) if
/// necessary.
pub fn get_conn(&self) -> MyResult<PooledConn> {
self._get_conn(None::<String>, None, true)
}
/// Will try to get connection for a duration of `timeout_ms` milliseconds.
///
/// # Failure
/// This function will return `Error::DriverError(DriverError::Timeout)` if timeout was
/// reached while waiting for new connection to become available.
pub fn try_get_conn(&self, timeout_ms: u32) -> MyResult<PooledConn> {
self._get_conn(None::<String>, Some(timeout_ms), true)
}
fn get_conn_by_stmt<T: AsRef<str>>(&self, query: T, call_ping: bool) -> MyResult<PooledConn> {
self._get_conn(Some(query), None, call_ping)
}
/// Will prepare statement. See [`Conn::prepare`](struct.Conn.html#method.prepare).
///
/// It will try to find connection which has this statement cached.
pub fn prepare<T: AsRef<str>>(&self, query: T) -> MyResult<Stmt<'static>> {
let conn = self.get_conn_by_stmt(query.as_ref(), true)?;
conn.pooled_prepare(query)
}
/// Shortcut for `pool.get_conn()?.prep_exec(..)`. See
/// [`Conn::prep_exec`](struct.Conn.html#method.prep_exec).
///
/// It will try to find connection which has this statement cached.
pub fn prep_exec<A, T>(&self, query: A, params: T) -> MyResult<QueryResult<'static>>
where
A: AsRef<str>,
T: Into<Params>,
{
let conn = self.get_conn_by_stmt(query.as_ref(), false)?;
let params = params.into();
match conn.pooled_prep_exec(query.as_ref(), params.clone()) {
Ok(stmt) => Ok(stmt),
Err(e) => {
if e.is_connectivity_error() {
let conn = self._get_conn(None::<String>, None, true)?;
conn.pooled_prep_exec(query, params)
} else {
Err(e)
}
}
}
}
/// See [`Conn::first_exec`](struct.Conn.html#method.first_exec).
pub fn first_exec<Q, P>(&self, query: Q, params: P) -> MyResult<Option<Row>>
where
Q: AsRef<str>,
P: Into<Params>,
{
self.prep_exec(query, params).and_then(|result| {
for row in result {
return row.map(Some);
}
return Ok(None);
})
}
/// Shortcut for `pool.get_conn()?.start_transaction(..)`.
pub fn start_transaction(
&self,
consistent_snapshot: bool,
isolation_level: Option<IsolationLevel>,
readonly: Option<bool>,
) -> MyResult<Transaction<'static>> {
let conn = self._get_conn(None::<String>, None, false)?;
let result = conn.pooled_start_transaction(consistent_snapshot, isolation_level, readonly);
match result {
Ok(trans) => Ok(trans),
Err(ref e) if e.is_connectivity_error() => {
let conn = self._get_conn(None::<String>, None, true)?;
conn.pooled_start_transaction(consistent_snapshot, isolation_level, readonly)
}
Err(e) => Err(e),
}
}
}
impl fmt::Debug for Pool {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"Pool {{ min: {}, max: {}, count: {} }}",
self.min.load(Ordering::Relaxed),
self.max.load(Ordering::Relaxed),
self.count.load(Ordering::Relaxed)
)
}
}
/// Pooled mysql connection which will return to the pool on `drop`.
///
/// You should prefer using `prepare` or `prep_exec` instead of `query` where possible, except
/// cases when statement has no params and when it has no return values or return values which
/// evaluates to `Value::Bytes`.
///
/// `query` is a part of mysql text protocol, so under the hood you will always receive
/// `Value::Bytes` as a result and `from_value` will need to parse it if you want, for example, `i64`
///
/// ```rust
/// # use mysql::{Pool, Opts, OptsBuilder, from_value, Value};
/// # fn get_opts() -> Opts {
/// # let user = "root";
/// # let addr = "127.0.0.1";
/// # let pwd: String = ::std::env::var("MYSQL_SERVER_PASS").unwrap_or("password".to_string());
/// # let port: u16 = ::std::env::var("MYSQL_SERVER_PORT").ok()
/// # .map(|my_port| my_port.parse().ok().unwrap_or(3307))
/// # .unwrap_or(3307);
/// # let mut builder = OptsBuilder::default();
/// # builder.user(Some(user))
/// # .pass(Some(pwd))
/// # .ip_or_hostname(Some(addr))
/// # .tcp_port(port)
/// # .init(vec!["SET GLOBAL sql_mode = 'TRADITIONAL'"]);
/// # builder.into()
/// # }
/// # let opts = get_opts();
/// # let pool = Pool::new(opts).unwrap();
/// let mut conn = pool.get_conn().unwrap();
///
/// conn.query("SELECT 42").map(|mut result| {
/// let cell = result.next().unwrap().unwrap().take(0).unwrap();
/// assert_eq!(cell, Value::Bytes(b"42".to_vec()));
/// assert_eq!(from_value::<i64>(cell), 42i64);
/// }).unwrap();
/// conn.prep_exec("SELECT 42", ()).map(|mut result| {
/// let cell = result.next().unwrap().unwrap().take(0).unwrap();
/// assert_eq!(cell, Value::Int(42i64));
/// assert_eq!(from_value::<i64>(cell), 42i64);
/// }).unwrap();
/// ```
///
/// For more info on how to work with query results please look at
/// [`QueryResult`](../struct.QueryResult.html) documentation.
#[derive(Debug)]
pub struct PooledConn {
pool: Pool,
conn: Option<Conn>,
}
impl Drop for PooledConn {
fn drop(&mut self) {
if self.pool.count.load(Ordering::Relaxed) > self.pool.max.load(Ordering::Relaxed)
|| self.conn.is_none()
{
self.pool.count.fetch_sub(1, Ordering::SeqCst);
} else {
self.conn.as_mut().unwrap().set_local_infile_handler(None);
let mut pool = (self.pool.inner).0.lock().unwrap();
pool.pool.push_back(self.conn.take().unwrap());
drop(pool);
(self.pool.inner).1.notify_one();
}
}
}
impl PooledConn {
/// Redirects to
/// [`Conn#query`](struct.Conn.html#method.query).
pub fn query<T: AsRef<str>>(&mut self, query: T) -> MyResult<QueryResult<'_>> {
self.conn.as_mut().unwrap().query(query)
}
/// See [`Conn::first`](struct.Conn.html#method.first).
pub fn first<T: AsRef<str>, U: FromRow>(&mut self, query: T) -> MyResult<Option<U>> {
self.query(query).and_then(|result| {
for row in result {
return row.map(|x| Some(from_row(x)));
}
return Ok(None);
})
}
/// See [`Conn::prepare`](struct.Conn.html#method.prepare).
pub fn | <T: AsRef<str>>(&mut self, query: T) -> MyResult<Stmt<'_>> {
self.conn.as_mut().unwrap().prepare(query)
}
/// See [`Conn::prep_exec`](struct.Conn.html#method.prep_exec).
pub fn prep_exec<A, T>(&mut self, query: A, params: T) -> MyResult<QueryResult<'_>>
where
A: AsRef<str>,
T: Into<Params>,
{
self.conn.as_mut().unwrap().prep_exec(query, params)
}
/// See [`Conn::first_exec`](struct.Conn.html#method.first_exec).
pub fn first_exec<Q, P, T>(&mut self, query: Q, params: P) -> MyResult<Option<T>>
where
Q: AsRef<str>,
P: Into<Params>,
T: FromRow,
{
self.prep_exec(query, params).and_then(|result| {
for row in result {
return row.map(|x| Some(from_row(x)));
}
return Ok(None);
})
}
/// Redirects to
/// [`Conn#start_transaction`](struct.Conn.html#method.start_transaction)
pub fn start_transaction<'a>(
&'a mut self,
consistent_snapshot: bool,
isolation_level: Option<IsolationLevel>,
readonly: Option<bool>,
) -> MyResult<Transaction<'a>> {
self.conn.as_mut().unwrap().start_transaction(
consistent_snapshot,
isolation_level,
readonly,
)
}
/// Gives mutable reference to the wrapped
/// [`Conn`](struct.Conn.html).
pub fn as_mut<'a>(&'a mut self) -> &'a mut Conn {
self.conn.as_mut().unwrap()
}
/// Gives reference to the wrapped
/// [`Conn`](struct.Conn.html).
pub fn as_ref<'a>(&'a self) -> &'a Conn {
self.conn.as_ref().unwrap()
}
/// Unwraps wrapped [`Conn`](struct.Conn.html).
pub fn unwrap(mut self) -> Conn {
self.conn.take().unwrap()
}
fn pooled_prepare<'a, T: AsRef<str>>(mut self, query: T) -> MyResult<Stmt<'a>> {
let query = query.as_ref();
let (named_params, real_query) = parse_named_params(query)?;
self.as_mut()
._prepare(real_query.borrow(), named_params)
.map(|stmt| Stmt::new_pooled(stmt, self))
}
fn pooled_prep_exec<'a, A, T>(mut self, query: A, params: T) -> MyResult<QueryResult<'a>>
where
A: AsRef<str>,
T: Into<Params>,
{
let query = query.as_ref();
let (named_params, real_query) = parse_named_params(query)?;
let stmt = self.as_mut()._prepare(real_query.borrow(), named_params)?;
let stmt = Stmt::new_pooled(stmt, self);
stmt.prep_exec(params)
}
fn pooled_start_transaction<'a>(
mut self,
consistent_snapshot: bool,
isolation_level: Option<IsolationLevel>,
readonly: Option<bool>,
) -> MyResult<Transaction<'a>> {
let _ = self
.as_mut()
._start_transaction(consistent_snapshot, isolation_level, readonly)?;
Ok(Transaction::new_pooled(self))
}
/// A way to override default local infile handler for this pooled connection. Destructor will
/// restore original handler before returning connection to a pool.
/// See [`Conn::set_local_infile_handler`](struct.Conn.html#method.set_local_infile_handler).
pub fn set_local_infile_handler(&mut self, handler: Option<LocalInfileHandler>) {
self.conn
.as_mut()
.unwrap()
.set_local_infile_handler(handler);
}
}
impl GenericConnection for PooledConn {
fn query<T: AsRef<str>>(&mut self, query: T) -> MyResult<QueryResult<'_>> {
self.query(query)
}
fn first<T: AsRef<str>, U: FromRow>(&mut self, query: T) -> MyResult<Option<U>> {
self.first(query)
}
fn prepare<T: AsRef<str>>(&mut self, query: T) -> MyResult<Stmt<'_>> {
self.prepare(query)
}
fn prep_exec<A, T>(&mut self, query: A, params: T) -> MyResult<QueryResult<'_>>
where
A: AsRef<str>,
T: Into<Params>,
{
self.prep_exec(query, params)
}
fn first_exec<Q, P, T>(&mut self, query: Q, params: P) -> MyResult<Option<T>>
where
Q: AsRef<str>,
P: Into<Params>,
T: FromRow,
{
self.first_exec(query, params)
}
}
#[cfg(test)]
#[allow(non_snake_case)]
mod test {
use crate::Opts;
use crate::OptsBuilder;
pub static USER: &'static str = "root";
pub static PASS: &'static str = "password";
pub static ADDR: &'static str = "127.0.0.1";
pub static PORT: u16 = 3307;
#[cfg(all(feature = "ssl", target_os = "macos"))]
pub fn get_opts() -> Opts {
let pwd: String = ::std::env::var("MYSQL_SERVER_PASS").unwrap_or(PASS.to_string());
let port: u16 = ::std::env::var("MYSQL_SERVER_PORT")
.ok()
.map(|my_port| my_port.parse().ok().unwrap_or(PORT))
.unwrap_or(PORT);
let mut builder = OptsBuilder::default();
builder
.user(Some(USER))
.pass(Some(pwd))
.ip_or_hostname(Some(ADDR))
.tcp_port(port)
.init(vec!["SET GLOBAL sql_mode = 'TRADITIONAL'"])
.ssl_opts(Some(Some((
"tests/client.p12",
"pass",
vec!["tests/ca-cert.cer"],
))));
builder.into()
}
#[cfg(all(feature = "ssl", all(unix, not(target_os = "macos"))))]
pub fn get_opts() -> Opts {
let pwd: String = ::std::env::var("MYSQL_SERVER_PASS").unwrap_or(PASS.to_string());
let port: u16 = ::std::env::var("MYSQL_SERVER_PORT")
.ok()
.map(|my_port| my_port.parse().ok().unwrap_or(PORT))
.unwrap_or(PORT);
let mut builder = OptsBuilder::default();
builder
.user(Some(USER))
.pass(Some(pwd))
.ip_or_hostname(Some(ADDR))
.tcp_port(port)
.init(vec!["SET GLOBAL sql_mode = 'TRADITIONAL'"])
.ssl_opts(Some(("tests/ca-cert.pem", None::<(String, String)>)));
builder.into()
}
#[cfg(any(not(feature = "ssl"), target_os = "windows"))]
pub fn get_opts() -> Opts {
let pwd: String = ::std::env::var("MYSQL_SERVER_PASS").unwrap_or(PASS.to_string());
let port: u16 = ::std::env::var("MYSQL_SERVER_PORT")
.ok()
.map(|my_port| my_port.parse().ok().unwrap_or(PORT))
.unwrap_or(PORT);
let mut builder = OptsBuilder::default();
builder
.user(Some(USER))
.pass(Some(pwd))
.ip_or_hostname(Some(ADDR))
.tcp_port(port)
.init(vec!["SET GLOBAL sql_mode = 'TRADITIONAL'"]);
builder.into()
}
mod pool {
use crate::params;
use crate::OptsBuilder;
use std::thread;
use std::time::Duration;
use super::super::super::super::error::{DriverError, Error};
use super::super::Pool;
use super::get_opts;
use crate::from_row;
use crate::from_value;
#[test]
fn multiple_pools_should_work() {
let pool = Pool::new(get_opts()).unwrap();
pool.prep_exec("DROP DATABASE IF EXISTS A", ()).unwrap();
pool.prep_exec("CREATE DATABASE A", ()).unwrap();
pool.prep_exec("DROP TABLE IF EXISTS A.a", ()).unwrap();
pool.prep_exec("CREATE TABLE IF NOT EXISTS A.a (id INT)", ())
.unwrap();
pool.prep_exec("INSERT INTO A.a VALUES (1)", ()).unwrap();
let mut builder = OptsBuilder::from_opts(get_opts());
builder.db_name(Some("A"));
let pool2 = Pool::new(builder).unwrap();
let row = pool2
.first_exec("SELECT COUNT(*) FROM a", ())
.unwrap()
.unwrap();
assert_eq!((1u8,), from_row(row));
pool.prep_exec("DROP DATABASE A", ()).unwrap();
}
struct A {
pool: Pool,
x: u32,
}
impl A {
fn add(&mut self) {
self.x += 1;
}
}
#[test]
fn get_opts_from_string() {
let pass: String =
::std::env::var("MYSQL_SERVER_PASS").unwrap_or(super::PASS.to_string());
let port: u16 = ::std::env::var("MYSQL_SERVER_PORT")
.ok()
.map(|my_port| my_port.parse().ok().unwrap_or(super::PORT))
.unwrap_or(super::PORT);
Pool::new(format!(
"mysql://{}:{}@{}:{}",
super::USER,
pass,
super::ADDR,
port
))
.unwrap();
}
#[test]
fn should_fix_connectivity_errors_on_prepare() {
let pool = Pool::new_manual(2, 2, get_opts()).unwrap();
let mut conn = pool.get_conn().unwrap();
let row = pool
.first_exec("SELECT CONNECTION_ID();", ())
.unwrap()
.unwrap();
let (id,): (u32,) = from_row(row);
conn.prep_exec("KILL CONNECTION ?", (id,)).unwrap();
thread::sleep(Duration::from_millis(250));
pool.prepare("SHOW FULL PROCESSLIST").unwrap();
}
#[test]
fn should_fix_connectivity_errors_on_prep_exec() {
let pool = Pool::new_manual(2, 2, get_opts()).unwrap();
let mut conn = pool.get_conn().unwrap();
let row = pool
.first_exec("SELECT CONNECTION_ID();", ())
.unwrap()
.unwrap();
let (id,): (u32,) = from_row(row);
conn.prep_exec("KILL CONNECTION ?", (id,)).unwrap();
thread::sleep(Duration::from_millis(250));
pool.prep_exec("SHOW FULL PROCESSLIST", ()).unwrap();
}
#[test]
fn should_fix_connectivity_errors_on_start_transaction() {
let pool = Pool::new_manual(2, 2, get_opts()).unwrap();
let mut conn = pool.get_conn().unwrap();
let row = pool
.first_exec("SELECT CONNECTION_ID();", ())
.unwrap()
.unwrap();
let (id,): (u32,) = from_row(row);
conn.prep_exec("KILL CONNECTION ?", (id,)).unwrap();
thread::sleep(Duration::from_millis(250));
pool.start_transaction(false, None, None).unwrap();
}
#[test]
fn should_execute_queryes_on_PooledConn() {
let pool = Pool::new(get_opts()).unwrap();
let mut threads = Vec::new();
for _ in 0usize..10 {
let pool = pool.clone();
threads.push(thread::spawn(move || {
let conn = pool.get_conn();
assert!(conn.is_ok());
let mut conn = conn.unwrap();
assert!(conn.query("SELECT 1").is_ok());
}));
}
for t in threads.into_iter() {
assert!(t.join().is_ok());
}
}
#[test]
fn should_timeout_if_no_connections_available() {
let pool = Pool::new_manual(0, 1, get_opts()).unwrap();
let conn1 = pool.try_get_conn(357).unwrap();
let conn2 = pool.try_get_conn(357);
assert!(conn2.is_err());
match conn2 {
Err(Error::DriverError(DriverError::Timeout)) => assert!(true),
_ => assert!(false),
}
drop(conn1);
assert!(pool.try_get_conn(357).is_ok());
}
#[test]
fn should_execute_statements_on_PooledConn() {
let pool = Pool::new(get_opts()).unwrap();
let mut threads = Vec::new();
for _ in 0usize..10 {
let pool = pool.clone();
threads.push(thread::spawn(move || {
let mut conn = pool.get_conn().unwrap();
let mut stmt = conn.prepare("SELECT 1").unwrap();
assert!(stmt.execute(()).is_ok());
}));
}
for t in threads.into_iter() {
assert!(t.join().is_ok());
}
let pool = Pool::new(get_opts()).unwrap();
let mut threads = Vec::new();
for _ in 0usize..10 {
let pool = pool.clone();
threads.push(thread::spawn(move || {
let mut conn = pool.get_conn().unwrap();
conn.prep_exec("SELECT ?", (1,)).unwrap();
}));
}
for t in threads.into_iter() {
assert!(t.join().is_ok());
}
}
#[test]
fn should_execute_statements_on_Pool() {
let pool = Pool::new(get_opts()).unwrap();
let mut threads = Vec::new();
for _ in 0usize..10 {
let pool = pool.clone();
threads.push(thread::spawn(move || {
let mut stmt = pool.prepare("SELECT 1").unwrap();
assert!(stmt.execute(()).is_ok());
}));
}
for t in threads.into_iter() {
assert!(t.join().is_ok());
}
let pool = Pool::new(get_opts()).unwrap();
let mut threads = Vec::new();
for _ in 0usize..10 {
let pool = pool.clone();
threads.push(thread::spawn(move || {
pool.prep_exec("SELECT ?", (1,)).unwrap();
}));
}
for t in threads.into_iter() {
assert!(t.join().is_ok());
}
pool.prep_exec("SELECT 1", ())
.and_then(|mut res1| {
pool.prep_exec("SELECT 2", ()).map(|mut res2| {
let (x1,) = from_row::<(u8,)>(res1.next().unwrap().unwrap());
let (x2,) = from_row::<(u8,)>(res2.next().unwrap().unwrap());
assert_eq!(1, x1);
assert_eq!(2, x2);
})
})
.unwrap()
}
#[test]
#[allow(unused_variables)]
fn should_start_transaction_on_Pool() {
let pool = Pool::new_manual(1, 10, get_opts()).unwrap();
pool.prepare("CREATE TEMPORARY TABLE mysql.tbl(a INT)")
.ok()
.map(|mut stmt| {
assert!(stmt.execute(()).is_ok());
});
pool.start_transaction(false, None, None)
.and_then(|mut t| {
t.query("INSERT INTO mysql.tbl(a) VALUES(1)").unwrap();
t.query("INSERT INTO mysql.tbl(a) VALUES(2)").unwrap();
t.commit()
})
.unwrap();
pool.prepare("SELECT COUNT(a) FROM mysql.tbl")
.ok()
.map(|mut stmt| {
for x in stmt.execute(()).unwrap() {
let mut x = x.unwrap();
assert_eq!(from_value::<u8>(x.take(0).unwrap()), 2u8);
}
});
pool.start_transaction(false, None, None)
.and_then(|mut t| {
t.query("INSERT INTO mysql.tbl(a) VALUES(1)").unwrap();
t.query("INSERT INTO mysql.tbl(a) VALUES(2)").unwrap();
t.rollback()
})
.unwrap();
pool.prepare("SELECT COUNT(a) FROM mysql.tbl")
.ok()
.map(|mut stmt| {
for x in stmt.execute(()).unwrap() {
let mut x = x.unwrap();
assert_eq!(from_value::<u8>(x.take(0).unwrap()), 2u8);
}
});
pool.start_transaction(false, None, None)
.and_then(|mut t| {
t.query("INSERT INTO mysql.tbl(a) VALUES(1)").unwrap();
t.query("INSERT INTO mysql.tbl(a) VALUES(2)").unwrap();
Ok(())
})
.unwrap();
pool.prepare("SELECT COUNT(a) FROM mysql.tbl")
.ok()
.map(|mut stmt| {
for x in stmt.execute(()).unwrap() {
let mut x = x.unwrap();
assert_eq!(from_value::<u8>(x.take(0).unwrap()), 2u8);
}
});
let mut a = A { pool: pool, x: 0 };
let transaction = a.pool.start_transaction(false, None, None).unwrap();
a.add();
}
#[test]
fn should_start_transaction_on_PooledConn() {
let pool = Pool::new(get_opts()).unwrap();
let mut conn = pool.get_conn().unwrap();
assert!(conn
.query("CREATE TEMPORARY TABLE mysql.tbl(a INT)")
.is_ok());
assert!(conn
.start_transaction(false, None, None)
.and_then(|mut t| {
assert!(t.query("INSERT INTO mysql.tbl(a) VALUES(1)").is_ok());
assert!(t.query("INSERT INTO mysql.tbl(a) VALUES(2)").is_ok());
t.commit()
})
.is_ok());
for x in conn.query("SELECT COUNT(a) FROM mysql.tbl").unwrap() {
let mut x = x.unwrap();
assert_eq!(from_value::<u8>(x.take(0).unwrap()), 2u8);
}
assert!(conn
.start_transaction(false, None, None)
.and_then(|mut t| {
assert!(t.query("INSERT INTO mysql.tbl(a) VALUES(1)").is_ok());
assert!(t.query("INSERT INTO mysql.tbl(a) VALUES(2)").is_ok());
t.rollback()
})
.is_ok());
for x in conn.query("SELECT COUNT(a) FROM mysql.tbl").unwrap() {
let mut x = x.unwrap();
assert_eq!(from_value::<u8>(x.take(0).unwrap()), 2u8);
}
assert!(conn
.start_transaction(false, None, None)
.and_then(|mut t| {
assert!(t.query("INSERT INTO mysql.tbl(a) VALUES(1)").is_ok());
assert!(t.query("INSERT INTO mysql.tbl(a) VALUES(2)").is_ok());
Ok(())
})
.is_ok());
for x in conn.query("SELECT COUNT(a) FROM mysql.tbl").unwrap() {
let mut x = x.unwrap();
assert_eq!(from_value::<u8>(x.take(0).unwrap()), 2u8);
}
}
#[test]
fn should_work_with_named_params() {
let pool = Pool::new(get_opts()).unwrap();
pool.prepare("SELECT :a, :b, :a + :b, :abc")
.map(|mut stmt| {
let mut result = stmt
.execute(params! {
"a" => 1,
"b" => 2,
"abc" => 4,
})
.unwrap();
let row = result.next().unwrap().unwrap();
assert_eq!((1, 2, 3, 4), from_row(row));
})
.unwrap();
let params = params! {"a" => 1, "b" => 2, "abc" => 4};
pool.prep_exec("SELECT :a, :b, :a+:b, :abc", params)
.map(|mut result| {
let row = result.next().unwrap().unwrap();
assert_eq!((1, 2, 3, 4), from_row(row));
})
.unwrap();
}
#[cfg(feature = "nightly")]
mod bench {
use super::super::get_opts;
use std::thread;
use test;
use Pool;
#[bench]
fn many_prepares(bencher: &mut test::Bencher) {
let pool = Pool::new(get_opts()).unwrap();
bencher.iter(|| {
pool.prepare("SELECT 1").unwrap();
});
}
#[bench]
fn many_prepexecs(bencher: &mut test::Bencher) {
let pool = Pool::new(get_opts()).unwrap();
bencher.iter(|| {
pool.prep_exec("SELECT 1", ()).unwrap();
});
}
#[bench]
fn many_prepares_threaded(bencher: &mut test::Bencher) {
let pool = Pool::new(get_opts()).unwrap();
bencher.iter(|| {
let mut threads = Vec::new();
for _ in 0..4 {
let pool = pool.clone();
threads.push(thread::spawn(move || {
for _ in 0..250 {
test::black_box(
pool.prep_exec(
"SELECT 1, 'hello world', 123.321, ?, ?, ?",
("hello", "world", 65536),
)
.unwrap(),
);
}
}));
}
for t in threads {
t.join().unwrap();
}
});
}
#[bench]
fn many_prepares_threaded_no_cache(bencher: &mut test::Bencher) {
let mut pool = Pool::new(get_opts()).unwrap();
pool.use_cache(false);
bencher.iter(|| {
let mut threads = Vec::new();
for _ in 0..4 {
let pool = pool.clone();
threads.push(thread::spawn(move || {
for _ in 0..250 {
test::black_box(
pool.prep_exec(
"SELECT 1, 'hello world', 123.321, ?, ?, ?",
("hello", "world", 65536),
)
.unwrap(),
);
}
}));
}
for t in threads {
t.join().unwrap();
}
});
}
}
}
}
| prepare |
file.go | package config
import (
"encoding/json"
"fmt"
"os"
"gopkg.in/apollo.v0"
"gopkg.in/yaml.v3"
)
//LoadEnvFile Load config from the file that path is saved in os env.
func LoadFromEnvFile() |
//LoadFromFile from file
func LoadFromFile(fileName string) error {
f, err := os.Open(fileName)
if err != nil {
return err
}
defer f.Close()
if err := yaml.NewDecoder(f).Decode(&config); err != nil {
return err
}
return nil
}
//LoadCustomFromFile Load custom config from file, save to custom config
func LoadCustomFromFile(fileName string, customCfg interface{}) error {
f, err := os.Open(fileName)
if err != nil {
return err
}
defer f.Close()
if err := yaml.NewDecoder(f).Decode(customCfg); err != nil {
return err
}
return nil
}
func loadConfigsFromYamlFile() {
appCfgFileName := os.Getenv(appConfigFileEnvKey)
if err := LoadFromFile(appCfgFileName); err != nil {
fmt.Printf("load file config error: %s\n", err)
os.Exit(1)
}
apiCfgFileName := os.Getenv(apiConfigFileEnvKey)
if err := LoadFromFile(apiCfgFileName); err != nil {
fmt.Printf("load file config error: %s\n", err)
os.Exit(1)
}
fmt.Printf("%+v", config)
}
| {
loadConfigsFromYamlFile()
if IsApolloEnable() {
if err := apollo.StartWithConf(&config.Apollo.Conf); err != nil {
fmt.Printf("load apollo config error: %s\n", err)
os.Exit(1)
return
}
go func() {
for {
event := apollo.WatchUpdate()
changeEvent := <-event
bytes, _ := json.Marshal(changeEvent)
fmt.Println("event:", string(bytes))
}
}()
}
} |
lib.rs | use std::{
cell::Cell,
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
thread,
time::Instant,
};
#[derive(Debug)]
/// Random number generator.
pub struct Rng(Cell<u64>);
const CF64: f64 = 1.0 / ((1u64 << 53) as f64);
impl Rng {
#[inline]
pub fn new() -> Self {
Self::with_seed({
let mut hasher = DefaultHasher::new();
Instant::now().hash(&mut hasher);
thread::current().id().hash(&mut hasher);
let hash = hasher.finish();
(hash << 1) | 1
})
}
#[inline]
pub const fn with_seed(seed: u64) -> Self {
Self { 0: Cell::new(seed) }
}
#[inline]
pub fn get_seed(&self) -> u64 {
self.0.get()
}
#[inline]
pub fn set_seed(&self, seed: u64) {
self.0.set(seed);
}
#[inline]
pub fn u64(&self) -> u64 {
self.0.set(self.0.get().wrapping_add(0xa0761d6478bd642f));
let s = self.0.get();
let t = u128::from(s) * (u128::from(s ^ 0xe7037ed1a0b428db));
((t >> 64) as u64) ^ (t as u64)
}
#[inline]
pub fn u32(&self) -> u32 {
self.u64() as u32
}
#[inline]
pub fn f64(&self) -> f64 {
((self.u64() >> 11) as f64) * CF64
}
#[inline]
pub fn f32(&self) -> f32 {
(self.u32() as f32) / (u32::MAX as f32)
}
#[inline]
pub fn i64(&self) -> i64 {
self.u64() as i64
}
#[inline]
pub fn i32(&self) -> i32 {
self.u32() as i32
}
#[inline]
pub fn | (&self, max: u64) -> u64 {
let mut r = self.u64();
let mut hi = mul_high_u64(r, max);
let mut lo = r.wrapping_mul(max);
if lo < max {
let t = max.wrapping_neg() % max;
while lo < t {
r = self.u64();
hi = mul_high_u64(r, max);
lo = r.wrapping_mul(max);
}
}
hi
}
#[inline]
pub fn u32_less_than(&self, max: u32) -> u32 {
let mut r = self.u32();
let mut hi = mul_high_u32(r, max);
let mut lo = r.wrapping_mul(max);
if lo < max {
let t = max.wrapping_neg() % max;
while lo < t {
r = self.u32();
hi = mul_high_u32(r, max);
lo = r.wrapping_mul(max);
}
}
hi
}
#[inline]
pub fn f64_less_than(&self, max: f64) -> f64 {
assert!(max > 0., "max must be positive");
self.f64() * max
}
#[inline]
pub fn f32_less_than(&self, max: f32) -> f32 {
assert!(max > 0., "max must be positive");
self.f32() * max
}
#[inline]
pub fn i64_less_than(&self, max: i64) -> i64 {
self.u64_less_than(max as u64) as i64
}
#[inline]
pub fn i32_less_than(&self, max: i32) -> i32 {
self.u32_less_than(max as u32) as i32
}
#[inline]
pub fn u64_in_range(&self, min: u64, max: u64) -> u64 {
assert!(max > min, "max must be greater than min");
min + self.u64_less_than(max + 1 - min)
}
#[inline]
pub fn u32_in_range(&self, min: u32, max: u32) -> u32 {
assert!(max > min, "max must be greater than min");
min + self.u32_less_than(max + 1 - min)
}
#[inline]
pub fn f64_in_range(&self, min: f64, max: f64) -> f64 {
assert!(max > min, "max must be greater than min");
min + self.f64_less_than(max - min)
}
#[inline]
pub fn f32_in_range(&self, min: f32, max: f32) -> f32 {
assert!(max > min, "max must be greater than min");
min + self.f32_less_than(max - min)
}
#[inline]
pub fn i64_in_range(&self, min: i64, max: i64) -> i64 {
assert!(max > min, "max must be greater than min");
min + self.i64_less_than(max + 1 - min)
}
#[inline]
pub fn i32_in_range(&self, min: i32, max: i32) -> i32 {
assert!(max > min, "max must be greater than min");
min + self.i32_less_than(max + 1 - min)
}
#[inline]
pub fn bool(&self) -> bool {
self.f32() < 0.5
}
#[inline]
pub fn wyhash_u64(&self) -> u64 {
self.0.set(self.0.get() + 0x60bee2bee120fc15);
let mut tmp: u128 = (self.0.get() as u128) * 0xa3b195354a39b70d;
let m1: u64 = ((tmp >> 64) ^ tmp) as u64;
tmp = (m1 as u128) * 0x1b03738712fad5c9;
((tmp >> 64) ^ tmp) as u64
}
#[inline]
pub fn wyhash_f64(&self) -> f64 {
(self.wyhash_u64() as f64) / (u64::MAX as f64)
}
}
#[inline]
fn mul_high_u32(a: u32, b: u32) -> u32 {
(((a as u64) * (b as u64)) >> 32) as u32
}
#[inline]
fn mul_high_u64(a: u64, b: u64) -> u64 {
(((a as u128) * (b as u128)) >> 64) as u64
}
thread_local! {
static RNG: Rng = Rng::new();
}
#[doc = "Get the seed for the random number generator."]
pub fn get_seed() -> u64 {
RNG.with(|rng| rng.get_seed())
}
#[doc = "Set the seed for the random number generator."]
pub fn set_seed(seed: u64) {
RNG.with(|rng| rng.set_seed(seed));
}
macro_rules! impl_rng_functions {
($doc1: tt $doc2: tt | $($fn: ident $type: ident $($arg: ident)* ),+ $(,)?) => {
$(
#[doc = $doc1]
#[doc = stringify!($type)]
#[doc = $doc2]
pub fn $fn( $($arg: $type, )* ) -> $type {
RNG.with(|rng| rng.$fn( $($arg, )* ))
}
)+
};
}
macro_rules! impl_rng_functions_helper_1 {
($doc1: tt $doc2: tt | $($type: ident, )+) => {
impl_rng_functions!($doc1 $doc2 | $($type $type, )+);
};
}
macro_rules! impl_rng_functions_helper_2 {
($doc1: tt $doc2: tt | $($fn: tt $type: ident, )+) => {
impl_rng_functions!($doc1 $doc2 | $($fn $type max, )+);
};
}
macro_rules! impl_rng_functions_helper_3 {
($($fn: tt $type: ident, )+) => {
impl_rng_functions!("Generate a random `" "` value in the range [min, max] (i.e., both endpoints are included)." | $($fn $type min max, )+);
}
}
impl_rng_functions_helper_1!("Generate a random `" "` value." | u64, u32, i64, i32, bool,);
impl_rng_functions_helper_1!("Generate a random `" "` value in the range [0, 1)." | f64, f32,);
impl_rng_functions_helper_2!("Generate a random `" "` value less than `max`." | u64_less_than u64, u32_less_than u32, i64_less_than i64, i32_less_than i32,);
impl_rng_functions_helper_2!("Generate a random `" "` value in the range [0, max)." | f64_less_than f64, f32_less_than f32,);
impl_rng_functions_helper_3!(u64_in_range u64, u32_in_range u32, f64_in_range f64, f32_in_range f32, i64_in_range i64, i32_in_range i32,);
| u64_less_than |
mod.rs | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::SCMPR1 {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(), | pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct SCMPR1R {
bits: u32,
}
impl SCMPR1R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
}
#[doc = r" Proxy"]
pub struct _SCMPR1W<'a> {
w: &'a mut W,
}
impl<'a> _SCMPR1W<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
const MASK: u32 = 4294967295;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:31 - Compare this value to the value in the COUNTER register according to the match criterion, as selected in the COMPARE_B_EN bit in the REG_CTIMER_STCGF register."]
#[inline]
pub fn scmpr1(&self) -> SCMPR1R {
let bits = {
const MASK: u32 = 4294967295;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u32
};
SCMPR1R { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:31 - Compare this value to the value in the COUNTER register according to the match criterion, as selected in the COMPARE_B_EN bit in the REG_CTIMER_STCGF register."]
#[inline]
pub fn scmpr1(&mut self) -> _SCMPR1W {
_SCMPR1W { w: self }
}
} | }
}
#[doc = r" Writes to the register"]
#[inline] |
common.rs | //! Common pinout
//!
//! The Teensy 4.0 and 4.1 share many pins. This module provides
//! the pins that are common across both boards. For pins that are unique to | //!
//! ## Common pin table
//!
//! This table describes all common pins and their possible functions. Besides this table,
//! there are two other ways to identify which pads support which peripheral:
//!
//! - study the i.MX RT 1060 Reference Manual. This is the authority on pad configuration.
//! - study the trait implementations for the pad. Select a pin type alias, like [`P0`],
//! and click-through to its pad documentation (`AD_B0_03`). Notice the listing of `imxrt-iomuxc`
//! trait implementations. This describes what kinds of functions the pin supports. The constraints
//! may be enforced by the HAL's APIs.
//!
//! | Pin | Pad ID | Alt0 | Alt1 | Alt2 | Alt3 | Alt4 | Alt5 | Alt6 | Alt7 | Alt8 | Alt9 |
//! | --- | -------- | --------------- | --------------- | --------------- | -------------------- | -------------------- | ------------------ | -------------------- | -------------------- | --------------------- | ---------------- |
//! | 0 | AD_B0_03 | FLEXCAN2_RX | XBAR1_INOUT17 | LPUART6_RX | USB_OTG1_OC | FLEXPWM1_PWMX01 | GPIO1_IO03 | REF_CLK_24M | LPSPI3_PCS0 | --- | --- |
//! | 1 | AD_B0_02 | FLEXCAN2_TX | XBAR1_INOUT16 | LPUART6_TX | USB_OTG1_PWR | FLEXPWM1_PWMX00 | GPIO1_IO02 | LPI2C1_HREQ | LPSPI3_SDI | --- | --- |
//! | 2 | EMC_04 | SEMC_DATA04 | FLEXPWM4_PWMA02 | SAI2_TX_DATA | XBAR1_INOUT06 | FLEXIO1_FLEXIO04 | GPIO4_IO04 | --- | --- | --- | --- |
//! | 3 | EMC_05 | SEMC_DATA05 | FLEXPWM4_PWMB02 | SAI2_TX_SYNC | XBAR1_INOUT07 | FLEXIO1_FLEXIO05 | GPIO4_IO05 | --- | --- | --- | --- |
//! | 4 | EMC_06 | SEMC_DATA06 | FLEXPWM2_PWMA00 | SAI2_TX_BCLK | XBAR1_INOUT08 | FLEXIO1_FLEXIO06 | GPIO4_IO06 | --- | --- | --- | --- |
//! | 5 | EMC_08 | SEMC_DM00 | FLEXPWM2_PWMA01 | SAI2_RX_DATA | XBAR1_INOUT17 | FLEXIO1_FLEXIO08 | GPIO4_IO08 | --- | --- | --- | --- |
//! | 6 | B0_10 | LCD_DATA06 | QTIMER4_TIMER1 | FLEXPWM2_PWMA02 | SAI1_TX_DATA03 | FLEXIO2_FLEXIO10 | GPIO2_IO10 | SRC_BOOT_CFG06 | --- | ENET2_CRS | --- |
//! | 7 | B1_01 | LCD_DATA13 | XBAR1_INOUT15 | LPUART4_RX | SAI1_TX_DATA00 | FLEXIO2_FLEXIO17 | GPIO2_IO17 | FLEXPWM1_PWMB03 | --- | ENET2_RDATA00 | FLEXIO3_FLEXIO17 |
//! | 8 | B1_00 | LCD_DATA12 | XBAR1_INOUT14 | LPUART4_TX | SAI1_RX_DATA00 | FLEXIO2_FLEXIO16 | GPIO2_IO16 | FLEXPWM1_PWMA03 | --- | ENET2_RX_ER | FLEXIO3_FLEXIO16 |
//! | 9 | B0_11 | LCD_DATA07 | QTIMER4_TIMER2 | FLEXPWM2_PWMB02 | SAI1_TX_DATA02 | FLEXIO2_FLEXIO11 | GPIO2_IO11 | SRC_BOOT_CFG07 | --- | ENET2_COL | --- |
//! | 10 | B0_00 | LCD_CLK | QTIMER1_TIMER0 | MQS_RIGHT | LPSPI4_PCS0 | FLEXIO2_FLEXIO00 | GPIO2_IO00 | SEMC_CSX01 | --- | ENET2_MDC | --- |
//! | 11 | B0_02 | LCD_HSYNC | QTIMER1_TIMER2 | FLEXCAN1_TX | LPSPI4_SDO | FLEXIO2_FLEXIO02 | GPIO2_IO02 | SEMC_CSX03 | --- | ENET2_1588_EVENT0_OUT | --- |
//! | 12 | B0_01 | LCD_ENABLE | QTIMER1_TIMER1 | MQS_LEFT | LPSPI4_SDI | FLEXIO2_FLEXIO01 | GPIO2_IO01 | SEMC_CSX02 | --- | ENET2_MDIO | --- |
//! | 13 | B0_03 | LCD_VSYNC | QTIMER2_TIMER0 | FLEXCAN1_RX | LPSPI4_SCK | FLEXIO2_FLEXIO03 | GPIO2_IO03 (LED) | WDOG2_RESET_B_DEB | --- | ENET2_1588_EVENT0_IN | --- |
//! | 14 | AD_B1_02 | USB_OTG1_ID | QTIMER3_TIMER2 | LPUART2_TX | SPDIF_OUT | ENET_1588_EVENT2_OUT | GPIO1_IO18 | USDHC1_CD_B | KPP_ROW06 | GPT2_CLK | FLEXIO3_FLEXIO02 |
//! | 15 | AD_B1_03 | USB_OTG1_OC | QTIMER3_TIMER3 | LPUART2_RX | SPDIF_IN | ENET_1588_EVENT2_IN | GPIO1_IO19 | USDHC2_CD_B | KPP_COL06 | GPT2_CAPTURE1 | FLEXIO3_FLEXIO03 |
//! | 16 | AD_B1_07 | FLEXSPIB_DATA00 | LPI2C3_SCL | LPUART3_RX | SPDIF_EXT_CLK | CSI_HSYNC | GPIO1_IO23 | USDHC2_DATA3 | KPP_COL04 | GPT2_COMPARE3 | FLEXIO3_FLEXIO07 |
//! | 17 | AD_B1_06 | FLEXSPIB_DATA01 | LPI2C3_SDA | LPUART3_TX | SPDIF_LOCK | CSI_VSYNC | GPIO1_IO22 | USDHC2_DATA2 | KPP_ROW04 | GPT2_COMPARE2 | FLEXIO3_FLEXIO06 |
//! | 18 | AD_B1_01 | USB_OTG1_PWR | QTIMER3_TIMER1 | LPUART2_RTS_B | LPI2C1_SDA | CCM_PMIC_READY | GPIO1_IO17 | USDHC1_VSELECT | KPP_COL07 | ENET2_1588_EVENT0_IN | FLEXIO3_FLEXIO01 |
//! | 19 | AD_B1_00 | USB_OTG2_ID | QTIMER3_TIMER0 | LPUART2_CTS | LPI2C1_SCL | WDOG1_B | GPIO1_IO16 | USDHC1_WP | KPP_ROW07 | ENET2_1588_EVENT0_OUT | FLEXIO3_FLEXIO00 |
//! | 20 | AD_B1_10 | FLEXSPIA_DATA03 | WDOG1_B | LPUART8_TX | SAI1_RX_SYNC | CSI_DATA07 | GPIO1_IO26 | USDHC2_WP | KPP_ROW02 | ENET2_1588_EVENT1_OUT | FLEXIO3_FLEXIO10 |
//! | 21 | AD_B1_11 | FLEXSPIA_DATA02 | EWM_OUT_B | LPUART8_RX | SAI1_RX_BCLK | CSI_DATA06 | GPIO1_IO27 | USDHC2_RESET_B | KPP_COL02 | ENET2_1588_EVENT1_IN | FLEXIO3_FLEXIO11 |
//! | 22 | AD_B1_08 | FLEXSPIA_SS1_B | FLEXPWM4_PWMA00 | FLEXCAN1_TX | CCM_PMIC_READY | CSI_DATA09 | GPIO1_IO24 | USDHC2_CMD | KPP_ROW03 | --- | FLEXIO3_FLEXIO08 |
//! | 23 | AD_B1_09 | FLEXSPIA_DQS | FLEXPWM4_PWMA01 | FLEXCAN1_RX | SAI1_MCLK | CSI_DATA08 | GPIO1_IO25 | USDHC2_CLK | KPP_COL03 | --- | FLEXIO3_FLEXIO09 |
//! | 24 | AD_B0_12 | LPI2C4_SCL | CCM_PMIC_READY | LPUART1_TX | WDOG2_WDOG_B | FLEXPWM1_PWMX02 | GPIO1_IO12 | ENET_1588_EVENT1_OUT | NMI_GLUE_NMI | --- | --- |
//! | 25 | AD_B0_13 | LPI2C4_SDA | GPT1_CLK | LPUART1_RX | EWM_OUT_B | FLEXPWM1_PWMX03 | GPIO1_IO13 | ENET_1588_EVENT1_IN | REF_CLK_24M | --- | --- |
//! | 26 | AD_B1_14 | USB_OTG2_OC | XBAR1_IN24 | LPUART1_CTS_B | ENET_1588_EVENT0_OUT | CSI_VSYNC | GPIO1_IO14 | FLEXCAN2_TX | --- | FLEXCAN3_TX | --- |
//! | 27 | AD_B1_15 | USB_OTG2_PWR | XBAR1_IN25 | LPUART1_RTS_B | ENET_1588_EVENT0_IN | CSI_HSYNC | GPIO1_IO15 | FLEXCAN2_RX | WDOG1_WDOG_RST_B_DEB | FLEXCAN3_RX | --- |
//! | 28 | EMC_32 | SEMC_DATA10 | FLEXPWM3_PWMB01 | LPUART7_RX | CCM_PMIC_RDY | CSI_DATA21 | GPIO3_IO18 | --- | --- | ENET2_TX_EN | --- |
//! | 29 | EMC_31 | SEMC_DATA09 | FLEXPWM3_PWMA01 | LPUART7_TX | LPSPI1_PCS1 | CSI_DATA22 | GPIO4_IO31 | --- | --- | ENET2_TDATA01 | --- |
//! | 30 | EMC_37 | SEMC_DATA15 | XBAR1_IN23 | GPT1_COMPARE3 | SAI3_MCLK | CSI_DATA16 | GPIO3_IO23 | USDHC2_WP | --- | ENET2_RX_EN | FLEXCAN3_RX |
//! | 31 | EMC_36 | SEMC_DATA14 | XBAR1_IN22 | GPT1_COMPARE2 | SAI3_TX_DATA | CSI_DATA17 | GPIO3_IO22 | USDHC1_WP | --- | ENET2_RDATA01 | FLEXCAN3_TX |
//! | 32 | B0_12 | LCD_DATA08 | XBAR1_INOUT10 | ARM_TRACE_CLK | SAI1_TX_DATA01 | FLEXIO2_FLEXIO12 | GPIO2_IO12 | SRC_BOOT_CFG08 | --- | ENET2_TDATA00 | --- |
//! | 33 | EMC_07 | SEMC_DATA07 | FLEXPWM2_PWMB00 | SAI2_MCLK | XBAR1_INOUT09 | FLEXIO1_FLEXIO07 | GPIO4_IO07 | --- | --- | --- | --- |
//!
//! References:
//! - [Teensy Schematics](https://www.pjrc.com/teensy/schematic.html)
//! - i.MX RT 1060 Processor Reference Manual, Rev. 2, 12/2019
use crate::iomuxc::{ad_b0::*, ad_b1::*, b0::*, b1::*, emc::*};
/// Pin 0 (common)
pub type P0 = AD_B0_03;
/// Pin 1 (common)
pub type P1 = AD_B0_02;
/// Pin 2 (common)
pub type P2 = EMC_04;
/// Pin 3 (common)
pub type P3 = EMC_05;
/// Pin 4 (common)
pub type P4 = EMC_06;
/// Pin 5 (common)
pub type P5 = EMC_08;
/// Pin 6 (common)
pub type P6 = B0_10;
/// Pin 7 (common)
pub type P7 = B1_01;
/// Pin 8 (common)
pub type P8 = B1_00;
/// Pin 9 (common)
pub type P9 = B0_11;
/// Pin 10 (common)
pub type P10 = B0_00;
/// Pin 11 (common)
pub type P11 = B0_02;
/// Pin 12 (common)
pub type P12 = B0_01;
/// Pin 13 (common)
pub type P13 = B0_03;
/// Pin 14 (common)
pub type P14 = AD_B1_02;
/// Pin 15 (common)
pub type P15 = AD_B1_03;
/// Pin 16 (common)
pub type P16 = AD_B1_07;
/// Pin 17 (common)
pub type P17 = AD_B1_06;
/// Pin 18 (common)
pub type P18 = AD_B1_01;
/// Pin 19 (common)
pub type P19 = AD_B1_00;
/// Pin 20 (common)
pub type P20 = AD_B1_10;
/// Pin 21 (common)
pub type P21 = AD_B1_11;
/// Pin 22 (common)
pub type P22 = AD_B1_08;
/// Pin 23 (common)
pub type P23 = AD_B1_09;
/// Pin 24 (common)
pub type P24 = AD_B0_12;
/// Pin 25 (common)
pub type P25 = AD_B0_13;
/// Pin 26 (common)
pub type P26 = AD_B1_14;
/// Pin 27 (common)
pub type P27 = AD_B1_15;
/// Pin 28 (common)
pub type P28 = EMC_32;
/// Pin 29 (common)
pub type P29 = EMC_31;
/// Pin 30 (common)
pub type P30 = EMC_37;
/// Pin 31 (common)
pub type P31 = EMC_36;
/// Pin 32 (common)
pub type P32 = B0_12;
/// Pin 33 (common)
pub type P33 = EMC_07; | //! each board, and to acquire all of a board's pins, see the [`t40`](super::t40)
//! and [`t41`](super::t41) modules. |
structure.rs | use std::collections::HashMap;
use crate::storage::partition::{PARTITIONS, calculate_partition};
pub struct Storage {
inner: HashMap<u16, HashMap<Vec<u8>, Vec<u8>>>
}
impl Storage {
pub fn | () -> Self {
Storage { inner: HashMap::new() }
}
pub fn insert(&mut self, storage_key: Vec<u8>, data: Vec<u8>) -> Option<Vec<u8>> {
let partition_id = calculate_partition(&storage_key);
let partition = match self.inner.get_mut(&partition_id) {
None => {
self.inner.insert(partition_id, HashMap::new());
self.inner.get_mut(&partition_id).unwrap()
}
Some(m) => m
};
partition.insert(storage_key, data)
}
pub fn get(&self, storage_key: &Vec<u8>) -> Option<&Vec<u8>> {
let partition_id = calculate_partition(&storage_key);
let partition = match self.inner.get(&partition_id) {
None => return None,
Some(m) => m
};
partition.get(storage_key)
}
pub fn remove(&mut self, storage_key: &Vec<u8>) -> Option<Vec<u8>> {
let partition_id = calculate_partition(&storage_key);
let partition = match self.inner.get_mut(&partition_id) {
None => return None,
Some(m) => m
};
partition.remove(storage_key)
}
pub fn get_partition(&self, partition: u16) -> Vec<(&Vec<u8>, &Vec<u8>)> {
if partition >= PARTITIONS {
panic!("invalid partition: {}", partition);
}
match self.inner.get(&partition) {
None => vec!{},
Some(partition) => partition.iter().collect()
}
}
pub fn put_partition(&mut self, partition: Vec<(Vec<u8>, Vec<u8>)>) {
if !partition.is_empty() {
log::info!("put_partition {:?}", partition);
}
for (storage_key, data) in partition.into_iter() {
self.insert(storage_key, data);
}
}
} | new |
02-delayed-boomr.js | /*eslint-env mocha*/
/*global BOOMR_test,assert,BOOMR*/
describe("e2e/26-iframedelay/01-delayed-boomr", function() {
var tf = BOOMR.plugins.TestFramework;
var t = BOOMR_test;
function | (id) {
return document.getElementById(id).contentWindow.BOOMR.plugins.TestFramework.lastBeacon();
}
it("The base page should have only sent one page load beacon", function(done) {
t.ensureBeaconCount(done, 1);
});
it("IFrame 1 Should have only sent one page load beacon", function(done) {
var w = document.getElementById("frame1").contentWindow;
w.BOOMR_test.ensureBeaconCount(done, 1);
});
it("IFrame 2 Should have only sent one page load beacon", function(done) {
var w = document.getElementById("frame2").contentWindow;
w.BOOMR_test.ensureBeaconCount(done, 1);
});
describe("IFrame 1 Beacon 1 (onload)", function(done) {
var id = "frame1";
it("Should have a t_done less than 1s", function() {
var b = getIFrameBeacon(id);
assert.operator(b.t_done, "<", 1000);
});
});
describe("IFrame 2 Beacon 1 (onload)", function(done) {
var id = "frame2";
it("Should have a t_done less than 1s", function() {
var b = getIFrameBeacon(id);
assert.operator(b.t_done, "<", 1000);
});
});
describe("Base page Beacon 1", function() {
it("Should have page_ready (pr) flag", function() {
var b = tf.lastBeacon();
assert.equal(b.pr, "1");
});
it("Should have ifdl.done param", function() {
var b = tf.lastBeacon();
assert.isDefined(b["ifdl.done"]);
});
it("Should have ifdl.ct param", function() {
var b = tf.lastBeacon();
assert.equal(b["ifdl.ct"], "2");
});
it("Should have ifdl.r param", function() {
var b = tf.lastBeacon();
assert.equal(b["ifdl.r"], "0");
});
it("Should have ifdl.mon param", function() {
var b = tf.lastBeacon();
assert.equal(b["ifdl.mon"], "2");
});
it("Should have rt.end of the slowest iframe", function() {
var b = tf.lastBeacon(), bf1 = getIFrameBeacon("frame1"), bf2 = getIFrameBeacon("frame2");
var loadEnd = Math.max(bf1["rt.end"], bf2["rt.end"]);
assert.equal(b["rt.end"], loadEnd);
});
});
});
| getIFrameBeacon |
loader_test.py | __author__ = 'anonymous'
import unittest
import json
from config_loader import ConfigLoader
class LoaderTest(unittest.TestCase):
def test_settings_1(self):
loader = ConfigLoader('config.ini', ['production', 'staging'])
expected = json.dumps('26214400')
actual = loader.get('common.basic_size_limit')
print(expected)
print(actual)
self.assertEqual(expected, actual, "Matched")
def test_settings_2(self):
loader = ConfigLoader('config.ini', ['production', 'staging'])
expected = json.dumps('52428800')
actual = loader.get('common.student_size_limit')
print(expected)
print(actual)
self.assertEqual(expected, actual, "Matched")
def test_settings_3(self):
loader = ConfigLoader('config.ini', ['production', 'staging'])
expected = json.dumps('/srv/var/tmp/')
actual = loader.get('common.path')
print(expected)
print(actual)
self.assertEqual(expected, actual, "Matched")
def test_settings_4(self):
|
def test_settings_5(self):
loader = ConfigLoader('config.ini', ['production', 'staging'])
expected = json.dumps('/srv/uploads/')
actual = loader.get('ftp.path')
print(expected)
print(actual)
self.assertEqual(expected, actual, "Matched")
def test_settings_6(self):
loader = ConfigLoader('config.ini', ['production', 'staging'])
expected = json.dumps('/etc/var/uploads')
actual = loader.get('ftp.path')
print(expected)
print(actual)
self.assertNotEqual(expected, actual, "Matched")
def test_group_1(self):
loader = ConfigLoader('config.ini', ['production', 'staging'])
expected = {}
expected['common'] ={}
expected['common']['basic_size_limit'] = '26214400'
expected['common']['student_size_limit'] = '52428800'
expected['common']['paid_users_size_limit'] = '2147483648'
expected['common']['path'] = '/srv/var/tmp/'
expected = json.dumps(expected['common'],indent=2,separators=(',',' == '))
actual = loader.get('common')
print(expected)
print(actual)
self.assertEqual(expected,actual,"Matched")
def test_group_2(self):
loader = ConfigLoader('config.ini', ['production', 'staging'])
expected = {}
expected['ftp'] ={}
expected['ftp']['name'] = 'hello there, ftp uploading'
expected['ftp']['path'] = '/srv/uploads/'
expected['ftp']['enabled'] = 'no'
expected = json.dumps(expected['ftp'],indent=2,separators=(',',' == '))
actual = loader.get('ftp')
print(expected)
print(actual)
self.assertEqual(expected,actual,"Matched")
def test_group_3(self):
loader = ConfigLoader('config.ini', ['production', 'staging','ubuntu'])
expected = {}
expected['ftp'] ={}
expected['ftp']['name'] = 'hello there, ftp uploading'
expected['ftp']['path'] = '/etc/var/uploads'
expected['ftp']['enabled'] = 'no'
expected = json.dumps(expected['ftp'],indent=2,separators=(',',' == '))
actual = loader.get('ftp')
print(expected)
print(actual)
self.assertEqual(expected,actual,"Matched")
def test_group_4(self):
loader = ConfigLoader('config.ini')
expected = {}
expected['ftp'] ={}
expected['ftp']['name'] = 'hello there, ftp uploading'
expected['ftp']['path'] = '/tmp/'
expected['ftp']['enabled'] = 'no'
expected = json.dumps(expected['ftp'],indent=2,separators=(',',' == '))
actual = loader.get('ftp')
print(expected)
print(actual)
self.assertEqual(expected,actual,"Matched")
if __name__ == '__main__':
unittest.main()
| loader = ConfigLoader('config.ini', ['production', 'staging'])
expected = json.dumps(None)
actual = loader.get('common.settings')
print(expected)
print(actual)
self.assertEqual(expected, actual, "Matched") |
config.go | package config
import (
"errors"
"fmt"
"os"
"path"
"path/filepath"
"strings"
"time"
aconfig "github.com/DataDog/datadog-agent/pkg/config" | "github.com/DataDog/datadog-agent/pkg/util/log"
"github.com/DataDog/viper"
)
// ModuleName is a typed alias for string, used only for module names
type ModuleName string
const (
// Namespace is the top-level configuration key that all system-probe settings are nested underneath
Namespace = "system_probe_config"
spNS = Namespace
defaultConfigFileName = "system-probe.yaml"
defaultConnsMessageBatchSize = 600
maxConnsMessageBatchSize = 1000
)
// system-probe module names
const (
NetworkTracerModule ModuleName = "network_tracer"
OOMKillProbeModule ModuleName = "oom_kill_probe"
TCPQueueLengthTracerModule ModuleName = "tcp_queue_length_tracer"
SecurityRuntimeModule ModuleName = "security_runtime"
ProcessModule ModuleName = "process"
)
func key(pieces ...string) string {
return strings.Join(pieces, ".")
}
// Config represents the configuration options for the system-probe
type Config struct {
Enabled bool
EnabledModules map[ModuleName]struct{}
// When the system-probe is enabled in a separate container, we need a way to also disable the system-probe
// packaged in the main agent container (without disabling network collection on the process-agent).
ExternalSystemProbe bool
SocketAddress string
MaxConnsPerMessage int
LogFile string
LogLevel string
DebugPort int
StatsdHost string
StatsdPort int
ProfilingEnabled bool
ProfilingSite string
ProfilingURL string
ProfilingAPIKey string
ProfilingEnvironment string
ProfilingPeriod time.Duration
ProfilingCPUDuration time.Duration
}
// New creates a config object for system-probe. It assumes no configuration has been loaded as this point.
func New(configPath string) (*Config, error) {
aconfig.InitSystemProbeConfig(aconfig.Datadog)
aconfig.Datadog.SetConfigName("system-probe")
// set the paths where a config file is expected
if len(configPath) != 0 {
// if the configuration file path was supplied on the command line,
// add that first so it's first in line
aconfig.Datadog.AddConfigPath(configPath)
// If they set a config file directly, let's try to honor that
if strings.HasSuffix(configPath, ".yaml") {
aconfig.Datadog.SetConfigFile(configPath)
}
}
aconfig.Datadog.AddConfigPath(defaultConfigDir)
_, err := aconfig.LoadWithoutSecret()
var e viper.ConfigFileNotFoundError
if err != nil {
if errors.As(err, &e) || errors.Is(err, os.ErrNotExist) {
log.Infof("no config exists at %s, ignoring...", configPath)
} else {
return nil, err
}
}
return load(configPath)
}
// Merge will merge the system-probe configuration into the existing datadog configuration
func Merge(configPath string) (*Config, error) {
aconfig.InitSystemProbeConfig(aconfig.Datadog)
if configPath != "" {
if !strings.HasSuffix(configPath, ".yaml") {
configPath = path.Join(configPath, defaultConfigFileName)
}
} else {
configPath = path.Join(defaultConfigDir, defaultConfigFileName)
}
if f, err := os.Open(configPath); err == nil {
err = aconfig.Datadog.MergeConfig(f)
_ = f.Close()
if err != nil {
return nil, fmt.Errorf("error merging system-probe config file: %s", err)
}
} else {
log.Infof("no config exists at %s, ignoring...", configPath)
}
return load(configPath)
}
func load(configPath string) (*Config, error) {
cfg := aconfig.Datadog
if err := aconfig.ResolveSecrets(cfg, filepath.Base(configPath)); err != nil {
return nil, err
}
c := &Config{
Enabled: cfg.GetBool(key(spNS, "enabled")),
EnabledModules: make(map[ModuleName]struct{}),
ExternalSystemProbe: cfg.GetBool(key(spNS, "external")),
SocketAddress: cfg.GetString(key(spNS, "sysprobe_socket")),
MaxConnsPerMessage: cfg.GetInt(key(spNS, "max_conns_per_message")),
LogFile: cfg.GetString(key(spNS, "log_file")),
LogLevel: cfg.GetString(key(spNS, "log_level")),
DebugPort: cfg.GetInt(key(spNS, "debug_port")),
StatsdHost: aconfig.GetBindHost(),
StatsdPort: cfg.GetInt("dogstatsd_port"),
ProfilingEnabled: cfg.GetBool(key(spNS, "internal_profiling.enabled")),
ProfilingSite: cfg.GetString(key(spNS, "internal_profiling.site")),
ProfilingURL: cfg.GetString(key(spNS, "internal_profiling.profile_dd_url")),
ProfilingAPIKey: aconfig.SanitizeAPIKey(cfg.GetString(key(spNS, "internal_profiling.api_key"))),
ProfilingEnvironment: cfg.GetString(key(spNS, "internal_profiling.env")),
ProfilingPeriod: cfg.GetDuration(key(spNS, "internal_profiling.period")),
ProfilingCPUDuration: cfg.GetDuration(key(spNS, "internal_profiling.cpu_duration")),
}
if err := ValidateSocketAddress(c.SocketAddress); err != nil {
log.Errorf("Could not parse %s.sysprobe_socket: %s", spNS, err)
c.SocketAddress = defaultSystemProbeAddress
cfg.Set(key(spNS, "sysprobe_socket"), c.SocketAddress)
}
if c.MaxConnsPerMessage > maxConnsMessageBatchSize {
log.Warn("Overriding the configured connections count per message limit because it exceeds maximum")
c.MaxConnsPerMessage = defaultConnsMessageBatchSize
cfg.Set(key(spNS, "max_conns_per_message"), c.MaxConnsPerMessage)
}
// this check must come first so we can accurately tell if system_probe was explicitly enabled
if cfg.GetBool("network_config.enabled") {
log.Info("network_config.enabled detected: enabling system-probe with network module running.")
c.EnabledModules[NetworkTracerModule] = struct{}{}
} else if c.Enabled && !cfg.IsSet("network_config.enabled") {
// This case exists to preserve backwards compatibility. If system_probe_config.enabled is explicitly set to true, and there is no network_config block,
// enable the connections/network check.
log.Info("network_config not found, but system-probe was enabled, enabling network module by default")
c.EnabledModules[NetworkTracerModule] = struct{}{}
}
if cfg.GetBool(key(spNS, "enable_tcp_queue_length")) {
log.Info("system_probe_config.enable_tcp_queue_length detected, will enable system-probe with TCP queue length check")
c.EnabledModules[TCPQueueLengthTracerModule] = struct{}{}
}
if cfg.GetBool(key(spNS, "enable_oom_kill")) {
log.Info("system_probe_config.enable_oom_kill detected, will enable system-probe with OOM Kill check")
c.EnabledModules[OOMKillProbeModule] = struct{}{}
}
if cfg.GetBool("runtime_security_config.enabled") || cfg.GetBool("runtime_security_config.fim_enabled") {
log.Info("runtime_security_config.enabled or runtime_security_config.fim_enabled detected, enabling system-probe")
c.EnabledModules[SecurityRuntimeModule] = struct{}{}
}
if cfg.GetBool(key(spNS, "process_config.enabled")) {
log.Info("process_config.enabled detected, enabling system-probe")
c.EnabledModules[ProcessModule] = struct{}{}
}
if len(c.EnabledModules) > 0 {
c.Enabled = true
}
return c, nil
}
// ModuleIsEnabled returns a bool indicating if the given module name is enabled.
func (c Config) ModuleIsEnabled(modName ModuleName) bool {
_, ok := c.EnabledModules[modName]
return ok
} | |
logger.ts | /**
The default logger logs only `error` and `warn` to console. To provide custom logging from Permissions:
- implement `IPermissionsLogger` methods (or just create a plain JS object with these)
- pass an instance to [`setLogger()`](/miscellaneous/variables.html#setLogger)
```js
import { setLogger, IPermissionsLogger } from '@superawesome/permissions'
class MyLogger implements IPermissionsLogger {
error(message: string, data?: any) {
console.error(message, data);
},
...
}
setLogger(new MyLogger());
// internally its used like this
getLogger().warn('Something smelly!', {data: 'to prove it'})
// but you only really need it if you develop a plugin etc
```
To disable logging completely:
```js
setLogger(null);
``` | */
export interface IPermissionsLogger {
error(message: string, data?: any): void;
warn(message: string, data?: any): void;
debug(message: string, data?: any): void;
}
/**
* @internal
*/
class SADefaultLogger implements IPermissionsLogger {
error(message: string, data?: any) {
console.error(`SA-Permissions ERROR: ${message}`, data);
}
warn(message: string, data?: any) {
console.log(`SA-Permissions WARNING: ${message}`, data);
}
debug(message: string, data?: any) {}
}
/**
* @internal
*/
const nullLogger = new (class SANullLogger implements IPermissionsLogger {
error(message: string, data?: any) {}
warn(message: string, data?: any) {}
debug(message: string, data?: any) {}
})();
/**
* @internal
*/
let logger = new SADefaultLogger();
/**
* Set a **global** logger ([IPermissionsLogger](/interfaces/IPermissionsLogger.html)) used by the library, instead of the console built in one.
*
* Use `setLogger(null)` to disable it.
*
* See [IPermissionsLogger](/interfaces/IPermissionsLogger.html)
*/
export const setLogger = <T extends IPermissionsLogger>(l: T | null): IPermissionsLogger =>
(logger = l);
/**
* Gives you the global logger so you can log eg `getLogger().warn('Something fishy!')`
*
* See [IPermissionsLogger](/interfaces/IPermissionsLogger.html)
*/
export const getLogger = (): IPermissionsLogger => logger || nullLogger; | |
literal_string_slice.rs | fn main () |
fn first_word(s: &str) -> &str {
let bytes = s.as_bytes();
for (index, &character) in bytes.iter().enumerate() {
if character == b' ' {
return &s[..index];
}
}
&s[..]
}
| {
let phrase = String::from("hello world");
let word = first_word(&phrase[..]);
println!("First word: {}", word);
let literal_string_phrase = "hello world";
let word = first_word(&literal_string_phrase[..]);
println!("second First word: {}", word);
let word = first_word(literal_string_phrase);
println!("third First word: {}", word);
} |
op.go | package mssql
import (
"log"
mssql "github.com/denisenkom/go-mssqldb"
"github.com/go-xorm/xorm"
)
func Insert(engine *xorm.Engine, data interface{}) error |
func insertOrUpdate(engine *xorm.Engine, err error, data interface{}) error {
e1, ok := err.(mssql.Error)
if !ok {
return err
}
errNum := e1.SQLErrorNumber()
if errNum != 208 && errNum != 2627 {
log.Println("mssql: insertOrUpdate, errnum=", errNum)
return err
}
//insert
if errNum == 208 {
if e2 := engine.CreateTables(data); e2 != nil {
return e2
}
_, e3 := engine.InsertOne(data)
return e3
} else if errNum == 2627 {
//update
d, _ := data.(*Item)
_, e3 := engine.Where("id = ?", d.Key).Cols("expiresAt", "data").Update(d)
return e3
}
return nil
}
| {
_, err := engine.InsertOne(data)
if err != nil {
//log.Println("mssql: Insert, err=", err)
return insertOrUpdate(engine, err, data)
}
return err
} |
test_brew_views.py | import datetime
import pytest
from flask import url_for
from brewlog.ext import db
from brewlog.models import Brew
from . import BrewlogTests
class BrewViewTests(BrewlogTests):
@pytest.fixture(autouse=True)
def set_up(self, user_factory, brewery_factory):
self.public_user = user_factory(
first_name='John', last_name='Public'
)
self.public_brewery = brewery_factory(
name='public brewery', brewer=self.public_user
)
self.hidden_user = user_factory(
is_public=False, first_name='Rebecca', last_name='Hidden'
)
self.hidden_brewery = brewery_factory(
name='hidden brewery', brewer=self.hidden_user
)
@pytest.mark.usefixtures('client_class')
class TestBrewDetailsView(BrewViewTests):
def url(self, brew):
return url_for('brew.details', brew_id=brew.id)
def test_get_404(self):
rv = self.client.get(url_for('brew.details', brew_id=666))
assert rv.status_code == 404
def test_get_no_access_hidden_brewery(self, brew_factory):
brew = brew_factory(brewery=self.hidden_brewery, name='hb1')
self.login(self.public_user.email)
rv = self.client.get(self.url(brew))
assert rv.status_code == 404
def test_get_no_access_hidden_brew(self, brew_factory):
brew = brew_factory(
brewery=self.public_brewery, is_public=False, name='hb1'
)
self.login(self.hidden_user.email)
rv = self.client.get(self.url(brew))
assert rv.status_code == 404
def test_post_anon(self, brew_factory):
brew = brew_factory(
brewery=self.public_brewery, name='pb1', code='xxx'
)
data = {
'name': brew.name,
'brewery': brew.brewery.id,
'code': '001',
'carbonation_level': 'low',
'carbonation_type': 'bottles with priming',
}
rv = self.client.post(self.url(brew), data=data)
assert rv.status_code == 403
def test_post_non_brewer(self, brew_factory):
brew = brew_factory(
brewery=self.public_brewery, name='pb1', code='xxx'
)
self.login(self.hidden_user.email)
data = {
'name': brew.name,
'brewery': brew.brewery.id,
'code': '001',
'carbonation_level': 'low',
'carbonation_type': 'bottles with priming',
}
rv = self.client.post(self.url(brew), data=data, follow_redirects=True)
assert rv.status_code == 403
def test_post_data_ok(self, brew_factory):
brew = brew_factory(
brewery=self.public_brewery, name='pb1', code='xxx'
)
self.login(self.public_user.email)
data = {
'name': brew.name,
'brewery': brew.brewery.id,
'code': '001',
'carbonation_level': 'low',
'carbonation_type': 'bottles with priming',
}
rv = self.client.post(self.url(brew), data=data, follow_redirects=True)
assert rv.status_code == 200
assert 'data updated' in rv.text
assert Brew.query.get(brew.id).code == data['code']
def test_post_data_missing(self, brew_factory):
brew = brew_factory(brewery=self.public_brewery, name='pb1', code='xxx')
self.login(self.public_user.email)
data = {
'name': None,
'brewery': brew.brewery.id,
'code': '001',
'carbonation_level': 'low',
'carbonation_type': 'bottles with priming',
}
rv = self.client.post(self.url(brew), data=data, follow_redirects=True)
assert rv.status_code == 200
assert 'field is required' in rv.text
assert 'data updated' not in rv.text
def test_state_form_present(self, brew_factory):
brewed = datetime.date(1992, 12, 4)
bottled = datetime.date(1993, 1, 12)
taped = datetime.date(1993, 3, 8)
brew = brew_factory(
brewery=self.public_brewery, name='pb1', date_brewed=brewed,
bottling_date=bottled, tapped=taped
)
self.login(self.public_user.email)
rv = self.client.get(self.url(brew))
assert url_for('brew.chgstate', brew_id=brew.id) in rv.text
def test_attenuation_display_none(self, brew_factory):
brew = brew_factory(brewery=self.public_brewery, name='pb1')
self.login(self.public_user.email)
rv = self.client.get(self.url(brew))
assert 'apparent' not in rv.text
@pytest.mark.usefixtures('client_class')
class TestBrewDetailsNavigation(BrewViewTests):
def url(self, brew):
return url_for('brew.details', brew_id=brew.id)
@pytest.mark.parametrize('anon', [
False, True,
], ids=['authenticated', 'anonymous'])
def test_brew_navigation_non_owner(self, anon, brew_factory):
p2_brew = brew_factory(brewery=self.public_brewery)
p1_brew = brew_factory(brewery=self.public_brewery, is_public=False)
brew = brew_factory(brewery=self.public_brewery)
n1_brew = brew_factory(brewery=self.public_brewery, is_public=False)
n2_brew = brew_factory(brewery=self.public_brewery)
if not anon:
self.login(self.hidden_user.email)
rv = self.client.get(self.url(brew))
assert f'href="{self.url(p2_brew)}"' in rv.text
assert f'href="{self.url(p1_brew)}"' not in rv.text
assert f'href="{self.url(n1_brew)}"' not in rv.text
assert f'href="{self.url(n2_brew)}"' in rv.text
def test_brew_navigation_owner(self, brew_factory):
p1_brew = brew_factory(brewery=self.public_brewery, is_public=False)
brew = brew_factory(brewery=self.public_brewery)
n1_brew = brew_factory(brewery=self.public_brewery, is_public=False)
self.login(self.public_user.email)
rv = self.client.get(self.url(brew))
assert f'href="{self.url(p1_brew)}"' in rv.text
assert f'href="{self.url(n1_brew)}"' in rv.text
@pytest.mark.usefixtures('client_class')
class TestBrewListView(BrewViewTests):
@pytest.fixture(autouse=True)
def set_up2(self):
self.url = url_for('brew.all')
def details_url(self, brew):
return url_for('brew.details', brew_id=brew.id)
def delete_url(self, brew):
return url_for('brew.delete', brew_id=brew.id)
def test_anon(self, brew_factory):
hb_hb = brew_factory(brewery=self.hidden_brewery, is_public=False)
pb_hb = brew_factory(brewery=self.hidden_brewery, is_public=True)
pb_pb = brew_factory(brewery=self.public_brewery, is_public=True)
hb_pb = brew_factory(brewery=self.public_brewery, is_public=False)
rv = self.client.get(self.url)
assert url_for('brew.details', brew_id=pb_pb.id) in rv.text
assert url_for('brew.delete', brew_id=pb_pb.id) not in rv.text
assert url_for('brew.details', brew_id=hb_hb.id) not in rv.text
assert url_for('brew.details', brew_id=pb_hb.id) not in rv.text
assert url_for('brew.details', brew_id=hb_pb.id) not in rv.text
def test_authenticated(self, user_factory, brewery_factory, brew_factory):
user2 = user_factory(first_name='Ivory', last_name='Tower')
brewery2 = brewery_factory(brewer=user2, name='brewery2')
pb1 = brew_factory(brewery=self.public_brewery)
pb2 = brew_factory(brewery=brewery2)
hb1 = brew_factory(name='hidden1', brewery=self.public_brewery, is_public=False)
hb2 = brew_factory(name='hidden2', brewery=brewery2, is_public=False)
hb3 = brew_factory(name='hidden3', brewery=self.hidden_brewery)
hb4 = brew_factory(name='hidden4', brewery=self.hidden_brewery, is_public=False)
self.login(email=self.public_user.email)
rv = self.client.get(self.url)
assert f'href="{self.details_url(pb1)}"' in rv.text
assert f'href="{self.delete_url(pb1)}"' in rv.text
assert f'href="{self.details_url(pb2)}"' in rv.text
assert f'href="{self.delete_url(pb2)}"' not in rv.text
assert f'href="{self.details_url(hb1)}"' in rv.text
assert f'href="{self.details_url(hb2)}"' not in rv.text
assert f'href="{self.details_url(hb3)}"' not in rv.text
assert f'href="{self.details_url(hb4)}"' not in rv.text
@pytest.mark.usefixtures('client_class')
class | (BrewViewTests):
def test_prefetch_anon(self, brew_factory):
brew1 = brew_factory(brewery=self.public_brewery, name='pb1')
brew_factory(brewery=self.hidden_brewery, name='hb2')
rv = self.client.get(url_for('brew.search'))
data = rv.get_json()
assert len(data) == 1
assert data[0]['name'] == brew1.name
def test_prefetch_auth(self, brew_factory):
brew_factory(brewery=self.public_brewery, name='pb1')
brew_h = brew_factory(brewery=self.public_brewery, name='hb2', is_public=False)
self.login(self.public_user.email)
rv = self.client.get(url_for('brew.search'))
data = rv.get_json()
assert len(data) == 2
names = [x['name'] for x in data]
assert brew_h.name in names
def test_search_anon(self, brew_factory):
brew_p = brew_factory(brewery=self.public_brewery, name='pb1')
brew_h = brew_factory(brewery=self.public_brewery, name='hb2', is_public=False)
rv = self.client.get(url_for('brew.search', q=brew_p.name))
data = rv.get_json()
assert len(data) == 1
assert data[0]['name'] == brew_p.name
rv = self.client.get(url_for('brew.search', q=brew_h.name))
data = rv.get_json()
assert len(data) == 0
def test_search_auth(self, brew_factory):
brew_p = brew_factory(brewery=self.public_brewery, name='pb1')
brew_h = brew_factory(brewery=self.public_brewery, name='hb2', is_public=False)
self.login(self.public_user.email)
rv = self.client.get(url_for('brew.search', q=brew_p.name))
data = rv.get_json()
assert len(data) == 1
assert data[0]['name'] == brew_p.name
rv = self.client.get(url_for('brew.search', q=brew_h.name))
data = rv.get_json()
assert len(data) == 1
assert data[0]['name'] == brew_h.name
@pytest.mark.usefixtures('client_class')
class TestStateChangeView(BrewViewTests):
@pytest.fixture(autouse=True)
def set_up2(self, brew_factory):
self.brew = brew_factory(
brewery=self.public_brewery,
name='pale ale',
date_brewed=datetime.date.today() - datetime.timedelta(days=30),
bottling_date=datetime.date.today() - datetime.timedelta(days=10),
)
self.url = url_for('brew.chgstate', brew_id=self.brew.id)
def test_brew_tap_anon(self):
rv = self.client.post(self.url, data={'action': 'tap'})
assert url_for('auth.select') in rv.headers['Location']
def test_brew_tap_nonbrewer(self):
self.login(self.hidden_user.email)
rv = self.client.post(self.url, data={'action': 'tap'}, follow_redirects=True)
assert rv.status_code == 403
assert "You don't have permission to access this page" in rv.text
def test_brew_tap_brewer(self):
self.login(self.public_user.email)
rv = self.client.post(self.url, data={'action': 'tap'}, follow_redirects=True)
assert f'</strong>: {Brew.STATE_TAPPED}' in rv.text
assert 'state changed' in rv.text
def test_brew_untap_brewer(self):
self.brew.tapped = datetime.datetime.today() - datetime.timedelta(days=2)
db.session.add(self.brew)
db.session.commit()
self.login(self.public_user.email)
rv = self.client.post(
self.url, data={'action': 'untap'}, follow_redirects=True
)
assert f'</strong>: {Brew.STATE_MATURING}' in rv.text
assert 'state changed' in rv.text
def test_brew_finish_brewer(self):
self.login(self.public_user.email)
rv = self.client.post(
self.url, data={'action': 'finish'}, follow_redirects=True
)
assert f'</strong>: {Brew.STATE_FINISHED}' in rv.text
assert 'state changed' in rv.text
assert self.brew.tapped is None
def test_invalid_state(self):
self.login(self.public_user.email)
rv = self.client.post(
self.url, data={'action': 'dummy'}, follow_redirects=True
)
assert 'invalid state' in rv.text
@pytest.mark.usefixtures('client_class')
class TestBrewAddView(BrewViewTests):
@pytest.fixture(autouse=True)
def set_up2(self):
self.url = url_for('brew.add')
def test_get_anon(self):
rv = self.client.get(self.url)
assert rv.status_code == 302
assert url_for('auth.select') in rv.headers['location']
def test_get_authenticated(self):
self.login(email=self.public_user.email)
rv = self.client.get(self.url)
assert f'action="{self.url}"' in rv.text
def test_post_anon(self):
data = {
'name': 'pale ale',
'brewery': self.public_brewery.id,
'carbonation_type': 'keg with priming',
'carbonation_level': 'low',
}
rv = self.client.post(self.url, data=data)
assert rv.status_code == 302
assert url_for('auth.select') in rv.headers['location']
def test_post_authenticated_own_brewery(self):
name = 'pale ale'
data = {
'name': name,
'brewery': self.public_brewery.id,
'carbonation_type': 'keg with priming',
'carbonation_level': 'low',
}
self.login(email=self.public_user.email)
rv = self.client.post(self.url, data=data, follow_redirects=True)
assert f'{name} created' in rv.text
def test_post_authenticated_other_brewery(self):
data = {
'name': 'pale ale',
'brewery': self.public_brewery.id,
'carbonation_type': 'keg with priming',
'carbonation_level': 'low',
}
self.login(email=self.hidden_user.email)
rv = self.client.post(self.url, data=data)
assert rv.status_code == 200
assert 'Not a valid choice' in rv.text
assert Brew.query.filter_by(name=data['name']).first() is None
@pytest.mark.usefixtures('client_class')
class TestBrewDeleteView(BrewViewTests):
@pytest.fixture(autouse=True)
def set_up2(self, brew_factory):
self.brew = brew_factory(
brewery=self.public_brewery,
name='pale ale',
date_brewed=datetime.date.today() - datetime.timedelta(days=30),
bottling_date=datetime.date.today() - datetime.timedelta(days=10),
)
self.url = url_for('brew.delete', brew_id=self.brew.id)
def test_get_anon(self):
rv = self.client.get(self.url)
assert rv.status_code == 302
assert url_for('auth.select') in rv.headers['Location']
def test_get_owner(self):
self.login(email=self.public_user.email)
rv = self.client.get(self.url)
assert f'action="{self.url}"' in rv.text
def test_get_non_owner(self):
self.login(email=self.hidden_user.email)
rv = self.client.get(self.url)
assert rv.status_code == 403
def test_post_anon(self):
rv = self.client.post(self.url, data={'delete_it': True})
assert rv.status_code == 302
assert url_for('auth.select') in rv.headers['Location']
assert Brew.query.get(self.brew.id) is not None
def test_post_owner(self):
self.login(email=self.public_user.email)
rv = self.client.post(self.url, data={'delete_it': True}, follow_redirects=True)
assert rv.status_code == 200
assert Brew.query.get(self.brew.id) is None
def test_post_non_owner(self):
self.login(email=self.hidden_user.email)
rv = self.client.post(self.url, data={'delete_it': True}, follow_redirects=True)
assert rv.status_code == 403
| TestJsonViews |
main.go | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// genlocal is a binary for generating gapics locally. It may be used to test out
// new changes, test the generation of a new library, test new generator tweaks, | "context"
"flag"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"cloud.google.com/go/internal/gapicgen"
"cloud.google.com/go/internal/gapicgen/generator"
"golang.org/x/sync/errgroup"
"gopkg.in/src-d/go-git.v4"
)
var (
toolsNeeded = []string{"go", "protoc"}
)
func main() {
log.SetFlags(0)
if err := gapicgen.VerifyAllToolsExist(toolsNeeded); err != nil {
log.Fatal(err)
}
log.Println("creating temp dir")
tmpDir, err := ioutil.TempDir("", "update-genproto")
if err != nil {
log.Fatal(err)
}
log.Printf("temp dir created at %s\n", tmpDir)
googleapisDir := flag.String("googleapis-dir", filepath.Join(tmpDir, "googleapis"), "Directory where sources of googleapis/googleapis resides. If unset the sources will be cloned to a temporary directory that is not cleaned up.")
gocloudDir := flag.String("gocloud-dir", filepath.Join(tmpDir, "gocloud"), "Directory where sources of googleapis/google-cloud-go resides. If unset the sources will be cloned to a temporary directory that is not cleaned up.")
genprotoDir := flag.String("genproto-dir", filepath.Join(tmpDir, "genproto"), "Directory where sources of googleapis/go-genproto resides. If unset the sources will be cloned to a temporary directory that is not cleaned up.")
protoDir := flag.String("proto-dir", filepath.Join(tmpDir, "proto"), "Directory where sources of google/protobuf resides. If unset the sources will be cloned to a temporary directory that is not cleaned up.")
flag.Parse()
ctx := context.Background()
// Clone repositories if needed.
grp, _ := errgroup.WithContext(ctx)
gitClone(grp, "https://github.com/googleapis/googleapis.git", *googleapisDir, tmpDir)
gitClone(grp, "https://github.com/googleapis/go-genproto", *genprotoDir, tmpDir)
gitClone(grp, "https://github.com/googleapis/google-cloud-go", *gocloudDir, tmpDir)
gitClone(grp, "https://github.com/google/protobuf", *protoDir, tmpDir)
if err := grp.Wait(); err != nil {
log.Println(err)
}
// Regen.
if err := generator.Generate(ctx, *googleapisDir, *genprotoDir, *gocloudDir, *protoDir); err != nil {
log.Printf("Generator ran (and failed) in %s\n", tmpDir)
log.Fatal(err)
}
// Log results.
log.Println(genprotoDir)
log.Println(gocloudDir)
}
// gitClone clones a repository in the given directory if dir is not in tmpDir.
func gitClone(eg *errgroup.Group, repo, dir, tmpDir string) {
if !strings.HasPrefix(dir, tmpDir) {
return
}
eg.Go(func() error {
log.Printf("cloning %s\n", repo)
_, err := git.PlainClone(dir, false, &git.CloneOptions{
URL: repo,
Progress: os.Stdout,
})
return err
})
} | // run generators against googleapis-private, and various other local tasks.
package main
import ( |
proximityPlacementGroup.go | // *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
package v20201201
import (
"context"
"reflect"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)
type ProximityPlacementGroup struct {
pulumi.CustomResourceState
AvailabilitySets SubResourceWithColocationStatusResponseArrayOutput `pulumi:"availabilitySets"` | ProximityPlacementGroupType pulumi.StringPtrOutput `pulumi:"proximityPlacementGroupType"`
Tags pulumi.StringMapOutput `pulumi:"tags"`
Type pulumi.StringOutput `pulumi:"type"`
VirtualMachineScaleSets SubResourceWithColocationStatusResponseArrayOutput `pulumi:"virtualMachineScaleSets"`
VirtualMachines SubResourceWithColocationStatusResponseArrayOutput `pulumi:"virtualMachines"`
}
// NewProximityPlacementGroup registers a new resource with the given unique name, arguments, and options.
func NewProximityPlacementGroup(ctx *pulumi.Context,
name string, args *ProximityPlacementGroupArgs, opts ...pulumi.ResourceOption) (*ProximityPlacementGroup, error) {
if args == nil {
return nil, errors.New("missing one or more required arguments")
}
if args.ResourceGroupName == nil {
return nil, errors.New("invalid value for required argument 'ResourceGroupName'")
}
aliases := pulumi.Aliases([]pulumi.Alias{
{
Type: pulumi.String("azure-nextgen:compute/v20201201:ProximityPlacementGroup"),
},
{
Type: pulumi.String("azure-native:compute:ProximityPlacementGroup"),
},
{
Type: pulumi.String("azure-nextgen:compute:ProximityPlacementGroup"),
},
{
Type: pulumi.String("azure-native:compute/v20180401:ProximityPlacementGroup"),
},
{
Type: pulumi.String("azure-nextgen:compute/v20180401:ProximityPlacementGroup"),
},
{
Type: pulumi.String("azure-native:compute/v20180601:ProximityPlacementGroup"),
},
{
Type: pulumi.String("azure-nextgen:compute/v20180601:ProximityPlacementGroup"),
},
{
Type: pulumi.String("azure-native:compute/v20181001:ProximityPlacementGroup"),
},
{
Type: pulumi.String("azure-nextgen:compute/v20181001:ProximityPlacementGroup"),
},
{
Type: pulumi.String("azure-native:compute/v20190301:ProximityPlacementGroup"),
},
{
Type: pulumi.String("azure-nextgen:compute/v20190301:ProximityPlacementGroup"),
},
{
Type: pulumi.String("azure-native:compute/v20190701:ProximityPlacementGroup"),
},
{
Type: pulumi.String("azure-nextgen:compute/v20190701:ProximityPlacementGroup"),
},
{
Type: pulumi.String("azure-native:compute/v20191201:ProximityPlacementGroup"),
},
{
Type: pulumi.String("azure-nextgen:compute/v20191201:ProximityPlacementGroup"),
},
{
Type: pulumi.String("azure-native:compute/v20200601:ProximityPlacementGroup"),
},
{
Type: pulumi.String("azure-nextgen:compute/v20200601:ProximityPlacementGroup"),
},
{
Type: pulumi.String("azure-native:compute/v20210301:ProximityPlacementGroup"),
},
{
Type: pulumi.String("azure-nextgen:compute/v20210301:ProximityPlacementGroup"),
},
{
Type: pulumi.String("azure-native:compute/v20210401:ProximityPlacementGroup"),
},
{
Type: pulumi.String("azure-nextgen:compute/v20210401:ProximityPlacementGroup"),
},
{
Type: pulumi.String("azure-native:compute/v20210701:ProximityPlacementGroup"),
},
{
Type: pulumi.String("azure-nextgen:compute/v20210701:ProximityPlacementGroup"),
},
})
opts = append(opts, aliases)
var resource ProximityPlacementGroup
err := ctx.RegisterResource("azure-native:compute/v20201201:ProximityPlacementGroup", name, args, &resource, opts...)
if err != nil {
return nil, err
}
return &resource, nil
}
// GetProximityPlacementGroup gets an existing ProximityPlacementGroup resource's state with the given name, ID, and optional
// state properties that are used to uniquely qualify the lookup (nil if not required).
func GetProximityPlacementGroup(ctx *pulumi.Context,
name string, id pulumi.IDInput, state *ProximityPlacementGroupState, opts ...pulumi.ResourceOption) (*ProximityPlacementGroup, error) {
var resource ProximityPlacementGroup
err := ctx.ReadResource("azure-native:compute/v20201201:ProximityPlacementGroup", name, id, state, &resource, opts...)
if err != nil {
return nil, err
}
return &resource, nil
}
// Input properties used for looking up and filtering ProximityPlacementGroup resources.
type proximityPlacementGroupState struct {
}
type ProximityPlacementGroupState struct {
}
func (ProximityPlacementGroupState) ElementType() reflect.Type {
return reflect.TypeOf((*proximityPlacementGroupState)(nil)).Elem()
}
type proximityPlacementGroupArgs struct {
ColocationStatus *InstanceViewStatus `pulumi:"colocationStatus"`
Location *string `pulumi:"location"`
ProximityPlacementGroupName *string `pulumi:"proximityPlacementGroupName"`
ProximityPlacementGroupType *string `pulumi:"proximityPlacementGroupType"`
ResourceGroupName string `pulumi:"resourceGroupName"`
Tags map[string]string `pulumi:"tags"`
}
// The set of arguments for constructing a ProximityPlacementGroup resource.
type ProximityPlacementGroupArgs struct {
ColocationStatus InstanceViewStatusPtrInput
Location pulumi.StringPtrInput
ProximityPlacementGroupName pulumi.StringPtrInput
ProximityPlacementGroupType pulumi.StringPtrInput
ResourceGroupName pulumi.StringInput
Tags pulumi.StringMapInput
}
func (ProximityPlacementGroupArgs) ElementType() reflect.Type {
return reflect.TypeOf((*proximityPlacementGroupArgs)(nil)).Elem()
}
type ProximityPlacementGroupInput interface {
pulumi.Input
ToProximityPlacementGroupOutput() ProximityPlacementGroupOutput
ToProximityPlacementGroupOutputWithContext(ctx context.Context) ProximityPlacementGroupOutput
}
func (*ProximityPlacementGroup) ElementType() reflect.Type {
return reflect.TypeOf((*ProximityPlacementGroup)(nil))
}
func (i *ProximityPlacementGroup) ToProximityPlacementGroupOutput() ProximityPlacementGroupOutput {
return i.ToProximityPlacementGroupOutputWithContext(context.Background())
}
func (i *ProximityPlacementGroup) ToProximityPlacementGroupOutputWithContext(ctx context.Context) ProximityPlacementGroupOutput {
return pulumi.ToOutputWithContext(ctx, i).(ProximityPlacementGroupOutput)
}
type ProximityPlacementGroupOutput struct{ *pulumi.OutputState }
func (ProximityPlacementGroupOutput) ElementType() reflect.Type {
return reflect.TypeOf((*ProximityPlacementGroup)(nil))
}
func (o ProximityPlacementGroupOutput) ToProximityPlacementGroupOutput() ProximityPlacementGroupOutput {
return o
}
func (o ProximityPlacementGroupOutput) ToProximityPlacementGroupOutputWithContext(ctx context.Context) ProximityPlacementGroupOutput {
return o
}
func init() {
pulumi.RegisterOutputType(ProximityPlacementGroupOutput{})
} | ColocationStatus InstanceViewStatusResponsePtrOutput `pulumi:"colocationStatus"`
Location pulumi.StringOutput `pulumi:"location"`
Name pulumi.StringOutput `pulumi:"name"` |
usecase.go | package usecases
import (
"context"
"github.com/matheusmosca/walrus/domain/entities"
"github.com/matheusmosca/walrus/domain/vos"
)
type topics map[vos.TopicName]entities.Topic
type useCase struct {
storage Repository
topics topics
}
//go:generate moq -fmt goimports -out repository_mock.go . Repository:RepositoryMock
type Repository interface {
CreateTopic(ctx context.Context, name vos.TopicName, topic entities.Topic) error
GetTopic(ctx context.Context, topicName vos.TopicName) (entities.Topic, error)
ListTopics(ctx context.Context) ([]entities.Topic, error)
}
type UseCase interface { | Subscribe(ctx context.Context, topicName vos.TopicName) (chan vos.Message, vos.SubscriberID, error)
ListTopics(ctx context.Context) ([]entities.Topic, error)
}
func New(storage Repository) UseCase {
return useCase{
storage: storage,
topics: make(topics),
}
} | Publish(ctx context.Context, message vos.Message) error
Unsubscribe(ctx context.Context, subscriberID vos.SubscriberID, topicName vos.TopicName) error |
aws_test.go | /*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package aws
import (
"io"
"reflect"
"strings"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/elb"
"github.com/aws/aws-sdk-go/service/autoscaling"
"github.com/golang/glog"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/kubernetes/pkg/api/v1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"k8s.io/apimachinery/pkg/types"
kubeletapis "k8s.io/kubernetes/pkg/kubelet/apis"
)
const TestClusterId = "clusterid.test"
const TestClusterName = "testCluster"
func TestReadAWSCloudConfig(t *testing.T) {
tests := []struct {
name string
reader io.Reader
aws Services
expectError bool
zone string
}{
{
"No config reader",
nil, nil,
true, "",
},
{
"Empty config, no metadata",
strings.NewReader(""), nil,
true, "",
},
{
"No zone in config, no metadata",
strings.NewReader("[global]\n"), nil,
true, "",
},
{
"Zone in config, no metadata",
strings.NewReader("[global]\nzone = eu-west-1a"), nil,
false, "eu-west-1a",
},
{
"No zone in config, metadata does not have zone",
strings.NewReader("[global]\n"), NewFakeAWSServices().withAz(""),
true, "",
},
{
"No zone in config, metadata has zone",
strings.NewReader("[global]\n"), NewFakeAWSServices(),
false, "us-east-1a",
},
{
"Zone in config should take precedence over metadata",
strings.NewReader("[global]\nzone = eu-west-1a"), NewFakeAWSServices(),
false, "eu-west-1a",
},
}
for _, test := range tests {
t.Logf("Running test case %s", test.name)
var metadata EC2Metadata
if test.aws != nil {
metadata, _ = test.aws.Metadata()
}
cfg, err := readAWSCloudConfig(test.reader, metadata)
if test.expectError {
if err == nil {
t.Errorf("Should error for case %s (cfg=%v)", test.name, cfg)
}
} else {
if err != nil {
t.Errorf("Should succeed for case: %s", test.name)
}
if cfg.Global.Zone != test.zone {
t.Errorf("Incorrect zone value (%s vs %s) for case: %s",
cfg.Global.Zone, test.zone, test.name)
}
}
}
}
type FakeAWSServices struct {
region string
instances []*ec2.Instance
selfInstance *ec2.Instance
networkInterfacesMacs []string
networkInterfacesVpcIDs []string
ec2 *FakeEC2
elb *FakeELB
asg *FakeASG
metadata *FakeMetadata
}
func NewFakeAWSServices() *FakeAWSServices {
s := &FakeAWSServices{}
s.region = "us-east-1"
s.ec2 = &FakeEC2{aws: s}
s.elb = &FakeELB{aws: s}
s.asg = &FakeASG{aws: s}
s.metadata = &FakeMetadata{aws: s}
s.networkInterfacesMacs = []string{"aa:bb:cc:dd:ee:00", "aa:bb:cc:dd:ee:01"}
s.networkInterfacesVpcIDs = []string{"vpc-mac0", "vpc-mac1"}
selfInstance := &ec2.Instance{}
selfInstance.InstanceId = aws.String("i-self")
selfInstance.Placement = &ec2.Placement{
AvailabilityZone: aws.String("us-east-1a"),
}
selfInstance.PrivateDnsName = aws.String("ip-172-20-0-100.ec2.internal")
selfInstance.PrivateIpAddress = aws.String("192.168.0.1")
selfInstance.PublicIpAddress = aws.String("1.2.3.4")
s.selfInstance = selfInstance
s.instances = []*ec2.Instance{selfInstance}
var tag ec2.Tag
tag.Key = aws.String(TagNameKubernetesClusterLegacy)
tag.Value = aws.String(TestClusterId)
selfInstance.Tags = []*ec2.Tag{&tag}
return s
}
func (s *FakeAWSServices) withAz(az string) *FakeAWSServices {
if s.selfInstance.Placement == nil {
s.selfInstance.Placement = &ec2.Placement{}
}
s.selfInstance.Placement.AvailabilityZone = aws.String(az)
return s
}
func (s *FakeAWSServices) Compute(region string) (EC2, error) {
return s.ec2, nil
}
func (s *FakeAWSServices) LoadBalancing(region string) (ELB, error) {
return s.elb, nil
}
func (s *FakeAWSServices) Autoscaling(region string) (ASG, error) {
return s.asg, nil
}
func (s *FakeAWSServices) Metadata() (EC2Metadata, error) {
return s.metadata, nil
}
func TestNewAWSCloud(t *testing.T) {
tests := []struct {
name string
reader io.Reader
awsServices Services
expectError bool
region string
}{
{
"No config reader",
nil, NewFakeAWSServices().withAz(""),
true, "",
},
{
"Config specifies valid zone",
strings.NewReader("[global]\nzone = eu-west-1a"), NewFakeAWSServices(),
false, "eu-west-1",
},
{
"Gets zone from metadata when not in config",
strings.NewReader("[global]\n"),
NewFakeAWSServices(),
false, "us-east-1",
},
{
"No zone in config or metadata",
strings.NewReader("[global]\n"),
NewFakeAWSServices().withAz(""),
true, "",
},
}
for _, test := range tests {
t.Logf("Running test case %s", test.name)
c, err := newAWSCloud(test.reader, test.awsServices)
if test.expectError {
if err == nil {
t.Errorf("Should error for case %s", test.name)
}
} else {
if err != nil {
t.Errorf("Should succeed for case: %s, got %v", test.name, err)
} else if c.region != test.region {
t.Errorf("Incorrect region value (%s vs %s) for case: %s",
c.region, test.region, test.name)
}
}
}
}
type FakeEC2 struct {
aws *FakeAWSServices
Subnets []*ec2.Subnet
DescribeSubnetsInput *ec2.DescribeSubnetsInput
RouteTables []*ec2.RouteTable
DescribeRouteTablesInput *ec2.DescribeRouteTablesInput
mock.Mock
}
func contains(haystack []*string, needle string) bool {
for _, s := range haystack {
// (deliberately panic if s == nil)
if needle == *s {
return true
}
}
return false
}
func instanceMatchesFilter(instance *ec2.Instance, filter *ec2.Filter) bool {
name := *filter.Name
if name == "private-dns-name" {
if instance.PrivateDnsName == nil {
return false
}
return contains(filter.Values, *instance.PrivateDnsName)
}
if name == "instance-state-name" {
return contains(filter.Values, *instance.State.Name)
}
if name == "tag-key" {
for _, instanceTag := range instance.Tags {
if contains(filter.Values, aws.StringValue(instanceTag.Key)) {
return true
}
}
return false
}
if strings.HasPrefix(name, "tag:") {
tagName := name[4:]
for _, instanceTag := range instance.Tags {
if aws.StringValue(instanceTag.Key) == tagName && contains(filter.Values, aws.StringValue(instanceTag.Value)) {
return true
}
}
return false
}
panic("Unknown filter name: " + name)
}
func (self *FakeEC2) DescribeInstances(request *ec2.DescribeInstancesInput) ([]*ec2.Instance, error) {
matches := []*ec2.Instance{}
for _, instance := range self.aws.instances {
if request.InstanceIds != nil {
if instance.InstanceId == nil {
glog.Warning("Instance with no instance id: ", instance)
continue
}
found := false
for _, instanceID := range request.InstanceIds {
if *instanceID == *instance.InstanceId {
found = true
break
}
}
if !found {
continue
}
}
if request.Filters != nil {
allMatch := true
for _, filter := range request.Filters {
if !instanceMatchesFilter(instance, filter) {
allMatch = false
break
}
}
if !allMatch {
continue
}
}
matches = append(matches, instance)
}
return matches, nil
}
func (self *FakeEC2) DescribeAddresses(request *ec2.DescribeAddressesInput) ([]*ec2.Address, error) {
addresses := []*ec2.Address{}
return addresses, nil
}
type FakeMetadata struct {
aws *FakeAWSServices
}
func (self *FakeMetadata) GetMetadata(key string) (string, error) {
networkInterfacesPrefix := "network/interfaces/macs/"
i := self.aws.selfInstance
if key == "placement/availability-zone" {
az := ""
if i.Placement != nil {
az = aws.StringValue(i.Placement.AvailabilityZone)
}
return az, nil
} else if key == "instance-id" {
return aws.StringValue(i.InstanceId), nil
} else if key == "local-hostname" {
return aws.StringValue(i.PrivateDnsName), nil
} else if key == "public-hostname" {
return aws.StringValue(i.PublicDnsName), nil
} else if key == "local-ipv4" {
return aws.StringValue(i.PrivateIpAddress), nil
} else if key == "public-ipv4" {
return aws.StringValue(i.PublicIpAddress), nil
} else if strings.HasPrefix(key, networkInterfacesPrefix) {
if key == networkInterfacesPrefix {
return strings.Join(self.aws.networkInterfacesMacs, "/\n") + "/\n", nil
} else {
keySplit := strings.Split(key, "/")
macParam := keySplit[3]
if len(keySplit) == 5 && keySplit[4] == "vpc-id" {
for i, macElem := range self.aws.networkInterfacesMacs {
if macParam == macElem {
return self.aws.networkInterfacesVpcIDs[i], nil
}
}
}
return "", nil
}
} else {
return "", nil
}
}
func (ec2 *FakeEC2) AttachVolume(request *ec2.AttachVolumeInput) (resp *ec2.VolumeAttachment, err error) {
panic("Not implemented")
}
func (ec2 *FakeEC2) DetachVolume(request *ec2.DetachVolumeInput) (resp *ec2.VolumeAttachment, err error) {
panic("Not implemented")
}
func (e *FakeEC2) DescribeVolumes(request *ec2.DescribeVolumesInput) ([]*ec2.Volume, error) {
args := e.Called(request)
return args.Get(0).([]*ec2.Volume), nil
}
func (ec2 *FakeEC2) CreateVolume(request *ec2.CreateVolumeInput) (resp *ec2.Volume, err error) {
panic("Not implemented")
}
func (ec2 *FakeEC2) DeleteVolume(request *ec2.DeleteVolumeInput) (resp *ec2.DeleteVolumeOutput, err error) {
panic("Not implemented")
}
func (ec2 *FakeEC2) DescribeSecurityGroups(request *ec2.DescribeSecurityGroupsInput) ([]*ec2.SecurityGroup, error) {
panic("Not implemented")
}
func (ec2 *FakeEC2) CreateSecurityGroup(*ec2.CreateSecurityGroupInput) (*ec2.CreateSecurityGroupOutput, error) {
panic("Not implemented")
}
func (ec2 *FakeEC2) DeleteSecurityGroup(*ec2.DeleteSecurityGroupInput) (*ec2.DeleteSecurityGroupOutput, error) {
panic("Not implemented")
}
func (ec2 *FakeEC2) AuthorizeSecurityGroupIngress(*ec2.AuthorizeSecurityGroupIngressInput) (*ec2.AuthorizeSecurityGroupIngressOutput, error) {
panic("Not implemented")
}
func (ec2 *FakeEC2) RevokeSecurityGroupIngress(*ec2.RevokeSecurityGroupIngressInput) (*ec2.RevokeSecurityGroupIngressOutput, error) {
panic("Not implemented")
}
func (ec2 *FakeEC2) DescribeSubnets(request *ec2.DescribeSubnetsInput) ([]*ec2.Subnet, error) {
ec2.DescribeSubnetsInput = request
return ec2.Subnets, nil
}
func (ec2 *FakeEC2) CreateTags(*ec2.CreateTagsInput) (*ec2.CreateTagsOutput, error) {
panic("Not implemented")
}
func (ec2 *FakeEC2) DescribeRouteTables(request *ec2.DescribeRouteTablesInput) ([]*ec2.RouteTable, error) {
ec2.DescribeRouteTablesInput = request
return ec2.RouteTables, nil
}
func (s *FakeEC2) CreateRoute(request *ec2.CreateRouteInput) (*ec2.CreateRouteOutput, error) {
panic("Not implemented")
}
func (s *FakeEC2) DeleteRoute(request *ec2.DeleteRouteInput) (*ec2.DeleteRouteOutput, error) {
panic("Not implemented")
}
func (s *FakeEC2) ModifyInstanceAttribute(request *ec2.ModifyInstanceAttributeInput) (*ec2.ModifyInstanceAttributeOutput, error) {
panic("Not implemented")
}
type FakeELB struct {
aws *FakeAWSServices
mock.Mock
}
func (ec2 *FakeELB) CreateLoadBalancer(*elb.CreateLoadBalancerInput) (*elb.CreateLoadBalancerOutput, error) {
panic("Not implemented")
}
func (ec2 *FakeELB) DeleteLoadBalancer(input *elb.DeleteLoadBalancerInput) (*elb.DeleteLoadBalancerOutput, error) {
panic("Not implemented")
}
func (ec2 *FakeELB) DescribeLoadBalancers(input *elb.DescribeLoadBalancersInput) (*elb.DescribeLoadBalancersOutput, error) {
args := ec2.Called(input)
return args.Get(0).(*elb.DescribeLoadBalancersOutput), nil
}
func (ec2 *FakeELB) RegisterInstancesWithLoadBalancer(*elb.RegisterInstancesWithLoadBalancerInput) (*elb.RegisterInstancesWithLoadBalancerOutput, error) {
panic("Not implemented")
}
func (ec2 *FakeELB) DeregisterInstancesFromLoadBalancer(*elb.DeregisterInstancesFromLoadBalancerInput) (*elb.DeregisterInstancesFromLoadBalancerOutput, error) {
panic("Not implemented")
}
func (ec2 *FakeELB) DetachLoadBalancerFromSubnets(*elb.DetachLoadBalancerFromSubnetsInput) (*elb.DetachLoadBalancerFromSubnetsOutput, error) {
panic("Not implemented")
}
func (ec2 *FakeELB) AttachLoadBalancerToSubnets(*elb.AttachLoadBalancerToSubnetsInput) (*elb.AttachLoadBalancerToSubnetsOutput, error) {
panic("Not implemented")
}
func (ec2 *FakeELB) CreateLoadBalancerListeners(*elb.CreateLoadBalancerListenersInput) (*elb.CreateLoadBalancerListenersOutput, error) {
panic("Not implemented")
}
func (ec2 *FakeELB) DeleteLoadBalancerListeners(*elb.DeleteLoadBalancerListenersInput) (*elb.DeleteLoadBalancerListenersOutput, error) {
panic("Not implemented")
}
func (ec2 *FakeELB) ApplySecurityGroupsToLoadBalancer(*elb.ApplySecurityGroupsToLoadBalancerInput) (*elb.ApplySecurityGroupsToLoadBalancerOutput, error) {
panic("Not implemented")
}
func (elb *FakeELB) ConfigureHealthCheck(*elb.ConfigureHealthCheckInput) (*elb.ConfigureHealthCheckOutput, error) {
panic("Not implemented")
}
func (elb *FakeELB) CreateLoadBalancerPolicy(*elb.CreateLoadBalancerPolicyInput) (*elb.CreateLoadBalancerPolicyOutput, error) {
panic("Not implemented")
}
func (elb *FakeELB) SetLoadBalancerPoliciesForBackendServer(*elb.SetLoadBalancerPoliciesForBackendServerInput) (*elb.SetLoadBalancerPoliciesForBackendServerOutput, error) {
panic("Not implemented")
}
func (elb *FakeELB) DescribeLoadBalancerAttributes(*elb.DescribeLoadBalancerAttributesInput) (*elb.DescribeLoadBalancerAttributesOutput, error) {
panic("Not implemented")
}
func (elb *FakeELB) ModifyLoadBalancerAttributes(*elb.ModifyLoadBalancerAttributesInput) (*elb.ModifyLoadBalancerAttributesOutput, error) {
panic("Not implemented")
}
type FakeASG struct {
aws *FakeAWSServices
}
func (a *FakeASG) UpdateAutoScalingGroup(*autoscaling.UpdateAutoScalingGroupInput) (*autoscaling.UpdateAutoScalingGroupOutput, error) {
panic("Not implemented")
}
func (a *FakeASG) DescribeAutoScalingGroups(*autoscaling.DescribeAutoScalingGroupsInput) (*autoscaling.DescribeAutoScalingGroupsOutput, error) {
panic("Not implemented")
}
func mockInstancesResp(selfInstance *ec2.Instance, instances []*ec2.Instance) (*Cloud, *FakeAWSServices) {
awsServices := NewFakeAWSServices()
awsServices.instances = instances
awsServices.selfInstance = selfInstance
awsCloud, err := newAWSCloud(nil, awsServices)
if err != nil {
panic(err)
}
return awsCloud, awsServices
}
func mockAvailabilityZone(availabilityZone string) *Cloud {
awsServices := NewFakeAWSServices().withAz(availabilityZone)
awsCloud, err := newAWSCloud(nil, awsServices)
if err != nil {
panic(err)
}
return awsCloud
}
func testHasNodeAddress(t *testing.T, addrs []v1.NodeAddress, addressType v1.NodeAddressType, address string) {
for _, addr := range addrs {
if addr.Type == addressType && addr.Address == address {
return
}
}
t.Errorf("Did not find expected address: %s:%s in %v", addressType, address, addrs)
}
func TestNodeAddresses(t *testing.T) {
// Note these instances have the same name
// (we test that this produces an error)
var instance0 ec2.Instance
var instance1 ec2.Instance
var instance2 ec2.Instance
//0
instance0.InstanceId = aws.String("i-0")
instance0.PrivateDnsName = aws.String("instance-same.ec2.internal")
instance0.PrivateIpAddress = aws.String("192.168.0.1")
instance0.PublicDnsName = aws.String("instance-same.ec2.external")
instance0.PublicIpAddress = aws.String("1.2.3.4")
instance0.InstanceType = aws.String("c3.large")
instance0.Placement = &ec2.Placement{AvailabilityZone: aws.String("us-east-1a")}
state0 := ec2.InstanceState{
Name: aws.String("running"),
}
instance0.State = &state0
//1
instance1.InstanceId = aws.String("i-1")
instance1.PrivateDnsName = aws.String("instance-same.ec2.internal")
instance1.PrivateIpAddress = aws.String("192.168.0.2")
instance1.InstanceType = aws.String("c3.large")
instance1.Placement = &ec2.Placement{AvailabilityZone: aws.String("us-east-1a")}
state1 := ec2.InstanceState{
Name: aws.String("running"),
}
instance1.State = &state1
//2
instance2.InstanceId = aws.String("i-2")
instance2.PrivateDnsName = aws.String("instance-other.ec2.internal")
instance2.PrivateIpAddress = aws.String("192.168.0.1")
instance2.PublicIpAddress = aws.String("1.2.3.4")
instance2.InstanceType = aws.String("c3.large")
instance2.Placement = &ec2.Placement{AvailabilityZone: aws.String("us-east-1a")}
state2 := ec2.InstanceState{
Name: aws.String("running"),
}
instance2.State = &state2
instances := []*ec2.Instance{&instance0, &instance1, &instance2}
aws1, _ := mockInstancesResp(&instance0, []*ec2.Instance{&instance0})
_, err1 := aws1.NodeAddresses("instance-mismatch.ec2.internal")
if err1 == nil {
t.Errorf("Should error when no instance found")
}
aws2, _ := mockInstancesResp(&instance2, instances)
_, err2 := aws2.NodeAddresses("instance-same.ec2.internal")
if err2 == nil {
t.Errorf("Should error when multiple instances found")
}
aws3, _ := mockInstancesResp(&instance0, instances[0:1])
addrs3, err3 := aws3.NodeAddresses("instance-same.ec2.internal")
if err3 != nil {
t.Errorf("Should not error when instance found")
}
if len(addrs3) != 4 {
t.Errorf("Should return exactly 4 NodeAddresses")
}
testHasNodeAddress(t, addrs3, v1.NodeInternalIP, "192.168.0.1")
testHasNodeAddress(t, addrs3, v1.NodeExternalIP, "1.2.3.4")
testHasNodeAddress(t, addrs3, v1.NodeExternalDNS, "instance-same.ec2.external")
testHasNodeAddress(t, addrs3, v1.NodeInternalDNS, "instance-same.ec2.internal")
// Fetch from metadata
aws4, fakeServices := mockInstancesResp(&instance0, []*ec2.Instance{&instance0})
fakeServices.selfInstance.PublicIpAddress = aws.String("2.3.4.5")
fakeServices.selfInstance.PrivateIpAddress = aws.String("192.168.0.2")
addrs4, err4 := aws4.NodeAddresses(mapInstanceToNodeName(&instance0))
if err4 != nil {
t.Errorf("unexpected error: %v", err4)
}
testHasNodeAddress(t, addrs4, v1.NodeInternalIP, "192.168.0.2")
testHasNodeAddress(t, addrs4, v1.NodeExternalIP, "2.3.4.5")
}
func TestGetRegion(t *testing.T) {
aws := mockAvailabilityZone("us-west-2e")
zones, ok := aws.Zones()
if !ok {
t.Fatalf("Unexpected missing zones impl")
}
zone, err := zones.GetZone()
if err != nil {
t.Fatalf("unexpected error %v", err)
}
if zone.Region != "us-west-2" {
t.Errorf("Unexpected region: %s", zone.Region)
}
if zone.FailureDomain != "us-west-2e" {
t.Errorf("Unexpected FailureDomain: %s", zone.FailureDomain)
}
}
func TestFindVPCID(t *testing.T) {
awsServices := NewFakeAWSServices()
c, err := newAWSCloud(strings.NewReader("[global]"), awsServices)
if err != nil {
t.Errorf("Error building aws cloud: %v", err)
return
}
vpcID, err := c.findVPCID()
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if vpcID != "vpc-mac0" {
t.Errorf("Unexpected vpcID: %s", vpcID)
}
}
func constructSubnets(subnetsIn map[int]map[string]string) (subnetsOut []*ec2.Subnet) {
for i := range subnetsIn {
subnetsOut = append(
subnetsOut,
constructSubnet(
subnetsIn[i]["id"],
subnetsIn[i]["az"],
),
)
}
return
}
func constructSubnet(id string, az string) *ec2.Subnet {
return &ec2.Subnet{
SubnetId: &id,
AvailabilityZone: &az,
}
}
func constructRouteTables(routeTablesIn map[string]bool) (routeTablesOut []*ec2.RouteTable) |
func constructRouteTable(subnetID string, public bool) *ec2.RouteTable {
var gatewayID string
if public {
gatewayID = "igw-" + subnetID[len(subnetID)-8:8]
} else {
gatewayID = "vgw-" + subnetID[len(subnetID)-8:8]
}
return &ec2.RouteTable{
Associations: []*ec2.RouteTableAssociation{{SubnetId: aws.String(subnetID)}},
Routes: []*ec2.Route{{
DestinationCidrBlock: aws.String("0.0.0.0/0"),
GatewayId: aws.String(gatewayID),
}},
}
}
func TestSubnetIDsinVPC(t *testing.T) {
awsServices := NewFakeAWSServices()
c, err := newAWSCloud(strings.NewReader("[global]"), awsServices)
if err != nil {
t.Errorf("Error building aws cloud: %v", err)
return
}
// test with 3 subnets from 3 different AZs
subnets := make(map[int]map[string]string)
subnets[0] = make(map[string]string)
subnets[0]["id"] = "subnet-a0000001"
subnets[0]["az"] = "af-south-1a"
subnets[1] = make(map[string]string)
subnets[1]["id"] = "subnet-b0000001"
subnets[1]["az"] = "af-south-1b"
subnets[2] = make(map[string]string)
subnets[2]["id"] = "subnet-c0000001"
subnets[2]["az"] = "af-south-1c"
awsServices.ec2.Subnets = constructSubnets(subnets)
routeTables := map[string]bool{
"subnet-a0000001": true,
"subnet-b0000001": true,
"subnet-c0000001": true,
}
awsServices.ec2.RouteTables = constructRouteTables(routeTables)
result, err := c.findELBSubnets(false)
if err != nil {
t.Errorf("Error listing subnets: %v", err)
return
}
if len(result) != 3 {
t.Errorf("Expected 3 subnets but got %d", len(result))
return
}
result_set := make(map[string]bool)
for _, v := range result {
result_set[v] = true
}
for i := range subnets {
if !result_set[subnets[i]["id"]] {
t.Errorf("Expected subnet%d '%s' in result: %v", i, subnets[i]["id"], result)
return
}
}
// test implicit routing table - when subnets are not explicitly linked to a table they should use main
awsServices.ec2.RouteTables = constructRouteTables(map[string]bool{})
result, err = c.findELBSubnets(false)
if err != nil {
t.Errorf("Error listing subnets: %v", err)
return
}
if len(result) != 3 {
t.Errorf("Expected 3 subnets but got %d", len(result))
return
}
result_set = make(map[string]bool)
for _, v := range result {
result_set[v] = true
}
for i := range subnets {
if !result_set[subnets[i]["id"]] {
t.Errorf("Expected subnet%d '%s' in result: %v", i, subnets[i]["id"], result)
return
}
}
// test with 4 subnets from 3 different AZs
// add duplicate az subnet
subnets[3] = make(map[string]string)
subnets[3]["id"] = "subnet-c0000002"
subnets[3]["az"] = "af-south-1c"
awsServices.ec2.Subnets = constructSubnets(subnets)
routeTables["subnet-c0000002"] = true
awsServices.ec2.RouteTables = constructRouteTables(routeTables)
result, err = c.findELBSubnets(false)
if err != nil {
t.Errorf("Error listing subnets: %v", err)
return
}
if len(result) != 3 {
t.Errorf("Expected 3 subnets but got %d", len(result))
return
}
// test with 6 subnets from 3 different AZs
// with 3 private subnets
subnets[4] = make(map[string]string)
subnets[4]["id"] = "subnet-d0000001"
subnets[4]["az"] = "af-south-1a"
subnets[5] = make(map[string]string)
subnets[5]["id"] = "subnet-d0000002"
subnets[5]["az"] = "af-south-1b"
awsServices.ec2.Subnets = constructSubnets(subnets)
routeTables["subnet-a0000001"] = false
routeTables["subnet-b0000001"] = false
routeTables["subnet-c0000001"] = false
routeTables["subnet-c0000002"] = true
routeTables["subnet-d0000001"] = true
routeTables["subnet-d0000002"] = true
awsServices.ec2.RouteTables = constructRouteTables(routeTables)
result, err = c.findELBSubnets(false)
if err != nil {
t.Errorf("Error listing subnets: %v", err)
return
}
if len(result) != 3 {
t.Errorf("Expected 3 subnets but got %d", len(result))
return
}
expected := []*string{aws.String("subnet-c0000002"), aws.String("subnet-d0000001"), aws.String("subnet-d0000002")}
for _, s := range result {
if !contains(expected, s) {
t.Errorf("Unexpected subnet '%s' found", s)
return
}
}
}
func TestIpPermissionExistsHandlesMultipleGroupIds(t *testing.T) {
oldIpPermission := ec2.IpPermission{
UserIdGroupPairs: []*ec2.UserIdGroupPair{
{GroupId: aws.String("firstGroupId")},
{GroupId: aws.String("secondGroupId")},
{GroupId: aws.String("thirdGroupId")},
},
}
existingIpPermission := ec2.IpPermission{
UserIdGroupPairs: []*ec2.UserIdGroupPair{
{GroupId: aws.String("secondGroupId")},
},
}
newIpPermission := ec2.IpPermission{
UserIdGroupPairs: []*ec2.UserIdGroupPair{
{GroupId: aws.String("fourthGroupId")},
},
}
equals := ipPermissionExists(&existingIpPermission, &oldIpPermission, false)
if !equals {
t.Errorf("Should have been considered equal since first is in the second array of groups")
}
equals = ipPermissionExists(&newIpPermission, &oldIpPermission, false)
if equals {
t.Errorf("Should have not been considered equal since first is not in the second array of groups")
}
}
func TestIpPermissionExistsHandlesRangeSubsets(t *testing.T) {
// Two existing scenarios we'll test against
emptyIpPermission := ec2.IpPermission{}
oldIpPermission := ec2.IpPermission{
IpRanges: []*ec2.IpRange{
{CidrIp: aws.String("10.0.0.0/8")},
{CidrIp: aws.String("192.168.1.0/24")},
},
}
// Two already existing ranges and a new one
existingIpPermission := ec2.IpPermission{
IpRanges: []*ec2.IpRange{
{CidrIp: aws.String("10.0.0.0/8")},
},
}
existingIpPermission2 := ec2.IpPermission{
IpRanges: []*ec2.IpRange{
{CidrIp: aws.String("192.168.1.0/24")},
},
}
newIpPermission := ec2.IpPermission{
IpRanges: []*ec2.IpRange{
{CidrIp: aws.String("172.16.0.0/16")},
},
}
exists := ipPermissionExists(&emptyIpPermission, &emptyIpPermission, false)
if !exists {
t.Errorf("Should have been considered existing since we're comparing a range array against itself")
}
exists = ipPermissionExists(&oldIpPermission, &oldIpPermission, false)
if !exists {
t.Errorf("Should have been considered existing since we're comparing a range array against itself")
}
exists = ipPermissionExists(&existingIpPermission, &oldIpPermission, false)
if !exists {
t.Errorf("Should have been considered existing since 10.* is in oldIpPermission's array of ranges")
}
exists = ipPermissionExists(&existingIpPermission2, &oldIpPermission, false)
if !exists {
t.Errorf("Should have been considered existing since 192.* is in oldIpPermission2's array of ranges")
}
exists = ipPermissionExists(&newIpPermission, &emptyIpPermission, false)
if exists {
t.Errorf("Should have not been considered existing since we compared against a missing array of ranges")
}
exists = ipPermissionExists(&newIpPermission, &oldIpPermission, false)
if exists {
t.Errorf("Should have not been considered existing since 172.* is not in oldIpPermission's array of ranges")
}
}
func TestIpPermissionExistsHandlesMultipleGroupIdsWithUserIds(t *testing.T) {
oldIpPermission := ec2.IpPermission{
UserIdGroupPairs: []*ec2.UserIdGroupPair{
{GroupId: aws.String("firstGroupId"), UserId: aws.String("firstUserId")},
{GroupId: aws.String("secondGroupId"), UserId: aws.String("secondUserId")},
{GroupId: aws.String("thirdGroupId"), UserId: aws.String("thirdUserId")},
},
}
existingIpPermission := ec2.IpPermission{
UserIdGroupPairs: []*ec2.UserIdGroupPair{
{GroupId: aws.String("secondGroupId"), UserId: aws.String("secondUserId")},
},
}
newIpPermission := ec2.IpPermission{
UserIdGroupPairs: []*ec2.UserIdGroupPair{
{GroupId: aws.String("secondGroupId"), UserId: aws.String("anotherUserId")},
},
}
equals := ipPermissionExists(&existingIpPermission, &oldIpPermission, true)
if !equals {
t.Errorf("Should have been considered equal since first is in the second array of groups")
}
equals = ipPermissionExists(&newIpPermission, &oldIpPermission, true)
if equals {
t.Errorf("Should have not been considered equal since first is not in the second array of groups")
}
}
func TestFindInstanceByNodeNameExcludesTerminatedInstances(t *testing.T) {
awsServices := NewFakeAWSServices()
nodeName := types.NodeName("my-dns.internal")
var tag ec2.Tag
tag.Key = aws.String(TagNameKubernetesClusterLegacy)
tag.Value = aws.String(TestClusterId)
tags := []*ec2.Tag{&tag}
var runningInstance ec2.Instance
runningInstance.InstanceId = aws.String("i-running")
runningInstance.PrivateDnsName = aws.String(string(nodeName))
runningInstance.State = &ec2.InstanceState{Code: aws.Int64(16), Name: aws.String("running")}
runningInstance.Tags = tags
var terminatedInstance ec2.Instance
terminatedInstance.InstanceId = aws.String("i-terminated")
terminatedInstance.PrivateDnsName = aws.String(string(nodeName))
terminatedInstance.State = &ec2.InstanceState{Code: aws.Int64(48), Name: aws.String("terminated")}
terminatedInstance.Tags = tags
instances := []*ec2.Instance{&terminatedInstance, &runningInstance}
awsServices.instances = append(awsServices.instances, instances...)
c, err := newAWSCloud(strings.NewReader("[global]"), awsServices)
if err != nil {
t.Errorf("Error building aws cloud: %v", err)
return
}
instance, err := c.findInstanceByNodeName(nodeName)
if err != nil {
t.Errorf("Failed to find instance: %v", err)
return
}
if *instance.InstanceId != "i-running" {
t.Errorf("Expected running instance but got %v", *instance.InstanceId)
}
}
func TestFindInstancesByNodeNameCached(t *testing.T) {
awsServices := NewFakeAWSServices()
nodeNameOne := "my-dns.internal"
nodeNameTwo := "my-dns-two.internal"
var tag ec2.Tag
tag.Key = aws.String(TagNameKubernetesClusterPrefix + TestClusterId)
tag.Value = aws.String("")
tags := []*ec2.Tag{&tag}
var runningInstance ec2.Instance
runningInstance.InstanceId = aws.String("i-running")
runningInstance.PrivateDnsName = aws.String(nodeNameOne)
runningInstance.State = &ec2.InstanceState{Code: aws.Int64(16), Name: aws.String("running")}
runningInstance.Tags = tags
var secondInstance ec2.Instance
secondInstance.InstanceId = aws.String("i-running")
secondInstance.PrivateDnsName = aws.String(nodeNameTwo)
secondInstance.State = &ec2.InstanceState{Code: aws.Int64(48), Name: aws.String("running")}
secondInstance.Tags = tags
var terminatedInstance ec2.Instance
terminatedInstance.InstanceId = aws.String("i-terminated")
terminatedInstance.PrivateDnsName = aws.String(nodeNameOne)
terminatedInstance.State = &ec2.InstanceState{Code: aws.Int64(48), Name: aws.String("terminated")}
terminatedInstance.Tags = tags
instances := []*ec2.Instance{&secondInstance, &runningInstance, &terminatedInstance}
awsServices.instances = append(awsServices.instances, instances...)
c, err := newAWSCloud(strings.NewReader("[global]"), awsServices)
if err != nil {
t.Errorf("Error building aws cloud: %v", err)
return
}
nodeNames := sets.NewString(nodeNameOne)
returnedInstances, errr := c.getInstancesByNodeNamesCached(nodeNames, "running")
if errr != nil {
t.Errorf("Failed to find instance: %v", err)
return
}
if len(returnedInstances) != 1 {
t.Errorf("Expected a single isntance but found: %v", returnedInstances)
}
if *returnedInstances[0].PrivateDnsName != nodeNameOne {
t.Errorf("Expected node name %v but got %v", nodeNameOne, returnedInstances[0].PrivateDnsName)
}
}
func TestGetVolumeLabels(t *testing.T) {
awsServices := NewFakeAWSServices()
c, err := newAWSCloud(strings.NewReader("[global]"), awsServices)
assert.Nil(t, err, "Error building aws cloud: %v", err)
volumeId := awsVolumeID("vol-VolumeId")
expectedVolumeRequest := &ec2.DescribeVolumesInput{VolumeIds: []*string{volumeId.awsString()}}
awsServices.ec2.On("DescribeVolumes", expectedVolumeRequest).Return([]*ec2.Volume{
{
VolumeId: volumeId.awsString(),
AvailabilityZone: aws.String("us-east-1a"),
},
})
labels, err := c.GetVolumeLabels(KubernetesVolumeID("aws:///" + string(volumeId)))
assert.Nil(t, err, "Error creating Volume %v", err)
assert.Equal(t, map[string]string{
kubeletapis.LabelZoneFailureDomain: "us-east-1a",
kubeletapis.LabelZoneRegion: "us-east-1"}, labels)
awsServices.ec2.AssertExpectations(t)
}
func (self *FakeELB) expectDescribeLoadBalancers(loadBalancerName string) {
self.On("DescribeLoadBalancers", &elb.DescribeLoadBalancersInput{LoadBalancerNames: []*string{aws.String(loadBalancerName)}}).Return(&elb.DescribeLoadBalancersOutput{
LoadBalancerDescriptions: []*elb.LoadBalancerDescription{{}},
})
}
func TestDescribeLoadBalancerOnDelete(t *testing.T) {
awsServices := NewFakeAWSServices()
c, _ := newAWSCloud(strings.NewReader("[global]"), awsServices)
awsServices.elb.expectDescribeLoadBalancers("aid")
c.EnsureLoadBalancerDeleted(TestClusterName, &v1.Service{ObjectMeta: metav1.ObjectMeta{Name: "myservice", UID: "id"}})
}
func TestDescribeLoadBalancerOnUpdate(t *testing.T) {
awsServices := NewFakeAWSServices()
c, _ := newAWSCloud(strings.NewReader("[global]"), awsServices)
awsServices.elb.expectDescribeLoadBalancers("aid")
c.UpdateLoadBalancer(TestClusterName, &v1.Service{ObjectMeta: metav1.ObjectMeta{Name: "myservice", UID: "id"}}, []*v1.Node{})
}
func TestDescribeLoadBalancerOnGet(t *testing.T) {
awsServices := NewFakeAWSServices()
c, _ := newAWSCloud(strings.NewReader("[global]"), awsServices)
awsServices.elb.expectDescribeLoadBalancers("aid")
c.GetLoadBalancer(TestClusterName, &v1.Service{ObjectMeta: metav1.ObjectMeta{Name: "myservice", UID: "id"}})
}
func TestDescribeLoadBalancerOnEnsure(t *testing.T) {
awsServices := NewFakeAWSServices()
c, _ := newAWSCloud(strings.NewReader("[global]"), awsServices)
awsServices.elb.expectDescribeLoadBalancers("aid")
c.EnsureLoadBalancer(TestClusterName, &v1.Service{ObjectMeta: metav1.ObjectMeta{Name: "myservice", UID: "id"}}, []*v1.Node{})
}
func TestBuildListener(t *testing.T) {
tests := []struct {
name string
lbPort int64
portName string
instancePort int64
backendProtocolAnnotation string
certAnnotation string
sslPortAnnotation string
expectError bool
lbProtocol string
instanceProtocol string
certID string
}{
{
"No cert or BE protocol annotation, passthrough",
80, "", 7999, "", "", "",
false, "tcp", "tcp", "",
},
{
"Cert annotation without BE protocol specified, SSL->TCP",
80, "", 8000, "", "cert", "",
false, "ssl", "tcp", "cert",
},
{
"BE protocol without cert annotation, passthrough",
443, "", 8001, "https", "", "",
false, "tcp", "tcp", "",
},
{
"Invalid cert annotation, bogus backend protocol",
443, "", 8002, "bacon", "foo", "",
true, "tcp", "tcp", "",
},
{
"Invalid cert annotation, protocol followed by equal sign",
443, "", 8003, "http=", "=", "",
true, "tcp", "tcp", "",
},
{
"HTTPS->HTTPS",
443, "", 8004, "https", "cert", "",
false, "https", "https", "cert",
},
{
"HTTPS->HTTP",
443, "", 8005, "http", "cert", "",
false, "https", "http", "cert",
},
{
"SSL->SSL",
443, "", 8006, "ssl", "cert", "",
false, "ssl", "ssl", "cert",
},
{
"SSL->TCP",
443, "", 8007, "tcp", "cert", "",
false, "ssl", "tcp", "cert",
},
{
"Port in whitelist",
1234, "", 8008, "tcp", "cert", "1234,5678",
false, "ssl", "tcp", "cert",
},
{
"Port not in whitelist, passthrough",
443, "", 8009, "tcp", "cert", "1234,5678",
false, "tcp", "tcp", "",
},
{
"Named port in whitelist",
1234, "bar", 8010, "tcp", "cert", "foo,bar",
false, "ssl", "tcp", "cert",
},
{
"Named port not in whitelist, passthrough",
443, "", 8011, "tcp", "cert", "foo,bar",
false, "tcp", "tcp", "",
},
{
"HTTP->HTTP",
80, "", 8012, "http", "", "",
false, "http", "http", "",
},
}
for _, test := range tests {
t.Logf("Running test case %s", test.name)
annotations := make(map[string]string)
if test.backendProtocolAnnotation != "" {
annotations[ServiceAnnotationLoadBalancerBEProtocol] = test.backendProtocolAnnotation
}
if test.certAnnotation != "" {
annotations[ServiceAnnotationLoadBalancerCertificate] = test.certAnnotation
}
ports := getPortSets(test.sslPortAnnotation)
l, err := buildListener(v1.ServicePort{
NodePort: int32(test.instancePort),
Port: int32(test.lbPort),
Name: test.portName,
Protocol: v1.Protocol("tcp"),
}, annotations, ports)
if test.expectError {
if err == nil {
t.Errorf("Should error for case %s", test.name)
}
} else {
if err != nil {
t.Errorf("Should succeed for case: %s, got %v", test.name, err)
} else {
var cert *string
if test.certID != "" {
cert = &test.certID
}
expected := &elb.Listener{
InstancePort: &test.instancePort,
InstanceProtocol: &test.instanceProtocol,
LoadBalancerPort: &test.lbPort,
Protocol: &test.lbProtocol,
SSLCertificateId: cert,
}
if !reflect.DeepEqual(l, expected) {
t.Errorf("Incorrect listener (%v vs expected %v) for case: %s",
l, expected, test.name)
}
}
}
}
}
func TestProxyProtocolEnabled(t *testing.T) {
policies := sets.NewString(ProxyProtocolPolicyName, "FooBarFoo")
fakeBackend := &elb.BackendServerDescription{
InstancePort: aws.Int64(80),
PolicyNames: stringSetToPointers(policies),
}
result := proxyProtocolEnabled(fakeBackend)
assert.True(t, result, "expected to find %s in %s", ProxyProtocolPolicyName, policies)
policies = sets.NewString("FooBarFoo")
fakeBackend = &elb.BackendServerDescription{
InstancePort: aws.Int64(80),
PolicyNames: []*string{
aws.String("FooBarFoo"),
},
}
result = proxyProtocolEnabled(fakeBackend)
assert.False(t, result, "did not expect to find %s in %s", ProxyProtocolPolicyName, policies)
policies = sets.NewString()
fakeBackend = &elb.BackendServerDescription{
InstancePort: aws.Int64(80),
}
result = proxyProtocolEnabled(fakeBackend)
assert.False(t, result, "did not expect to find %s in %s", ProxyProtocolPolicyName, policies)
}
func TestGetLoadBalancerAdditionalTags(t *testing.T) {
tagTests := []struct {
Annotations map[string]string
Tags map[string]string
}{
{
Annotations: map[string]string{
ServiceAnnotationLoadBalancerAdditionalTags: "Key=Val",
},
Tags: map[string]string{
"Key": "Val",
},
},
{
Annotations: map[string]string{
ServiceAnnotationLoadBalancerAdditionalTags: "Key1=Val1, Key2=Val2",
},
Tags: map[string]string{
"Key1": "Val1",
"Key2": "Val2",
},
},
{
Annotations: map[string]string{
ServiceAnnotationLoadBalancerAdditionalTags: "Key1=, Key2=Val2",
"anotherKey": "anotherValue",
},
Tags: map[string]string{
"Key1": "",
"Key2": "Val2",
},
},
{
Annotations: map[string]string{
"Nothing": "Key1=, Key2=Val2, Key3",
},
Tags: map[string]string{},
},
{
Annotations: map[string]string{
ServiceAnnotationLoadBalancerAdditionalTags: "K=V K1=V2,Key1========, =====, ======Val, =Val, , 234,",
},
Tags: map[string]string{
"K": "V K1",
"Key1": "",
"234": "",
},
},
}
for _, tagTest := range tagTests {
result := getLoadBalancerAdditionalTags(tagTest.Annotations)
for k, v := range result {
if len(result) != len(tagTest.Tags) {
t.Errorf("incorrect expected length: %v != %v", result, tagTest.Tags)
continue
}
if tagTest.Tags[k] != v {
t.Errorf("%s != %s", tagTest.Tags[k], v)
continue
}
}
}
}
func TestInstanceIDFromProviderID(t *testing.T) {
testCases := []struct {
providerID string
instanceID string
fail bool
}{
{
providerID: "aws://i-0194bbdb81a49b169",
instanceID: "i-0194bbdb81a49b169",
fail: false,
},
{
providerID: "i-0194bbdb81a49b169",
instanceID: "",
fail: true,
},
}
for _, test := range testCases {
instanceID, err := instanceIDFromProviderID(test.providerID)
if (err != nil) != test.fail {
t.Errorf("%s yielded `err != nil` as %t. expected %t", test.providerID, (err != nil), test.fail)
}
if test.fail {
continue
}
if instanceID != test.instanceID {
t.Errorf("%s yielded %s. expected %s", test.providerID, instanceID, test.instanceID)
}
}
}
| {
routeTablesOut = append(routeTablesOut,
&ec2.RouteTable{
Associations: []*ec2.RouteTableAssociation{{Main: aws.Bool(true)}},
Routes: []*ec2.Route{{
DestinationCidrBlock: aws.String("0.0.0.0/0"),
GatewayId: aws.String("igw-main"),
}},
})
for subnetID := range routeTablesIn {
routeTablesOut = append(
routeTablesOut,
constructRouteTable(
subnetID,
routeTablesIn[subnetID],
),
)
}
return
} |
server-index-page.py | import sys, os, BaseHTTPServer
#-------------------------------------------------------------------------------
class ServerException(Exception):
'''For internal error reporting.'''
pass
#-------------------------------------------------------------------------------
class case_no_file(object):
'''File or directory does not exist.'''
def test(self, handler):
return not os.path.exists(handler.full_path)
def act(self, handler):
raise ServerException("'{0}' not found".format(handler.path))
#-------------------------------------------------------------------------------
class case_existing_file(object):
'''File exists.'''
def test(self, handler):
return os.path.isfile(handler.full_path)
def act(self, handler):
handler.handle_file(handler.full_path)
#-------------------------------------------------------------------------------
class case_directory_index_file(object):
'''Serve index.html page for a directory.'''
def index_path(self, handler):
return os.path.join(handler.full_path, 'index.html')
def test(self, handler):
return os.path.isdir(handler.full_path) and \
os.path.isfile(self.index_path(handler))
def act(self, handler):
handler.handle_file(self.index_path(handler))
#-------------------------------------------------------------------------------
class case_always_fail(object):
'''Base case if nothing else worked.'''
def test(self, handler):
return True
def act(self, handler):
raise ServerException("Unknown object '{0}'".format(handler.path))
#-------------------------------------------------------------------------------
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
'''
If the requested path maps to a file, that file is served.
If anything goes wrong, an error page is constructed.
'''
Cases = [case_no_file(),
case_existing_file(),
case_directory_index_file(),
case_always_fail()]
# How to display an error.
Error_Page = """\
<html>
<body>
<h1>Error accessing {path}</h1>
<p>{msg}</p>
</body>
</html>
"""
# Classify and handle request.
def do_GET(self):
try:
# Figure out what exactly is being requested.
self.full_path = os.getcwd() + self.path
# Figure out how to handle it.
for case in self.Cases:
if case.test(self):
case.act(self)
break
# Handle errors.
except Exception as msg:
self.handle_error(msg)
def handle_file(self, full_path):
try:
with open(full_path, 'rb') as reader:
content = reader.read()
self.send_content(content)
except IOError as msg:
msg = "'{0}' cannot be read: {1}".format(self.path, msg)
self.handle_error(msg)
# Handle unknown objects.
def handle_error(self, msg):
content = self.Error_Page.format(path=self.path, msg=msg)
self.send_content(content, 404)
# Send actual content.
def send_content(self, content, status=200):
self.send_response(status)
self.send_header("Content-type", "text/html")
self.send_header("Content-Length", str(len(content)))
self.end_headers()
self.wfile.write(content)
#-------------------------------------------------------------------------------
if __name__ == '__main__':
| serverAddress = ('', 8080)
server = BaseHTTPServer.HTTPServer(serverAddress, RequestHandler)
server.serve_forever() |
|
unifi.js | module.exports = function (RED) {
'use strict';
const STATUS_OK = {
fill: "green",
shape: "dot",
text: "OK"
};
const Unifi = require('ubnt-unifi');
function UnifiEventsNode(config) {
RED.nodes.createNode(this, config);
const node = this;
const {username, password} = node.credentials;
let {site, host, port, insecure, unifios} = config;
let clientMap = {};
// console.log("Connecting to", host);
this.status({fill:"grey",shape:"dot",text:"connecting"});
let unifi = new Unifi({
host: host,
port: port,
username: username,
password: password,
site: site,
insecure: insecure,
unifios: unifios
});
unifi.on('ctrl.connect', function (data) {
node.status({fill:"green",shape:"dot",text:"connected"});
unifi.get('stat/alluser')
.then(sta => {
// console.log('Loaded info for '+sta.data.length+' users');
sta.data.forEach((el, index) => clientMap[el.mac] = el);
console.log(sta.data.map((el) => el.mac + " " + (el.name || el.hostname || el.device_name)));
});
});
unifi.on('ctrl.error', function (data) {
node.status({fill:"red",shape:"dot",text:"error"});
});
unifi.on('ctrl.disconnect', function (data) {
node.status({fill:"grey",shape:"ring",text:"disconnected"});
});
unifi.on('ctrl.reconnect', function (data) {
node.status({fill:"grey",shape:"dot",text:"reconnecting"});
});
unifi.on('ctrl.close', function (data) {
node.status({fill:"grey",shape:"dot",text:"disconnected"});
});
// Listen for any event
unifi.on('**', function (data) {
console.log("Received event", this.event, data);
let msg = {
payload: {
namespace: this.event.split('.')[0],
event: this.event,
data: data
}
};
if (data && data.user) {
// details are cached. enrich event
let client = clientMap[data.user];
if (client) {
addClientToPayload(client, msg.payload);
node.send(msg);
} else {
// load client details
// console.log('Loading info for '+data.user);
unifi.get('stat/user/'+data.user)
.then(response => {
// console.log('Got user info', response);
client = response.data[0];
clientMap[data.user] = client;
addClientToPayload(client, msg.payload);
node.send(msg);
});
}
} else {
node.send(msg);
}
});
function | (client, payload) {
payload.client = {
hostname: client.hostname,
device_name: client.device_name,
name: client.name,
ip: client.ip
};
}
this.on('close', function() {
node.status({fill:"grey",shape:"dot",text:"disconnecting"});
// console.log("Closing connection");
unifi.close();
});
}
RED.nodes.registerType("UnifiEvents", UnifiEventsNode, {
credentials: {
username: {type: "text"},
password: {type: "password"}
}
});
}; | addClientToPayload |
iperf.rs | #![feature(alloc)]
#![no_std]
#![no_main]
#[macro_use]
extern crate rcore_user;
extern crate alloc;
use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use isomorphic_drivers::net::ethernet::intel::ixgbe;
use isomorphic_drivers::provider;
use rcore_user::syscall::*;
use smoltcp::iface::*;
use smoltcp::phy;
use smoltcp::phy::*;
use smoltcp::socket::*;
use smoltcp::time::*;
use smoltcp::wire::*;
use smoltcp::Result;
#[derive(Copy, Clone)]
pub struct Provider;
impl Provider {
pub fn new() -> Box<Provider> {
Box::new(Provider {})
}
}
impl provider::Provider for Provider {
/// Get page size
fn get_page_size(&self) -> usize {
4096
}
// Translate virtual address to physical address
fn translate_va(&self, va: usize) -> usize {
let mut pa = [0u64; 1];
sys_get_paddr(&[va as u64], &mut pa[..]);
pa[0] as usize
}
// Bulk translate virtual addresses to physical addresses for performance
fn translate_vas(&self, vas: &[usize]) -> Vec<usize> {
let mut pas = vec![0u64; vas.len()];
let mut vec_vas = vec![0u64; vas.len()];
for va in vas.iter() {
vec_vas.push(*va as u64);
}
sys_get_paddr(&vec_vas[..], &mut pas[..]);
let mut res = vec![0usize; vas.len()];
for pa in pas {
res.push(pa as usize);
}
res
}
}
#[derive(Clone)]
struct IXGBEDriver {
inner: ixgbe::IXGBEDriver,
}
pub struct IXGBERxToken(Vec<u8>);
pub struct IXGBETxToken(IXGBEDriver);
impl<'a> phy::Device<'a> for IXGBEDriver {
type RxToken = IXGBERxToken;
type TxToken = IXGBETxToken;
fn receive(&'a mut self) -> Option<(Self::RxToken, Self::TxToken)> {
if self.inner.can_send() {
if let Some(data) = self.inner.recv() {
Some((IXGBERxToken(data), IXGBETxToken(self.clone())))
} else {
None
}
} else {
None
}
}
fn | (&'a mut self) -> Option<Self::TxToken> {
if self.inner.can_send() {
Some(IXGBETxToken(self.clone()))
} else {
None
}
}
fn capabilities(&self) -> DeviceCapabilities {
let mut caps = DeviceCapabilities::default();
caps.max_transmission_unit = ixgbe::IXGBEDriver::get_mtu(); // max MTU
//caps.max_transmission_unit = 1500; // max MTU
caps.max_burst_size = Some(256);
// IP Rx checksum is offloaded with RXCSUM
caps.checksum.ipv4 = Checksum::Tx;
caps
}
}
impl phy::RxToken for IXGBERxToken {
fn consume<R, F>(self, _timestamp: Instant, f: F) -> Result<R>
where
F: FnOnce(&[u8]) -> Result<R>,
{
f(&self.0)
}
}
impl phy::TxToken for IXGBETxToken {
fn consume<R, F>(self, _timestamp: Instant, len: usize, f: F) -> Result<R>
where
F: FnOnce(&mut [u8]) -> Result<R>,
{
let mut buffer = [0u8; ixgbe::IXGBEDriver::get_mtu()];
let result = f(&mut buffer[..len]);
if result.is_ok() {
(self.0).inner.send(&buffer[..len]);
}
result
}
}
#[derive(Copy, Clone, Debug, PartialEq)]
enum State {
BEGIN,
CONTROL_SOCKET_CONNECT,
CONTROL_COOKIE_SENT,
JSON_CONFIG_SENT,
CREATE_STREAMS,
DATA_SOCKET_CONNECT,
DATA_COOKIE_SENT,
TEST_START,
TEST_RUNNING,
}
// IMPORTANT: Must define main() like this
#[no_mangle]
pub fn main() {
enlarge_heap();
println!("I am going to map IXGBE driver to user space");
println!("Kernel network stack should not use it anymore");
let addr = sys_map_pci_device(0x8086, 0x10fb);
println!("IXGBE addr at {:#X}", addr);
let ixgbe = ixgbe::IXGBEDriver::init(Provider::new(), addr as usize, 0x20000);
println!("IXGBE driver up");
println!("IXGBE driver waiting for link up");
while !ixgbe.is_link_up() {}
println!("IXGBE driver link is up");
let ethernet_addr = ixgbe.get_mac();
let ip_addrs = [IpCidr::new(IpAddress::v4(10, 0, 0, 2), 24)];
let neighbor_cache = NeighborCache::new(BTreeMap::new());
let mut iface = EthernetInterfaceBuilder::new(IXGBEDriver { inner: ixgbe })
.ethernet_addr(EthernetAddress::from_bytes(ðernet_addr.as_bytes()))
.ip_addrs(ip_addrs)
.neighbor_cache(neighbor_cache)
.finalize();
// 37 byte ascii cookie
let cookie = String::from("cafebabed00dbeefELFGIF89aPKGET/HTTP/\0").into_bytes();
assert_eq!(cookie.len(), 37);
// Json config
let json = String::from(r##"{"tcp":true,"omit":0,"time":10,"parallel":1,"len":2147483647,"pacing_timer":1000,"client_version":"3.6"}"##).into_bytes();
println!("Waiting for 3s");
sys_sleep(3);
println!("Simulating iperf3 client to 10.0.0.1");
// tcp for control, tcp2 for data
let tcp_rx_buffer = TcpSocketBuffer::new(vec![0; 204800]);
let tcp_tx_buffer = TcpSocketBuffer::new(vec![0; 204800]);
let tcp_socket = TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer);
let tcp2_rx_buffer = TcpSocketBuffer::new(vec![0; 204800]);
let tcp2_tx_buffer = TcpSocketBuffer::new(vec![0; 204800]);
let tcp2_socket = TcpSocket::new(tcp2_rx_buffer, tcp2_tx_buffer);
let mut sockets = SocketSet::new(vec![]);
let tcp_handle = sockets.add(tcp_socket);
let tcp2_handle = sockets.add(tcp2_socket);
let mut tick = 0;
let mut state = State::BEGIN;
let mut last_state = State::BEGIN;
let data = [0u8; 204800];
loop {
tick += 1;
iface.poll(&mut sockets, Instant::from_millis(tick * 1000_000));
{
let mut socket = sockets.get::<TcpSocket>(tcp_handle);
if let State::BEGIN = state {
socket
.connect(
IpEndpoint::new(IpAddress::v4(10, 0, 0, 1), 5201),
IpEndpoint::new(IpAddress::v4(10, 0, 0, 2), 5201),
)
.unwrap();
state = State::CONTROL_SOCKET_CONNECT;
} else if let State::CONTROL_SOCKET_CONNECT = state {
if socket.may_send() {
socket.send_slice(&cookie).unwrap();
state = State::CONTROL_COOKIE_SENT;
}
} else if let State::CONTROL_COOKIE_SENT = state {
let mut recv = [0u8; 1];
if socket.may_recv() {
socket.recv_slice(&mut recv).unwrap();
if recv[0] == 9 {
// param exchange
// dword len
let len = json.len();
let mut len_data = [0u8; 4];
len_data[3] = len as u8;
socket.send_slice(&len_data).unwrap();
socket.send_slice(&json).unwrap();
state = State::JSON_CONFIG_SENT;
}
}
} else if let State::JSON_CONFIG_SENT = state {
let mut recv = [0u8; 1];
if socket.may_recv() {
socket.recv_slice(&mut recv).unwrap();
if recv[0] == 10 {
// create streams
state = State::CREATE_STREAMS;
}
}
} else if let State::DATA_COOKIE_SENT = state {
let mut recv = [0u8; 1];
if socket.may_recv() {
socket.recv_slice(&mut recv).unwrap();
if recv[0] == 1 {
// test start
state = State::TEST_START;
}
}
} else if let State::TEST_START = state {
let mut recv = [0u8; 1];
if socket.may_recv() {
socket.recv_slice(&mut recv).unwrap();
if recv[0] == 2 {
// test running
state = State::TEST_RUNNING;
}
}
}
}
{
let mut socket = sockets.get::<TcpSocket>(tcp2_handle);
if let State::CREATE_STREAMS = state {
socket
.connect(
IpEndpoint::new(IpAddress::v4(10, 0, 0, 1), 5201),
IpEndpoint::new(IpAddress::v4(10, 0, 0, 2), 5202),
)
.unwrap();
state = State::DATA_SOCKET_CONNECT;
} else if let State::DATA_SOCKET_CONNECT = state {
if socket.may_send() {
socket.send_slice(&cookie).unwrap();
state = State::DATA_COOKIE_SENT;
}
} else if let State::TEST_RUNNING = state {
if socket.can_send() {
socket.send_slice(&data).unwrap();
}
}
}
if state != last_state {
println!("{:?} -> {:?}", last_state, state);
}
last_state = state;
}
}
| transmit |
SOM.py |
"""
Author: Zahra Gharaee.
This code is written for the 3D-Human-Action-Recognition Project, started March 14 2014.
"""
import numpy as np
from numpy import linalg as LA
class SOM:
def __init__(self, learning, outputsize_x, outputsize_y, inputsize, sigma, softmax_exponent, max_epoch):
self.name = 'SOM'
self.learning = learning
self.outputsize_x = outputsize_x
self.outputsize_y = outputsize_y
self.inputsize = inputsize
self.sigma = sigma
self.softmax_exponent = softmax_exponent
self.max_epoch = max_epoch
self.metric = 'Euclidean'
self.normalize_input = False
self.normalize_weights = False
self.softmax_normalization = True
self.neighborhood_decay = 0.9999
self.neighborhood_min = 1
self.learningRate = 0.1
self.learningRate_decay = 0.9999
self.learningRate_min = 0.01
self.neighborhood_radius = outputsize_x
self.node_map = np.zeros((outputsize_x, outputsize_y, 2))
self.weights = np.random.rand(outputsize_x, outputsize_y, inputsize) # Rows, Columns, Depth
for i in range(outputsize_x):
for j in range(outputsize_y):
self.node_map[i, j, 0] = i
self.node_map[i, j, 1] = j
def normalize(self, state):
if self.normalize_input:
state /= LA.norm(np.expand_dims(state, axis=0))
return state
def soft_max_normalization(self, state):
m = np.max(state)
if m != 0:
state /= m
return state
def set_activity(self, state):
|
def find_winning_node(self, activity):
winner_x, winner_y = np.unravel_index(np.argmax(activity, axis=None), activity.shape)
winning_node = np.array([winner_x, winner_y])
return winning_node
def learn(self, state, winner):
dis = np.sum((self.node_map - winner) ** 2, axis=2)
gus = np.exp(-dis / (2 * self.neighborhood_radius ** 2))
err = state - self.weights
self.weights += self.learningRate * (err.T * gus.T).T
def learning_decay(self):
self.learningRate *= self.learningRate_decay
if self.learningRate < self.learningRate_min:
self.learningRate = self.learningRate_min
self.neighborhood_radius *= self.neighborhood_decay
if self.neighborhood_radius < self.neighborhood_min:
self.neighborhood_radius = self.neighborhood_min
def run_SOM(self, state):
state = self.normalize(state)
activity = self.set_activity(state)
winner = self.find_winning_node(activity)
if self.learning:
self.learn(state, winner)
self.learning_decay()
return activity, winner
| if self.metric == 'Euclidean':
dist = np.sum((state - self.weights) ** 2, axis=2)
activity = np.exp(-dist / self.sigma)
else:
# Scalar Product
mat_mul = state * self.weights
activity = mat_mul.sum(axis=2)
if self.softmax_exponent != 1:
activity = activity ** self.softmax_exponent
if self.softmax_normalization:
activity = self.soft_max_normalization(activity)
return activity |
vm_call.rs | use crate::runtime::{Call, Future, Generator, Stream, Value, Vm, VmError, VmExecution};
/// An instruction to push a virtual machine to the execution.
#[derive(Debug)]
pub(crate) struct VmCall {
call: Call,
vm: Vm,
}
impl VmCall {
/// Construct a new nested vm call.
pub(crate) fn | (call: Call, vm: Vm) -> Self {
Self { call, vm }
}
/// Encode the push itno an execution.
pub(crate) fn into_execution<T>(self, execution: &mut VmExecution<T>) -> Result<(), VmError>
where
T: AsMut<Vm>,
{
let value = match self.call {
Call::Async => Value::from(Future::new(self.vm.async_complete())),
Call::Immediate => {
execution.push_vm(self.vm);
return Ok(());
}
Call::Stream => Value::from(Stream::new(self.vm)),
Call::Generator => Value::from(Generator::new(self.vm)),
};
let vm = execution.vm_mut();
vm.stack_mut().push(value);
vm.advance();
Ok(())
}
}
| new |
int.go | package zero
import (
"bytes"
"database/sql"
"encoding/json"
"errors"
"fmt"
"strconv"
)
// Int is a nullable int64.
// JSON marshals to zero if null.
// Considered null to SQL if zero.
type Int struct {
sql.NullInt64
}
// NewInt creates a new Int
func NewInt(i int64, valid bool) Int {
return Int{
NullInt64: sql.NullInt64{
Int64: i,
Valid: valid,
},
}
}
// IntFrom creates a new Int that will be null if zero.
func IntFrom(i int64) Int {
return NewInt(i, i != 0)
}
// IntFromPtr creates a new Int that be null if i is nil.
func | (i *int64) Int {
if i == nil {
return NewInt(0, false)
}
n := NewInt(*i, true)
return n
}
// ValueOrZero returns the inner value if valid, otherwise zero.
func (i Int) ValueOrZero() int64 {
if !i.Valid {
return 0
}
return i.Int64
}
// UnmarshalJSON implements json.Unmarshaler.
// It supports number and null input.
// 0 will be considered a null Int.
func (i *Int) UnmarshalJSON(data []byte) error {
if bytes.Equal(data, nullBytes) {
i.Valid = false
return nil
}
if err := json.Unmarshal(data, &i.Int64); err != nil {
var typeError *json.UnmarshalTypeError
if errors.As(err, &typeError) {
// special case: accept string input
if typeError.Value != "string" {
return fmt.Errorf("zero: JSON input is invalid type (need int or string): %w", err)
}
var str string
if err := json.Unmarshal(data, &str); err != nil {
return fmt.Errorf("zero: couldn't unmarshal number string: %w", err)
}
n, err := strconv.ParseInt(str, 10, 64)
if err != nil {
return fmt.Errorf("zero: couldn't convert string to int: %w", err)
}
i.Int64 = n
i.Valid = n != 0
return nil
}
return fmt.Errorf("zero: couldn't unmarshal JSON: %w", err)
}
i.Valid = i.Int64 != 0
return nil
}
// UnmarshalText implements encoding.TextUnmarshaler.
// It will unmarshal to a null Int if the input is a blank, or zero.
// It will return an error if the input is not an integer, blank, or "null".
func (i *Int) UnmarshalText(text []byte) error {
str := string(text)
if str == "" || str == "null" {
i.Valid = false
return nil
}
var err error
i.Int64, err = strconv.ParseInt(string(text), 10, 64)
if err != nil {
return fmt.Errorf("zero: couldn't unmarshal text: %w", err)
}
i.Valid = i.Int64 != 0
return err
}
// MarshalJSON implements json.Marshaler.
// It will encode 0 if this Int is null.
func (i Int) MarshalJSON() ([]byte, error) {
n := i.Int64
if !i.Valid {
n = 0
}
return []byte(strconv.FormatInt(n, 10)), nil
}
// MarshalText implements encoding.TextMarshaler.
// It will encode a zero if this Int is null.
func (i Int) MarshalText() ([]byte, error) {
n := i.Int64
if !i.Valid {
n = 0
}
return []byte(strconv.FormatInt(n, 10)), nil
}
// SetValid changes this Int's value and also sets it to be non-null.
func (i *Int) SetValid(n int64) {
i.Int64 = n
i.Valid = true
}
// Ptr returns a pointer to this Int's value, or a nil pointer if this Int is null.
func (i Int) Ptr() *int64 {
if !i.Valid {
return nil
}
return &i.Int64
}
// IsZero returns true for null or zero Ints, for future omitempty support (Go 1.4?)
func (i Int) IsZero() bool {
return !i.Valid || i.Int64 == 0
}
// Equal returns true if both ints have the same value or are both either null or zero.
func (i Int) Equal(other Int) bool {
return i.ValueOrZero() == other.ValueOrZero()
}
| IntFromPtr |
services.py | from .model import Model
class Services(Model):
| pass |
|
get_build_logs.go | package cmd
import (
"fmt"
"os"
"sort"
"strings"
"time"
"github.com/jenkins-x/golang-jenkins"
"github.com/jenkins-x/jx/pkg/apis/jenkins.io/v1"
"github.com/jenkins-x/jx/pkg/builds"
"github.com/jenkins-x/jx/pkg/client/clientset/versioned"
"github.com/jenkins-x/jx/pkg/gits"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/tekton"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/tektoncd/pipeline/pkg/apis/pipeline"
"k8s.io/client-go/kubernetes"
"github.com/jenkins-x/jx/pkg/jx/cmd/templates"
"github.com/jenkins-x/jx/pkg/log"
"github.com/jenkins-x/jx/pkg/util"
tektonclient "github.com/tektoncd/pipeline/pkg/client/clientset/versioned"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// GetBuildLogsOptions the command line options
type GetBuildLogsOptions struct {
GetOptions
Tail bool
Wait bool
BuildFilter builds.BuildPodInfoFilter
JenkinsSelector JenkinsSelectorOptions
CurrentFolder bool
WaitForPipelineDuration time.Duration
}
var (
get_build_log_long = templates.LongDesc(`
Display a build log
`)
get_build_log_example = templates.Examples(`
# Display a build log - with the user choosing which repo + build to view
jx get build log
# Pick a build to view the log based on the repo cheese
jx get build log --repo cheese
# Pick a pending knative build to view the log based
jx get build log -p
# Pick a pending knative build to view the log based on the repo cheese
jx get build log --repo cheese -p
# Pick a knative build for the 1234 Pull Request on the repo cheese
jx get build log --repo cheese --branch PR-1234
# View the build logs for a specific tekton build pod
jx get build log --pod my-pod-name
`)
)
// NewCmdGetBuildLogs creates the command
func NewCmdGetBuildLogs(commonOpts *CommonOptions) *cobra.Command {
options := &GetBuildLogsOptions{
GetOptions: GetOptions{
CommonOptions: commonOpts,
},
}
cmd := &cobra.Command{
Use: "log [flags]",
Short: "Display a build log",
Long: get_build_log_long,
Example: get_build_log_example,
Aliases: []string{"logs"},
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
CheckErr(err)
},
}
cmd.Flags().BoolVarP(&options.Tail, "tail", "t", true, "Tails the build log to the current terminal")
cmd.Flags().BoolVarP(&options.Wait, "wait", "w", false, "Waits for the build to start before failing")
cmd.Flags().DurationVarP(&options.WaitForPipelineDuration, "wait-duration", "d", time.Minute*5, "Timeout period waiting for the given pipeline to be created")
cmd.Flags().BoolVarP(&options.BuildFilter.Pending, "pending", "p", false, "Only display logs which are currently pending to choose from if no build name is supplied")
cmd.Flags().StringVarP(&options.BuildFilter.Filter, "filter", "f", "", "Filters all the available jobs by those that contain the given text")
cmd.Flags().StringVarP(&options.BuildFilter.Owner, "owner", "o", "", "Filters the owner (person/organisation) of the repository")
cmd.Flags().StringVarP(&options.BuildFilter.Repository, "repo", "r", "", "Filters the build repository")
cmd.Flags().StringVarP(&options.BuildFilter.Branch, "branch", "", "", "Filters the branch")
cmd.Flags().StringVarP(&options.BuildFilter.Build, "build", "", "", "The build number to view")
cmd.Flags().StringVarP(&options.BuildFilter.Pod, "pod", "", "", "The pod name to view")
cmd.Flags().BoolVarP(&options.CurrentFolder, "current", "c", false, "Display logs using current folder as repo name, and parent folder as owner")
options.JenkinsSelector.AddFlags(cmd)
return cmd
}
// Run implements this command
func (o *GetBuildLogsOptions) Run() error {
jxClient, ns, err := o.JXClientAndDevNamespace()
if err != nil {
return err
}
kubeClient, err := o.KubeClient()
if err != nil {
return err
}
tektonClient, _, err := o.TektonClient()
if err != nil {
return err
}
tektonEnabled, err := kube.IsTektonEnabled(kubeClient, ns)
if err != nil {
return err
}
devEnv, err := kube.GetEnrichedDevEnvironment(kubeClient, jxClient, ns)
if devEnv == nil {
return fmt.Errorf("No development environment found for namespace %s", ns)
}
webhookEngine := devEnv.Spec.WebHookEngine
if webhookEngine == v1.WebHookEngineProw && !o.JenkinsSelector.IsCustom() {
return o.getProwBuildLog(kubeClient, tektonClient, jxClient, ns, tektonEnabled)
}
args := o.Args
if !o.BatchMode && len(args) == 0 {
jobMap, err := o.getJobMap(&o.JenkinsSelector, o.BuildFilter.Filter)
if err != nil {
return err
}
names := []string{}
for k := range jobMap {
names = append(names, k)
}
sort.Strings(names)
if len(names) == 0 {
return fmt.Errorf("No pipelines have been built!")
}
defaultName := ""
for _, n := range names {
if strings.HasSuffix(n, "/master") {
defaultName = n
break
}
}
name, err := util.PickNameWithDefault(names, "Which pipeline do you want to view the logs of?: ", defaultName, "", o.In, o.Out, o.Err)
if err != nil {
return err
}
args = []string{name}
}
if len(args) == 0 {
return fmt.Errorf("No pipeline chosen")
}
name := args[0]
buildNumber := o.BuildFilter.BuildNumber()
last, err := o.getLastJenkinsBuild(name, buildNumber)
if err != nil {
return err
}
log.Infof("%s %s\n", util.ColorStatus("view the log at:"), util.ColorInfo(util.UrlJoin(last.Url, "/console")))
return o.tailBuild(&o.JenkinsSelector, name, &last)
}
func (o *GetBuildLogsOptions) getLastJenkinsBuild(name string, buildNumber int) (gojenkins.Build, error) {
var last gojenkins.Build
jenkinsClient, err := o.CreateCustomJenkinsClient(&o.JenkinsSelector)
if err != nil {
return last, err
}
f := func() error {
var err error
jobMap, err := o.getJobMap(&o.JenkinsSelector, o.BuildFilter.Filter)
if err != nil {
return err
}
job := jobMap[name]
if job.Url == "" {
return fmt.Errorf("No Job exists yet called %s", name)
}
job.Url = switchJenkinsBaseURL(job.Url, jenkinsClient.BaseURL())
if buildNumber > 0 {
last, err = jenkinsClient.GetBuild(job, buildNumber)
} else {
last, err = jenkinsClient.GetLastBuild(job)
}
if err != nil {
return err
}
if last.Url == "" {
if buildNumber > 0 {
return fmt.Errorf("No build found for name %s number %d", name, buildNumber)
} else {
return fmt.Errorf("No build found for name %s", name)
}
}
last.Url = switchJenkinsBaseURL(last.Url, jenkinsClient.BaseURL())
return err
}
if o.Wait {
err := o.retry(60, time.Second*2, f)
return last, err
} else {
err := f()
return last, err
}
}
func (o *GetBuildLogsOptions) getProwBuildLog(kubeClient kubernetes.Interface, tektonClient tektonclient.Interface, jxClient versioned.Interface, ns string, tektonEnabled bool) error {
if o.CurrentFolder {
currentDirectory, err := os.Getwd()
if err != nil {
return err
}
gitRepository, err := gits.NewGitCLI().Info(currentDirectory)
if err != nil {
return err
}
o.BuildFilter.Repository = gitRepository.Name
o.BuildFilter.Owner = gitRepository.Organisation
}
var names []string
var defaultName string
var buildMap map[string]builds.BaseBuildInfo
var pipelineMap map[string]builds.BaseBuildInfo
args := o.Args
pickedPipeline := false
if len(args) == 0 {
if o.BatchMode {
return util.MissingArgument("pipeline")
}
var err error
if tektonEnabled {
names, defaultName, buildMap, pipelineMap, err = o.loadPipelines(kubeClient, tektonClient, jxClient, ns)
} else {
names, defaultName, buildMap, pipelineMap, err = o.loadBuilds(kubeClient, ns)
}
if err != nil {
return err
}
pickedPipeline = true
name, err := util.PickNameWithDefault(names, "Which build do you want to view the logs of?: ", defaultName, "", o.In, o.Out, o.Err)
if err != nil {
return err
}
args = []string{name}
}
if len(args) == 0 {
return fmt.Errorf("No pipeline chosen")
}
name := args[0]
build := buildMap[name]
suffix := ""
if build == nil {
build = pipelineMap[name]
if build != nil {
suffix = " #" + build.GetBuild()
} | }
if build == nil && !pickedPipeline && o.Wait {
log.Infof("waiting for pipeline %s to start...\n", util.ColorInfo(name))
// there's no pipeline with yet called 'name' so lets wait for it to start...
f := func() error {
var err error
if tektonEnabled {
names, defaultName, buildMap, pipelineMap, err = o.loadPipelines(kubeClient, tektonClient, jxClient, ns)
} else {
names, defaultName, buildMap, pipelineMap, err = o.loadBuilds(kubeClient, ns)
}
if err != nil {
return err
}
build = buildMap[name]
if build == nil {
build = pipelineMap[name]
if build != nil {
suffix = " #" + build.GetBuild()
}
}
if build == nil {
log.Infof("no build found in: %s\n", util.ColorInfo(strings.Join(names, ", ")))
return fmt.Errorf("No pipeline exists yet: %s", name)
}
return nil
}
err := util.Retry(o.WaitForPipelineDuration, f)
if err != nil {
return err
}
}
if build == nil {
return fmt.Errorf("No Pipeline found for name %s in values: %s", name, strings.Join(names, ", "))
}
if tektonEnabled {
pr := build.(*tekton.PipelineRunInfo)
log.Infof("Build logs for %s\n", util.ColorInfo(name+suffix))
for _, stage := range pr.GetOrderedTaskStages() {
if stage.Pod == nil {
// The stage's pod hasn't been created yet, so let's wait a bit.
f := func() error {
selector, err := metav1.LabelSelectorAsSelector(&metav1.LabelSelector{MatchLabels: map[string]string{
pipeline.GroupName + pipeline.PipelineRunLabelKey: pr.PipelineRun,
}})
if err != nil {
return err
}
podList, err := kubeClient.CoreV1().Pods(ns).List(metav1.ListOptions{
LabelSelector: selector.String(),
})
if err != nil {
return err
}
if err := stage.SetPodsForStageInfo(podList, pr.PipelineRun); err != nil {
return err
}
if stage.Pod == nil {
log.Infof("no pod found yet for stage %s in build %s\n", util.ColorInfo(stage.Name), util.ColorInfo(pr.PipelineRun))
return fmt.Errorf("No pod for stage %s in build %s exists yet", stage.Name, pr.PipelineRun)
}
return nil
}
err := util.Retry(o.WaitForPipelineDuration, f)
if err != nil {
return err
}
}
pod := stage.Pod
containers, _, _ := kube.GetContainersWithStatusAndIsInit(pod)
if len(containers) <= 0 {
return fmt.Errorf("No Containers for Pod %s for build: %s", pod.Name, name)
}
for i, ic := range containers {
pod, err := kubeClient.CoreV1().Pods(ns).Get(pod.Name, metav1.GetOptions{})
if err != nil {
return errors.Wrapf(err, "failed to find pod %s", pod.Name)
}
if i > 0 {
_, containerStatuses, _ := kube.GetContainersWithStatusAndIsInit(pod)
if i < len(containerStatuses) {
lastContainer := containerStatuses[i-1]
terminated := lastContainer.State.Terminated
if terminated != nil && terminated.ExitCode != 0 {
log.Warnf("container %s failed with exit code %d: %s\n", lastContainer.Name, terminated.ExitCode, terminated.Message)
}
}
}
pod, err = waitForContainerToStart(kubeClient, ns, pod, i)
if err != nil {
return err
}
err = o.getStageLog(ns, name+suffix, stage.GetStageNameIncludingParents(), pod, ic)
if err != nil {
return err
}
}
}
} else {
b := build.(*builds.BuildPodInfo)
pod := b.Pod
if pod == nil {
return fmt.Errorf("No Pod found for name %s", name)
}
containers, _, _ := kube.GetContainersWithStatusAndIsInit(pod)
if len(containers) <= 0 {
return fmt.Errorf("No Containers for Pod %s for build: %s", pod.Name, name)
}
log.Infof("Build logs for %s\n", util.ColorInfo(name+suffix))
for i, ic := range containers {
pod, err := kubeClient.CoreV1().Pods(ns).Get(pod.Name, metav1.GetOptions{})
if err != nil {
return errors.Wrapf(err, "failed to find pod %s", pod.Name)
}
if i > 0 {
_, containerStatuses, _ := kube.GetContainersWithStatusAndIsInit(pod)
if i < len(containerStatuses) {
lastContainer := containerStatuses[i-1]
terminated := lastContainer.State.Terminated
if terminated != nil && terminated.ExitCode != 0 {
log.Warnf("container %s failed with exit code %d: %s\n", lastContainer.Name, terminated.ExitCode, terminated.Message)
}
}
}
pod, err = waitForContainerToStart(kubeClient, ns, pod, i)
if err != nil {
return err
}
err = o.getPodLog(ns, pod, ic)
if err != nil {
return err
}
}
}
return nil
}
func waitForContainerToStart(kubeClient kubernetes.Interface, ns string, pod *corev1.Pod, idx int) (*corev1.Pod, error) {
if pod.Status.Phase == corev1.PodFailed {
log.Warnf("pod %s has failed\n", pod.Name)
return pod, nil
}
if kube.HasContainerStarted(pod, idx) {
return pod, nil
}
containerName := ""
containers, _, _ := kube.GetContainersWithStatusAndIsInit(pod)
if idx < len(containers) {
containerName = containers[idx].Name
}
log.Infof("waiting for pod %s container %s to start...\n", util.ColorInfo(pod.Name), util.ColorInfo(containerName))
for {
time.Sleep(time.Second)
p, err := kubeClient.CoreV1().Pods(ns).Get(pod.Name, metav1.GetOptions{})
if err != nil {
return p, errors.Wrapf(err, "failed to load pod %s", pod.Name)
}
if kube.HasContainerStarted(p, idx) {
return p, nil
}
}
}
func (o *GetBuildLogsOptions) getPodLog(ns string, pod *corev1.Pod, container corev1.Container) error {
log.Infof("getting the log for pod %s and container %s\n", util.ColorInfo(pod.Name), util.ColorInfo(container.Name))
return o.TailLogs(ns, pod.Name, container.Name)
}
func (o *GetBuildLogsOptions) getStageLog(ns, build, stageName string, pod *corev1.Pod, container corev1.Container) error {
log.Infof("getting the log for build %s stage %s and container %s\n", util.ColorInfo(build), util.ColorInfo(stageName), util.ColorInfo(container.Name))
return o.TailLogs(ns, pod.Name, container.Name)
}
func (o *GetBuildLogsOptions) loadBuilds(kubeClient kubernetes.Interface, ns string) ([]string, string, map[string]builds.BaseBuildInfo, map[string]builds.BaseBuildInfo, error) {
defaultName := ""
names := []string{}
buildMap := map[string]builds.BaseBuildInfo{}
pipelineMap := map[string]builds.BaseBuildInfo{}
pods, err := builds.GetBuildPods(kubeClient, ns)
if err != nil {
log.Warnf("Failed to query pods %s\n", err)
return names, defaultName, buildMap, pipelineMap, err
}
buildInfos := []*builds.BuildPodInfo{}
for _, pod := range pods {
containers, _, _ := kube.GetContainersWithStatusAndIsInit(pod)
if len(containers) > 0 {
buildInfo := builds.CreateBuildPodInfo(pod)
if o.BuildFilter.BuildMatches(buildInfo) {
buildInfos = append(buildInfos, buildInfo)
}
}
}
builds.SortBuildPodInfos(buildInfos)
if len(buildInfos) == 0 {
return names, defaultName, buildMap, pipelineMap, fmt.Errorf("no knative builds have been triggered which match the current filter")
}
for _, build := range buildInfos {
name := build.Pipeline + " #" + build.Build
names = append(names, name)
buildMap[name] = build
pipelineMap[build.Pipeline] = build
if build.Branch == "master" {
defaultName = name
}
}
return names, defaultName, buildMap, pipelineMap, nil
}
func (o *GetBuildLogsOptions) loadPipelines(kubeClient kubernetes.Interface, tektonClient tektonclient.Interface, jxClient versioned.Interface, ns string) ([]string, string, map[string]builds.BaseBuildInfo, map[string]builds.BaseBuildInfo, error) {
defaultName := ""
names := []string{}
buildMap := map[string]builds.BaseBuildInfo{}
pipelineMap := map[string]builds.BaseBuildInfo{}
prList, err := tektonClient.TektonV1alpha1().PipelineRuns(ns).List(metav1.ListOptions{})
if err != nil {
log.Warnf("Failed to query PipelineRuns %s\n", err)
return names, defaultName, buildMap, pipelineMap, err
}
structures, err := jxClient.JenkinsV1().PipelineStructures(ns).List(metav1.ListOptions{})
if err != nil {
log.Warnf("Failed to query PipelineStructures %s\n", err)
return names, defaultName, buildMap, pipelineMap, err
}
buildInfos := []*tekton.PipelineRunInfo{}
podList, err := kubeClient.CoreV1().Pods(ns).List(metav1.ListOptions{
LabelSelector: pipeline.GroupName + pipeline.PipelineRunLabelKey,
})
if err != nil {
return names, defaultName, buildMap, pipelineMap, err
}
for _, pr := range prList.Items {
var ps v1.PipelineStructure
for _, p := range structures.Items {
if p.Name == pr.Name {
ps = p
}
}
pri, err := tekton.CreatePipelineRunInfo(pr.Name, podList, &ps, &pr)
if err != nil {
if o.Verbose {
log.Warnf("Error creating PipelineRunInfo for PipelineRun %s: %s\n", pr.Name, err)
}
}
if pri != nil && o.BuildFilter.BuildMatches(pri.ToBuildPodInfo()) {
buildInfos = append(buildInfos, pri)
}
}
tekton.SortPipelineRunInfos(buildInfos)
if len(buildInfos) == 0 {
return names, defaultName, buildMap, pipelineMap, fmt.Errorf("no Tekton pipelines have been triggered which match the current filter")
}
for _, build := range buildInfos {
name := build.Pipeline + " #" + build.Build
names = append(names, name)
buildMap[name] = build
pipelineMap[build.Pipeline] = build
if build.Branch == "master" {
defaultName = name
}
}
return names, defaultName, buildMap, pipelineMap, nil
} | |
func.go | package public
func min(x, y int) int {
if x < y {
return x
}
return y
}
func | (x, y int) int {
if x > y {
return x
}
return y
}
func maxN(nums ...int) int {
if len(nums) == 0 {
return 0
}
max := nums[0]
for _, num := range nums {
if max < num {
max = num
}
}
return max
}
func minN(nums ...int) int {
if len(nums) == 0 {
return 0
}
min := nums[0]
for _, num := range nums {
if min > num {
min = num
}
}
return min
}
func abs(x int) int {
if x < 0 {
return -1 * x
}
return x
}
| max |
osm_reader.rs | use osmpbfreader::{Node, NodeId, OsmObj, OsmPbfReader, Way};
use std::collections::HashMap;
use std::time::Instant;
use osm_parse_config::OSMParseConfig;
use std;
fn filter_nodes_and_ways(
mut nodes: HashMap<NodeId, Node>,
mut ways: Vec<Way>,
osm_parse_config: &OSMParseConfig,
) -> (HashMap<NodeId, Node>, Vec<Way>) {
let mut ways_filtered: Vec<Way> = Vec::new();
let mut nodes_filtered: HashMap<NodeId, Node> = HashMap::new();
let nodes_initially = nodes.len();
let ways_initially = ways.len();
let now = Instant::now();
while !ways.is_empty() {
let way = ways.pop().unwrap();
let all_nodes_available = way
.nodes
.iter()
.all(|x| (nodes.contains_key(x) || nodes_filtered.contains_key(x)));
let is_area = way.tags.get("area").map(|x| x == "yes").unwrap_or(false);
let allowed_highway = way
.tags
.get("highway")
.map(|x| osm_parse_config.is_allowed(&(::NETWORK_TYPE), x))
.unwrap_or(false);
let way_ok = all_nodes_available && !is_area && allowed_highway;
if way_ok {
way.nodes
.iter()
.filter_map(|x| nodes.remove(x))
.for_each(|n| {
nodes_filtered.insert(n.id, n);
});
ways_filtered.push(way);
}
}
println!(
"filtered unnecessary nodes and ways: {}s",
now.elapsed().as_secs()
);
println!(
"#nodes now: {}/{} ({:.2}%)",
nodes_filtered.len(),
nodes_initially,
nodes_filtered.len() as f64 / nodes_initially as f64 * 100.0
);
println!(
"#ways now: {}/{} ({:.2}%)",
ways_filtered.len(),
ways_initially,
ways_filtered.len() as f64 / ways_initially as f64 * 100.0
);
println!();
(nodes_filtered, ways_filtered)
}
fn read_nodes_and_ways(file_reference: std::fs::File) -> (HashMap<NodeId, Node>, Vec<Way>) |
pub fn read_osm(filename: &str, config: &OSMParseConfig) -> (HashMap<NodeId, Node>, Vec<Way>) {
let file_reference = std::fs::File::open(&std::path::Path::new(filename)).unwrap();
let (nodes, ways) = read_nodes_and_ways(file_reference);
filter_nodes_and_ways(nodes, ways, config)
}
| {
let mut pbf = OsmPbfReader::new(file_reference);
let mut nodes = HashMap::new();
let mut ways = Vec::new();
let now = Instant::now();
for obj in pbf.par_iter().map(Result::unwrap) {
match obj {
OsmObj::Node(node) => {
nodes.insert(node.id, node);
}
OsmObj::Way(way) => {
ways.push(way);
}
_ => {}
}
}
println!("finished reading of osm data: {}s", now.elapsed().as_secs());
println!(
"data contains: {} ways, and {} nodes",
ways.len(),
nodes.len()
);
(nodes, ways)
} |
views.py | """Views for the wordrelaygame app."""
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect, render
from django.views.generic import View, DetailView, ListView
from .forms import WordForm
from .models import Story
class HomeView(DetailView):
"""Main view that displays the current story & information about the game.
Shows the current story and information about the game. If there is a user
logged in and it is their turn, it show a form to add a word to the story.
"""
context_object_name = 'latest_story'
model = Story
template_name = 'wordrelaygame/home.html'
def get_object(self, queryset=None):
try:
latest_story = Story.objects.latest('date_created')
except Story.DoesNotExist:
return None
else:
return latest_story
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs) | latest_word_auth_id = (self.object.words.order_by('-id')[0].
author.id)
except (AttributeError, IndexError):
latest_word_auth_id = None
if(kwargs.get('current_user_id') != latest_word_auth_id or
latest_word_auth_id is None):
context['form'] = WordForm()
return context
def get(self, request, *args, **kwargs):
self.object = self.get_object() # pylint: disable=locally-disabled, W0201
if request.user.is_authenticated:
current_user_id = request.user.id
else:
current_user_id = None
context = self.get_context_data(object=self.object,
current_user_id=current_user_id)
return self.render_to_response(context)
class StoryListView(ListView):
"""Show an archive of past stories."""
model = Story
paginate_by = 5
def get_queryset(self):
queryset = super().get_queryset()
return queryset.order_by('-date_created')
class AddWordView(LoginRequiredMixin, View):
"""Add a word to the latest story."""
http_method_names = ['post']
def post(self, request):
"""Handles the POST request to add a word to the latest story."""
try:
latest_story = Story.objects.latest('date_created')
except Story.DoesNotExist:
messages.error(request, 'You need to create a story to add a word.')
return redirect('wordrelaygame:home')
# Check the author of the previous word is different to the current
# logged in user.
try:
latest_word_auth_id = (latest_story.words.order_by('-id')[0].
author.id)
except IndexError:
latest_word_auth_id = None
if latest_word_auth_id == self.request.user.id:
messages.error(request, 'You added the last word. ' +
'Someone else needs to add a word next.')
return redirect('wordrelaygame:home')
# If the form is valid, save the new word
form = WordForm(request.POST)
if form.is_valid():
word = form.save(commit=False)
word.story = latest_story
word.author = self.request.user
word.save()
messages.success(request, 'Your word as been added. Thanks!')
return redirect('wordrelaygame:home')
return render(request, 'wordrelaygame/home.html',
{'form': form, 'latest_story': latest_story})
class AddStoryView(LoginRequiredMixin, View):
"""Create a new story.
Only allow the creation of a new story if there are no stories or if the
latest stories contains at least 64 words.
"""
http_method_names = ['post']
def post(self, request):
"""Handles the POST request to add a new story."""
add_story_allowed = False
try:
latest_story = Story.objects.latest('date_created')
except Story.DoesNotExist:
add_story_allowed = True
else:
if latest_story.words.count() > 64:
add_story_allowed = True
if add_story_allowed:
new_story = Story()
new_story.save()
messages.success(
request,
'A new story has been created. Now add the first word.'
)
else:
messages.error(
request,
('Failed to create new story. Add more '
'words to the current story instead.')
)
return redirect('wordrelaygame:home') |
# Only pass the form to the context if the current user is different
# to the user that wrote the last word of the story.
try: |
test_drone.py | # coding: utf-8
from __future__ import division, print_function, unicode_literals, absolute_import
import os
import unittest
# from pymatgen.io.lammps.sets import LammpsInputSet
# from pymatgen.io.lammps.output import LammpsLog
from atomate.utils.testing import AtomateTest
from atomate.lammps.drones import LammpsDrone
__author__ = 'Kiran Mathew'
__email__ = '[email protected]'
module_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)))
db_dir = os.path.join(module_dir, "..", "..", "common", "test_files")
LAMMPS_CMD = None # "lmp_serial"
@unittest.skip("Atomate Lammps does not work after pymatgen release v2018.5.22")
class TestLammpsDrone(AtomateTest):
def setUp(self):
super(TestLammpsDrone, self).setUp()
self.drone = LammpsDrone()
self.calc_dir = os.path.join(module_dir, "test_files")
self.input_file = os.path.join(self.calc_dir, "lammps.in")
self.data_file = os.path.join(self.calc_dir, "lammps.data")
self.log_file = os.path.join(self.calc_dir, "lammps.log")
def test_assimilate(self):
|
if __name__ == "__main__":
unittest.main()
| doc = self.drone.assimilate(self.calc_dir, input_filename="lammps.in",
log_filename="lammps.log",
data_filename="lammps.data")
lmps_input_set = LammpsInputSet.from_file("lammps", self.input_file,
{}, lammps_data=self.data_file,
data_filename="lammps.data")
# no dump file ==> output is just the log file
lmps_output = LammpsLog(self.log_file)
self.assertDictEqual(doc["input"], lmps_input_set.as_dict())
self.assertDictEqual(doc["output"]["log"], lmps_output.as_dict())
enthalpy = [1906.1958, 1220.2265, 596.51973, 465.01619, 148.91822, 26.160144,
319.27146, 141.35729, 299.04503, 271.19625, 145.4361]
self.assertEqual(lmps_output.as_dict()['thermo_data']['enthalpy'], enthalpy) |
log.go | // Copyright Ngo Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package accesslog
import (
"bytes"
"encoding/base64"
"fmt"
"io"
"net"
"net/http"
"os"
"strconv"
"strings"
"time"
"unicode"
"github.com/valyala/bytebufferpool"
"github.com/NetEase-Media/ngo/adapter/util"
"github.com/gin-gonic/gin"
)
// OptFunc is the type to use to options to the option struct during initialization
type OptFunc func(*opt)
// opt is the internal struct that holds the options for logging.
type opt struct {
Output io.Writer
Time time.Time
}
// newOpt returns a new struct to hold options, with the default output to stdout.
func newOpt() *opt {
o := new(opt)
o.Output = os.Stdout
return o
}
// WithOutput sets the io.Writer output for the log file.
func WithOutput(out io.Writer) OptFunc {
return func(o *opt) {
o.Output = out
}
}
// responseWriter is the internal struct that will wrap the http.ResponseWriter
// and hold the status and number of bytes written
type responseWriter struct {
gin.ResponseWriter
start time.Time
}
// startTime sets the start time to calculate the elapsed time for the %D directive
func (rw *responseWriter) startTime() {
rw.start = time.Now()
}
const (
// ApacheCommonLogFormat is the Apache Common Log directives
ApacheCommonLogFormat = `%h %l %u %t "%r" %>s %b`
// ApacheCombinedLogFormat is the Apache Combined Log directives
ApacheCombinedLogFormat = `%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-agent}i"`
)
var timeFmtMap = map[rune]string{
'a': "Mon", 'A': "Monday", 'b': "Jan", 'B': "January", 'C': "06",
'd': "02", 'D': "01/02/06", 'e': "_2", 'F': "2006-01-02",
'f': "15:04:05.000",
'h': "Jan", 'H': "15", 'I': "3", 'k': "•15", 'l': "_3",
'm': "01", 'M': "04", 'n': "\n", 'p': "PM", 'P': "pm",
'r': "03:04:05 PM", 'R': "15:04", 'S': "05",
't': "\t", 'T': "15:04:05", 'y': "06", 'Y': "2006",
'z': "-700", 'Z': "MST", '%': "%%",
// require calculated time
'G': "%v", 'g': "%v", 'j': "%v", 's': "%v",
'u': "%v", 'V': "%v", 'w': "%v",
// Unsupported directives
'c': "?", 'E': "?", 'O': "?", 'U': "?",
'W': "?", 'x': "?", 'X': "?", '+': "?",
}
// convertTimeFormat converts strftime formatting directives to a go time.Time format
func convertTimeFormat(now time.Time, format string) string {
var isDirective bool
var buf = new(bytes.Buffer)
for _, r := range format {
if !isDirective && r == '%' {
isDirective = true
continue
}
if !isDirective {
buf.WriteRune(r)
continue
}
if val, ok := timeFmtMap[r]; ok {
switch val {
case "%v":
switch r {
case 'G':
y, _ := now.ISOWeek()
buf.WriteString(strconv.Itoa(y))
case 'g':
y, _ := now.ISOWeek()
y -= (y / 100) * 100
buf.WriteString(fmt.Sprintf("%02d", y))
case 'j':
buf.WriteString(strconv.Itoa(now.YearDay()))
case 's':
buf.WriteString(strconv.FormatInt(now.Unix(), 10))
case 'u':
w := now.Weekday()
if w == 0 {
w = 7
}
buf.WriteString(strconv.Itoa(int(w)))
case 'V':
_, w := now.ISOWeek()
buf.WriteString(strconv.Itoa(w))
case 'w':
buf.WriteString(strconv.Itoa(int(now.Weekday())))
}
default:
buf.WriteString(now.Format(val))
}
isDirective = false
continue
}
buf.WriteString("(%" + string(r) + " is invalid)")
}
return buf.String()
}
// line is the type that will hold all of the runtime formating directives for the log line
type line struct {
time time.Time
request *http.Request
writer *responseWriter
keys map[string]interface{}
// directives
a, A, b, B, h, H, l, m, p, q, r, s, S, t, u, U, v, D, T, I string
}
func (ln *line) withTime(o *opt) *line {
if !o.Time.IsZero() {
ln.time = o.Time
return ln
}
ln.time = time.Now()
return ln
}
func (ln *line) withRequest(r *http.Request) *line {
ln.request = r
return ln
}
func (ln *line) withResponse(a *responseWriter) *line {
ln.writer = a
return ln
}
func (ln *line) withKeys(k map[string]interface{}) *line {
ln.keys = k
return ln
}
// remoteAddr - %a
func (ln *line) remoteAddr() string {
if len(ln.a) == 0 {
remoteIp, _, _ := net.SplitHostPort(strings.TrimSpace(ln.request.RemoteAddr))
ln.a = remoteIp
if len(ln.a) == 0 {
ln.a = "-"
}
}
return ln.a
}
// localAddr - %A
func (ln *line) localAddr() string {
if len(ln.A) == 0 {
ip, _ := util.GetOutBoundIP()
ln.A = ip
if len(ln.A) == 0 {
ln.A = "-"
}
}
return ln.A
}
// bytesWritten - %b
func (ln *line) bytesWritten() string {
if len(ln.b) == 0 {
size := ln.writer.Size()
if size == 0 {
ln.b = "-"
} else {
ln.b = strconv.Itoa(size)
}
}
return ln.b
}
// bytesWritten - %B
func (ln *line) bytesWritten2() string {
if len(ln.B) == 0 {
ln.B = strconv.Itoa(ln.writer.Size())
}
return ln.B
}
// remoteHostname - %h
func (ln *line) remoteHostname() string {
if len(ln.h) == 0 {
ln.h = ln.request.URL.Host
if len(ln.h) == 0 {
ln.h = "-"
}
}
return ln.h
}
// protocol - %H
func (ln *line) protocol() string {
if len(ln.H) == 0 {
ln.H = ln.request.Proto
}
return ln.H
}
// remoteUsername - %l
func (ln *line) remoteUsername() string {
if len(ln.l) == 0 {
ln.l = "-"
}
return ln.l
}
// method - %m
func (ln *line) method() string {
if len(ln.m) == 0 {
ln.m = ln.request.Method
}
return ln.m
}
// port - %m
func (ln *line) port() string {
if len(ln.p) == 0 {
ln.p = "-"
}
return ln.p
}
// queryString - %q
func (ln *line) queryString() string {
if len(ln.q) == 0 {
query := ln.request.URL.RawQuery
if len(query) > 0 {
ln.q = "?" + query
} else {
ln.q = "-"
}
}
return ln.q
}
// requestLine - %r
func (ln *line) requestLine() string {
if len(ln.r) == 0 {
ln.r = strings.ToUpper(ln.request.Method) + " " + ln.request.RequestURI + " " + ln.request.Proto
}
return ln.r
}
// status - %s
func (ln *line) status() string {
if len(ln.s) == 0 {
ln.s = strconv.Itoa(ln.writer.Status())
}
return ln.s
}
// sessionId - %S
func (ln *line) sessionId() string {
if len(ln.S) == 0 {
ln.S = "-"
}
return ln.S
}
// timeFormatted - %t
func (ln *line) timeFormatted(format string) string {
if len(ln.t) == 0 {
ln.t = ln.time.Format(format)
}
return ln.t
}
// username - %u
func (ln *line) username() string {
if len(ln.u) == 0 {
ln.u = "-"
if s := strings.SplitN(ln.request.Header.Get("Authorization"), " ", 2); len(s) == 2 {
if b, err := base64.StdEncoding.DecodeString(s[1]); err == nil {
if pair := strings.SplitN(string(b), ":", 2); len(pair) == 2 {
ln.u = pair[0]
}
}
}
}
return ln.u
}
// url - %U
func (ln *line) url() string {
if len(ln.U) == 0 {
ln.U = ln.request.URL.Path
}
return ln.U
}
// serviceName - %v
func (ln *line) serviceName() string {
if len(ln.v) == 0 {
ln.v = "-"
}
return ln.v
}
// timeElapsedMs - %D
func (ln *line) timeElapsedMs(cost time.Duration) string {
if len(ln.D) == 0 {
ln.D = strconv.FormatInt(cost.Milliseconds(), 10)
}
return ln.D
}
// timeElapsedSeconds - %T
func (ln *line) timeElapsedSeconds(cost time.Duration) string {
if len(ln.T) == 0 {
ln.T = strconv.FormatFloat(cost.Seconds(), 'f', 3, 64)
}
return ln.T
}
// threadName - %I
func (ln *line) threadName() string {
if len(ln.I) == 0 {
ln.I = "-"
}
return ln.I
}
// flatten takes two slices and merges them into one
func flatten(o *opt, a, b []string) func(w *responseWriter, r *http.Request, k map[string]interface{}) string {
return func(w *responseWriter, r *http.Request, k map[string]interface{}) string {
ln := new(line)
ln.withTime(o).withRequest(r).withResponse(w).withKeys(k)
cost := time.Since(ln.writer.start)
buf := bytebufferpool.Get()
for i, s := range a {
switch s {
case "":
buf.WriteString(b[i])
case "%a":
buf.WriteString(ln.remoteAddr())
case "%A":
buf.WriteString(ln.localAddr())
case "%b":
buf.WriteString(ln.bytesWritten())
case "%B":
buf.WriteString(ln.bytesWritten2())
case "%h":
buf.WriteString(ln.remoteHostname())
case "%H":
buf.WriteString(ln.protocol())
case "%l":
buf.WriteString(ln.remoteUsername())
case "%m":
buf.WriteString(ln.method())
case "%p":
buf.WriteString(ln.port())
case "%q":
buf.WriteString(ln.queryString())
case "%r":
buf.WriteString(ln.requestLine())
case "%s", "%>s":
buf.WriteString(ln.status())
case "%S":
buf.WriteString(ln.sessionId())
case "%t":
buf.WriteString(ln.timeFormatted("[02/01/2006:15:04:05 -0700]"))
case "%u":
buf.WriteString(ln.username())
case "%U":
buf.WriteString(ln.url())
case "%v":
buf.WriteString(ln.serviceName())
case "%D":
buf.WriteString(ln.timeElapsedMs(cost))
case "%T":
buf.WriteString(ln.timeElapsedSeconds(cost))
case "%I":
buf.WriteString(ln.threadName())
default:
if len(s) > 4 && s[:2] == "%{" && s[len(s)-2] == '}' {
label := s[2 : len(s)-2]
switch s[len(s)-1] {
case 'i':
reqHeader := r.Header.Get(label)
if len(reqHeader) == 0 {
reqHeader = "-"
}
buf.WriteString(reqHeader)
case 'o':
rspHeader := w.Header().Get(label)
if len(rspHeader) == 0 {
rspHeader = "-"
}
buf.WriteString(rspHeader)
case 'c':
if cookie, err := r.Cookie(label); err != nil && cookie != nil && len(cookie.Value) > 0 {
buf.WriteString(cookie.Value)
} else {
buf.WriteString("-")
}
case 't':
buf.WriteString(convertTimeFormat(ln.time, label))
case 'r':
if v, ok := ln.keys[label]; ok {
buf.WriteString(v.(string))
} else {
buf.WriteString("-")
}
}
}
}
}
s := buf.String()
bytebufferpool.Get()
return s
}
}
// FormatWith accepts a format string using Apache formatting directives with
// option functions and returns a function that can handle standard Gin middleware.
func Fo | ormat string, opts ...OptFunc) func(c *gin.Context) {
if strings.EqualFold("common", format) {
format = ApacheCommonLogFormat
} else if strings.EqualFold("combined", format) {
format = ApacheCombinedLogFormat
}
options := newOpt()
for _, opt := range opts {
opt(options)
}
var directives, betweens = make([]string, 0, 50), make([]string, 0, 50)
var cBuf *bytes.Buffer // current buffer
aBuf, bBuf := new(bytes.Buffer), new(bytes.Buffer)
cBuf = bBuf
var isDirective, isEnclosure bool
for i, r := range format {
switch r {
case '%':
if isDirective {
cBuf.WriteRune(r)
continue
}
isDirective = true
if i != 0 {
directives = append(directives, aBuf.String())
betweens = append(betweens, bBuf.String())
aBuf.Reset()
bBuf.Reset()
}
cBuf = aBuf
case '{':
isEnclosure = true
case '}':
isEnclosure = false
case '>':
// nothing - no change in status
default:
if isDirective && !isEnclosure && !unicode.IsLetter(r) {
isDirective = false
isEnclosure = false
if i != 0 {
directives = append(directives, aBuf.String())
betweens = append(betweens, bBuf.String())
aBuf.Reset()
bBuf.Reset()
}
cBuf = bBuf
}
}
cBuf.WriteRune(r)
}
directives = append(directives, aBuf.String())
betweens = append(betweens, bBuf.String())
aBuf.Reset()
bBuf.Reset()
logFunc := flatten(options, directives, betweens)
return func(c *gin.Context) {
rw := &responseWriter{ResponseWriter: c.Writer}
rw.startTime()
c.Next()
_, err := fmt.Fprintln(options.Output, logFunc(rw, c.Request, c.Keys))
if err != nil {
panic(err)
}
}
}
| rmatWith(f |
hmac.rs | /*!
This module contains structures for describing and interacting with HMAC
algorithms and tags.
Unlike the `compression` and `encryption` modules, there is not a `NoHMAC`
option, as the repository's structure does not make sense without an HMAC
algorithm.
As such, at least one HMAC algorithm feature must be enabled, or else you will
get a compile time error.
*/
#[cfg(feature = "blake2b_simd")]
use blake2b_simd::blake2bp;
#[cfg(feature = "blake2b_simd")]
use blake2b_simd::Params;
use cfg_if::cfg_if;
#[allow(unused_imports)]
use crypto_mac::NewMac;
#[allow(unused_imports)]
use hmac::{Hmac, Mac};
use serde::{Deserialize, Serialize};
#[cfg(feature = "sha2")]
use sha2::Sha256;
#[cfg(feature = "sha3")]
use sha3::Sha3_256;
use crate::repository::Key;
use std::cmp::min;
#[cfg(not(any(
feature = "blake2b_simd",
feature = "sha2",
feature = "sha3",
feature = "blake3"
)))]
compile_error!("Asuran requires at least one HMAC algorithim to be enabled.");
#[cfg(feature = "sha2")]
type HmacSha256 = Hmac<Sha256>;
#[cfg(feature = "sha3")]
type HmacSHA3 = Hmac<Sha3_256>;
/// Tag for the HMAC algorithim used by a particular `Chunk`
#[derive(Deserialize, Serialize, Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum HMAC {
SHA256,
Blake2b,
Blake2bp,
Blake3,
SHA3,
}
impl HMAC {
/// Produces an HMAC for the given data with the given key, using the algorithm
/// specified by the variant of `self`.
///
/// # Panics
///
/// Will panic if the user attempts to produce an HMAC using an algorithm for which
/// support was not compiled in.
#[allow(unused_variables)]
fn internal_mac(self, data: &[u8], key: &[u8]) -> Vec<u8> {
match self {
HMAC::SHA256 => {
cfg_if! {
if #[cfg(feature = "sha2")] {
let mut mac = HmacSha256::new_varkey(key)
.expect("HmacSHA256 was provided with a key of invalid length.");
mac.update(data);
mac.finalize().into_bytes().as_slice().to_vec()
} else {
unimplemented!("Asuran was not compiled with SHA2 support")
}
}
}
HMAC::Blake2b => {
cfg_if! {
if #[cfg(feature = "blake2b_simd")] {
Params::new()
.hash_length(64)
.key(key)
.hash(data)
.as_bytes()
.to_vec()
} else {
unimplemented!("Asuran was not compiled with BLAKE2b support")
}
}
}
HMAC::Blake2bp => {
cfg_if! {
if #[cfg(feature = "blake2b_simd")] {
blake2bp::Params::new()
.hash_length(64)
.key(key)
.hash(data)
.as_bytes()
.to_vec()
} else {
unimplemented!("Asuran was not compiled with BLAKE2b support")
}
}
}
HMAC::Blake3 => {
cfg_if! {
if #[cfg(feature = "blake3")] {
let mut tmp_key = [0_u8; 32];
let len = min(32, key.len());
tmp_key[..len].copy_from_slice(&key[..len]);
blake3::keyed_hash(&tmp_key, data).as_bytes().to_vec()
} else {
unimplemented!("Asuran was not compiled with BLAKE3 support")
}
}
}
HMAC::SHA3 => {
cfg_if! {
if #[cfg(feature = "sha3")] {
let mut mac = HmacSHA3::new_varkey(key)
.expect("HmacSHA3 was provided with a key of invalid length.");
mac.update(data);
mac.finalize().into_bytes().as_slice().to_vec()
} else {
unimplemented!("Asuran was not compiled with SHA3 support")
}
}
}
}
}
/// Produces an HMAC tag using the section of the key material reserved for
/// integrity verification.
///
/// # Panics
///
/// Will panic if the user has selected an algorithm for which support has not been
/// compiled in.
pub fn mac(self, data: &[u8], key: &Key) -> Vec<u8> {
let key = key.hmac_key();
self.internal_mac(data, key)
}
/// Produces an HMAC tag using the section of the key material reserved for
/// `ChunkID` generation.
///
/// # Panics
///
/// Will panic if the user has selected an algorithm for which support has not been
/// compiled in.
pub fn id(self, data: &[u8], key: &Key) -> Vec<u8> {
let key = key.id_key();
self.internal_mac(data, key)
}
/// Produces an HMAC for the supplied data, using the portion of the supplied key
/// reserved for integrity verification, and the algorithm specified by the variant
/// of `self`, and verifies it against the supplied HMAC, using constant time
/// comparisons where possible.
///
/// # Panics
///
/// Panics if the user has selected an algorithm for which support has not been
/// compiled in.
#[allow(unused_variables)]
pub fn verify_hmac(self, input_mac: &[u8], data: &[u8], key: &Key) -> bool {
let key = key.hmac_key();
match self {
HMAC::SHA256 => {
cfg_if! {
if #[cfg(feature = "sha2")] {
let mut mac = HmacSha256::new_varkey(key)
.expect("HmacSHA256 was provided with a key of invalid length.");
mac.update(data);
let result = mac.verify(input_mac);
result.is_ok()
} else {
unimplemented!("Asuran was not compiled with SHA2 support")
}
}
}
HMAC::Blake2b => {
cfg_if! {
if #[cfg(feature = "blake2b_simd")] {
let hash = Params::new().hash_length(64).key(key).hash(data);
hash.eq(input_mac)
} else {
unimplemented!("Asuran was not compiled with BLAKE2b support")
}
}
}
HMAC::Blake2bp => {
cfg_if! {
if #[cfg(feature = "blake2b_simd")] {
let hash = blake2bp::Params::new().hash_length(64).key(key).hash(data);
hash.eq(input_mac)
} else {
unimplemented!("Asuran was not compiled with BLAKE2b support")
}
}
}
HMAC::Blake3 => {
cfg_if! {
if #[cfg(feature = "blake3")] {
let mut tmp_hash = [0_u8; 32];
tmp_hash.copy_from_slice(&input_mac[..32]);
let mut tmp_key = [0_u8; 32];
tmp_key.copy_from_slice(&key[..32]);
let input_hash = blake3::Hash::from(tmp_hash);
let output_hash = blake3::keyed_hash(&tmp_key, data);
output_hash.eq(&input_hash)
} else {
unimplemented!("Asuran was not compiled with BLAKE3 support")
}
}
}
HMAC::SHA3 => |
}
}
}
| {
cfg_if! {
if #[cfg(feature = "sha3")] {
let mut mac = HmacSHA3::new_varkey(key)
.expect("HmacSHA3 was provided with a key of invalid length");
mac.update(data);
let result = mac.verify(input_mac);
result.is_ok()
} else {
unimplemented!("Asuran was not compiled with SHA3 support")
}
}
} |
role.model.ts | import { BelongsToMany, Column, DataType, Model, Table } from 'sequelize-typescript';
import { ApiProperty } from '@nestjs/swagger';
import { User } from '../users/users.model';
import { UserRoles } from './user-roles.model';
interface RoleCreationAttr {
value: string
description: string
}
@Table({tableName: 'roles'})
export class | extends Model<Role, RoleCreationAttr> {
@ApiProperty({example: 'Manager', description: 'Значение роли пользователя'})
@Column({type: DataType.STRING, unique: true, allowNull: false})
value: string;
@ApiProperty({example: 'Супервайзер', description: 'Описание роли пользователя'})
@Column({type: DataType.STRING, allowNull: false})
description: string;
@BelongsToMany(() => User, () => UserRoles)
users: User[]
} | Role |
cloudpipe.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License. |
from patronclient.tests.unit.fixture_data import base
class Fixture(base.Fixture):
base_url = 'os-cloudpipe'
def setUp(self):
super(Fixture, self).setUp()
get_os_cloudpipe = {'cloudpipes': [{'project_id': 1}]}
self.requests.register_uri('GET', self.url(),
json=get_os_cloudpipe,
headers=self.json_headers)
instance_id = '9d5824aa-20e6-4b9f-b967-76a699fc51fd'
post_os_cloudpipe = {'instance_id': instance_id}
self.requests.register_uri('POST', self.url(),
json=post_os_cloudpipe,
headers=self.json_headers,
status_code=202)
self.requests.register_uri('PUT', self.url('configure-project'),
headers=self.json_headers,
status_code=202) | |
stream.rs | #![allow(clippy::upper_case_acronyms)]
use crate::{AeadCore, AeadInPlace, Buffer, Error, Key, NewAead, Result};
use core::ops::{AddAssign, Sub};
use generic_array::{
typenum::{Unsigned, U4, U5},
ArrayLength, GenericArray,
};
#[cfg(feature = "alloc")]
use {crate::Payload, alloc::vec::Vec};
pub type Nonce<A, S> = GenericArray<u8, NonceSize<A, S>>;
pub type NonceSize<A, S> =
<<A as AeadCore>::NonceSize as Sub<<S as StreamPrimitive<A>>::NonceOverhead>>::Output;
pub type EncryptorBE32<A> = Encryptor<A, StreamBE32<A>>;
pub type DecryptorBE32<A> = Decryptor<A, StreamBE32<A>>;
pub type EncryptorLE31<A> = Encryptor<A, StreamLE31<A>>;
pub type DecryptorLE31<A> = Decryptor<A, StreamLE31<A>>;
pub trait NewStream<A>: StreamPrimitive<A>
where
A: AeadInPlace,
A::NonceSize: Sub<Self::NonceOverhead>,
NonceSize<A, Self>: ArrayLength<u8>,
{
fn new(key: &Key<A>, nonce: &Nonce<A, Self>) -> Self
where
A: NewAead,
Self: Sized,
{
Self::from_aead(A::new(key), nonce)
}
fn from_aead(aead: A, nonce: &Nonce<A, Self>) -> Self;
}
pub trait StreamPrimitive<A>
where
A: AeadInPlace,
A::NonceSize: Sub<Self::NonceOverhead>,
NonceSize<A, Self>: ArrayLength<u8>,
{
type NonceOverhead: ArrayLength<u8>;
type Counter: AddAssign + Copy + Default + Eq;
const COUNTER_INCR: Self::Counter;
const COUNTER_MAX: Self::Counter;
fn encrypt_in_place(
&self,
position: Self::Counter,
last_block: bool,
associated_data: &[u8],
buffer: &mut dyn Buffer,
) -> Result<()>;
fn decrypt_in_place(
&self,
position: Self::Counter,
last_block: bool,
associated_data: &[u8],
buffer: &mut dyn Buffer,
) -> Result<()>;
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
fn encrypt<'msg, 'aad>(
&self,
position: Self::Counter,
last_block: bool,
plaintext: impl Into<Payload<'msg, 'aad>>,
) -> Result<Vec<u8>> {
let payload = plaintext.into();
let mut buffer = Vec::with_capacity(payload.msg.len() + A::TagSize::to_usize());
buffer.extend_from_slice(payload.msg);
self.encrypt_in_place(position, last_block, payload.aad, &mut buffer)?;
Ok(buffer)
}
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
fn decrypt<'msg, 'aad>(
&self,
position: Self::Counter,
last_block: bool,
ciphertext: impl Into<Payload<'msg, 'aad>>,
) -> Result<Vec<u8>> {
let payload = ciphertext.into();
let mut buffer = Vec::from(payload.msg);
self.decrypt_in_place(position, last_block, payload.aad, &mut buffer)?;
Ok(buffer)
}
fn encryptor(self) -> Encryptor<A, Self>
where
Self: Sized,
{
Encryptor::from_stream_primitive(self)
}
fn decryptor(self) -> Decryptor<A, Self>
where
Self: Sized,
{
Decryptor::from_stream_primitive(self)
}
}
macro_rules! impl_stream_object {
(
$name:ident,
$next_method:tt,
$next_in_place_method:tt,
$last_method:tt,
$last_in_place_method:tt,
$op:tt,
$in_place_op:tt,
$op_desc:expr,
$obj_desc:expr
) => {
#[doc = "Stateful STREAM object which can"]
#[doc = $op_desc]
#[doc = "AEAD messages one-at-a-time."]
#[doc = ""]
#[doc = "This corresponds to the "]
#[doc = $obj_desc]
#[doc = "object as defined in the paper"]
#[doc = "[Online Authenticated-Encryption and its Nonce-Reuse Misuse-Resistance][1]."]
#[doc = ""]
#[doc = "[1]: https://eprint.iacr.org/2015/189.pdf"]
pub struct $name<A, S>
where
A: AeadInPlace,
S: StreamPrimitive<A>,
A::NonceSize: Sub<<S as StreamPrimitive<A>>::NonceOverhead>,
NonceSize<A, S>: ArrayLength<u8>,
{
stream: S,
position: S::Counter,
}
impl<A, S> $name<A, S>
where
A: AeadInPlace,
S: StreamPrimitive<A>,
A::NonceSize: Sub<<S as StreamPrimitive<A>>::NonceOverhead>,
NonceSize<A, S>: ArrayLength<u8>,
{
#[doc = "Create a"]
#[doc = $obj_desc]
#[doc = "object from the given AEAD key and nonce."]
pub fn new(key: &Key<A>, nonce: &Nonce<A, S>) -> Self
where
A: NewAead,
S: NewStream<A>,
{
Self::from_stream_primitive(S::new(key, nonce))
}
#[doc = "Create a"]
#[doc = $obj_desc]
#[doc = "object from the given AEAD primitive."]
pub fn from_aead(aead: A, nonce: &Nonce<A, S>) -> Self
where
A: NewAead,
S: NewStream<A>,
{
Self::from_stream_primitive(S::from_aead(aead, nonce))
}
#[doc = "Create a"]
#[doc = $obj_desc]
#[doc = "object from the given STREAM primitive."]
pub fn from_stream_primitive(stream: S) -> Self {
Self {
stream,
position: Default::default(),
}
}
#[doc = "Use the underlying AEAD to"]
#[doc = $op_desc]
#[doc = "the next AEAD message in this STREAM, returning the"]
#[doc = "result as a [`Vec`]."]
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn $next_method<'msg, 'aad>(
&mut self,
payload: impl Into<Payload<'msg, 'aad>>,
) -> Result<Vec<u8>> {
if self.position == S::COUNTER_MAX {
return Err(Error);
}
let result = self.stream.$op(self.position, false, payload)?;
self.position += S::COUNTER_INCR;
Ok(result)
}
#[doc = "Use the underlying AEAD to"]
#[doc = $op_desc]
#[doc = "the next AEAD message in this STREAM in-place."]
pub fn $next_in_place_method(
&mut self,
associated_data: &[u8],
buffer: &mut dyn Buffer,
) -> Result<()> {
if self.position == S::COUNTER_MAX {
return Err(Error);
}
self.stream
.$in_place_op(self.position, false, associated_data, buffer)?;
self.position += S::COUNTER_INCR;
Ok(())
}
#[doc = "Use the underlying AEAD to"]
#[doc = $op_desc]
#[doc = "the last AEAD message in this STREAM,"]
#[doc = "consuming the "]
#[doc = $obj_desc]
#[doc = "object in order to prevent further use."]
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn $last_method<'msg, 'aad>(
self,
payload: impl Into<Payload<'msg, 'aad>>,
) -> Result<Vec<u8>> {
self.stream.$op(self.position, true, payload)
}
#[doc = "Use the underlying AEAD to"]
#[doc = $op_desc]
#[doc = "the last AEAD message in this STREAM in-place,"]
#[doc = "consuming the "]
#[doc = $obj_desc]
#[doc = "object in order to prevent further use."]
pub fn $last_in_place_method(
self,
associated_data: &[u8],
buffer: &mut dyn Buffer,
) -> Result<()> {
self.stream
.$in_place_op(self.position, true, associated_data, buffer)
}
}
};
}
impl_stream_object!(
Encryptor,
encrypt_next,
encrypt_next_in_place,
encrypt_last,
encrypt_last_in_place,
encrypt,
encrypt_in_place,
"encrypt",
"ℰ STREAM encryptor"
);
impl_stream_object!(
Decryptor,
decrypt_next,
decrypt_next_in_place,
decrypt_last,
decrypt_last_in_place,
decrypt,
decrypt_in_place,
"decrypt",
"𝒟 STREAM decryptor"
);
pub struct StreamBE32<A>
where
A: AeadInPlace,
A::NonceSize: Sub<U5>,
<<A as AeadCore>::NonceSize as Sub<U5>>::Output: ArrayLength<u8>,
{
aead: A,
nonce: Nonce<A, Self>,
}
impl<A> NewStream<A> for StreamBE32<A>
where
A: AeadInPlace,
A::NonceSize: Sub<U5>,
<<A as AeadCore>::NonceSize as Sub<U5>>::Output: ArrayLength<u8>,
{
fn from_aead(aead: A, nonce: &Nonce<A, Self>) -> Self {
Self {
aead,
nonce: nonce.clone(),
}
}
}
impl<A> StreamPrimitive<A> for StreamBE32<A>
where
A: AeadInPlace,
A::NonceSize: Sub<U5>,
<<A as AeadCore>::NonceSize as Sub<U5>>::Output: ArrayLength<u8>,
{
type NonceOverhead = U5;
type Counter = u32;
const COUNTER_INCR: u32 = 1;
const COUNTER_MAX: u32 = core::u32::MAX;
fn encrypt_in_place(
&self,
position: u32,
last_block: bool,
associated_data: &[u8],
buffer: &mut dyn Buffer,
) -> Result<()> {
let nonce = self.aead_nonce(position, last_block);
self.aead.encrypt_in_place(&nonce, associated_data, buffer)
}
fn decrypt_in_place(
&self,
position: Self::Counter,
last_block: bool,
associated_data: &[u8],
buffer: &mut dyn Buffer,
) -> Result<()> {
let nonce = self.aead_nonce(position, last_block);
self.aead.decrypt_in_place(&nonce, associated_data, buffer)
}
}
impl<A> StreamBE32<A>
where
A: AeadInPlace,
A::NonceSize: Sub<U5>,
<<A as AeadCore>::NonceSize as Sub<U5>>::Output: ArrayLength<u8>,
{
fn aead_nonce(&self, position: u32, last_block: bool) -> crate::Nonce<A> {
let mut result = GenericArray::default();
let (prefix, tail) = result.split_at_mut(NonceSize::<A, Self>::to_usize());
prefix.copy_from_slice(&self.nonce);
let (counter, flag) = tail.split_at_mut(4);
counter.copy_from_slice(&position.to_be_bytes());
flag[0] = last_block as u8;
result
}
}
pub struct StreamLE31<A>
where
A: AeadInPlace,
A::NonceSize: Sub<U4>,
<<A as AeadCore>::NonceSize as Sub<U4>>::Output: ArrayLength<u8>,
{ | }
impl<A> NewStream<A> for StreamLE31<A>
where
A: AeadInPlace,
A::NonceSize: Sub<U4>,
<<A as AeadCore>::NonceSize as Sub<U4>>::Output: ArrayLength<u8>,
{
fn from_aead(aead: A, nonce: &Nonce<A, Self>) -> Self {
Self {
aead,
nonce: nonce.clone(),
}
}
}
impl<A> StreamPrimitive<A> for StreamLE31<A>
where
A: AeadInPlace,
A::NonceSize: Sub<U4>,
<<A as AeadCore>::NonceSize as Sub<U4>>::Output: ArrayLength<u8>,
{
type NonceOverhead = U4;
type Counter = u32;
const COUNTER_INCR: u32 = 1;
const COUNTER_MAX: u32 = 0xfff_ffff;
fn encrypt_in_place(
&self,
position: u32,
last_block: bool,
associated_data: &[u8],
buffer: &mut dyn Buffer,
) -> Result<()> {
let nonce = self.aead_nonce(position, last_block)?;
self.aead.encrypt_in_place(&nonce, associated_data, buffer)
}
fn decrypt_in_place(
&self,
position: Self::Counter,
last_block: bool,
associated_data: &[u8],
buffer: &mut dyn Buffer,
) -> Result<()> {
let nonce = self.aead_nonce(position, last_block)?;
self.aead.decrypt_in_place(&nonce, associated_data, buffer)
}
}
impl<A> StreamLE31<A>
where
A: AeadInPlace,
A::NonceSize: Sub<U4>,
<<A as AeadCore>::NonceSize as Sub<U4>>::Output: ArrayLength<u8>,
{
fn aead_nonce(&self, position: u32, last_block: bool) -> Result<crate::Nonce<A>> {
if position > Self::COUNTER_MAX {
return Err(Error);
}
let mut result = GenericArray::default();
let (prefix, tail) = result.split_at_mut(NonceSize::<A, Self>::to_usize());
prefix.copy_from_slice(&self.nonce);
let position_with_flag = position | ((last_block as u32) << 31);
tail.copy_from_slice(&position_with_flag.to_le_bytes());
Ok(result)
}
} | aead: A,
nonce: Nonce<A, Self>, |
node.go | package lntest
import (
"bytes"
"encoding/hex"
"flag"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"sync"
"time"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
macaroon "gopkg.in/macaroon.v2"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/rpcclient"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/go-errors/errors"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/macaroons"
)
var (
// numActiveNodes is the number of active nodes within the test network.
numActiveNodes = 0
// defaultNodePort is the initial p2p port which will be used by the
// first created lightning node to listen on for incoming p2p
// connections. Subsequent allocated ports for future Lightning nodes
// instances will be monotonically increasing numbers calculated as
// such: defaultP2pPort + (3 * harness.nodeNum).
defaultNodePort = 19555
// defaultClientPort is the initial rpc port which will be used by the
// first created lightning node to listen on for incoming rpc
// connections. Subsequent allocated ports for future rpc harness
// instances will be monotonically increasing numbers calculated
// as such: defaultP2pPort + (3 * harness.nodeNum).
defaultClientPort = 19556
// defaultRestPort is the initial rest port which will be used by the
// first created lightning node to listen on for incoming rest
// connections. Subsequent allocated ports for future rpc harness
// instances will be monotonically increasing numbers calculated
// as such: defaultP2pPort + (3 * harness.nodeNum).
defaultRestPort = 19557
// logOutput is a flag that can be set to append the output from the
// seed nodes to log files.
logOutput = flag.Bool("logoutput", false,
"log output from node n to file outputn.log")
// logPubKeyBytes is the number of bytes of the node's PubKey that
// will be appended to the log file name. The whole PubKey is too
// long and not really necessary to quickly identify what node
// produced which log file.
logPubKeyBytes = 4
// trickleDelay is the amount of time in milliseconds between each
// release of announcements by AuthenticatedGossiper to the network.
trickleDelay = 50
)
// generateListeningPorts returns three ints representing ports to listen on
// designated for the current lightning network test. If there haven't been any
// test instances created, the default ports are used. Otherwise, in order to
// support multiple test nodes running at once, the p2p, rpc, and rest ports
// are incremented after each initialization.
func generateListeningPorts() (int, int, int) {
var p2p, rpc, rest int
if numActiveNodes == 0 {
p2p = defaultNodePort
rpc = defaultClientPort
rest = defaultRestPort
} else {
p2p = defaultNodePort + (3 * numActiveNodes)
rpc = defaultClientPort + (3 * numActiveNodes)
rest = defaultRestPort + (3 * numActiveNodes)
}
return p2p, rpc, rest
}
type nodeConfig struct {
Name string
RPCConfig *rpcclient.ConnConfig
NetParams *chaincfg.Params
BaseDir string
ExtraArgs []string
DataDir string
LogDir string
TLSCertPath string
TLSKeyPath string
AdminMacPath string
ReadMacPath string
InvoiceMacPath string
HasSeed bool
P2PPort int
RPCPort int
RESTPort int
}
func (cfg nodeConfig) P2PAddr() string {
return net.JoinHostPort("127.0.0.1", strconv.Itoa(cfg.P2PPort))
}
func (cfg nodeConfig) RPCAddr() string {
return net.JoinHostPort("127.0.0.1", strconv.Itoa(cfg.RPCPort))
}
func (cfg nodeConfig) RESTAddr() string {
return net.JoinHostPort("127.0.0.1", strconv.Itoa(cfg.RESTPort))
}
func (cfg nodeConfig) DBPath() string {
return filepath.Join(cfg.DataDir, "graph", "simnet/channel.db")
}
// genArgs generates a slice of command line arguments from the lightning node
// config struct.
func (cfg nodeConfig) genArgs() []string {
var args []string
switch cfg.NetParams {
case &chaincfg.TestNet3Params:
args = append(args, "--bitcoin.testnet")
case &chaincfg.SimNetParams:
args = append(args, "--bitcoin.simnet")
case &chaincfg.RegressionNetParams:
args = append(args, "--bitcoin.regtest")
}
encodedCert := hex.EncodeToString(cfg.RPCConfig.Certificates)
args = append(args, "--bitcoin.active")
args = append(args, "--nobootstrap")
args = append(args, "--debuglevel=debug")
args = append(args, "--bitcoin.defaultchanconfs=1")
args = append(args, "--bitcoin.defaultremotedelay=4")
args = append(args, fmt.Sprintf("--btcd.rpchost=%v", cfg.RPCConfig.Host))
args = append(args, fmt.Sprintf("--btcd.rpcuser=%v", cfg.RPCConfig.User))
args = append(args, fmt.Sprintf("--btcd.rpcpass=%v", cfg.RPCConfig.Pass))
args = append(args, fmt.Sprintf("--btcd.rawrpccert=%v", encodedCert))
args = append(args, fmt.Sprintf("--rpclisten=%v", cfg.RPCAddr()))
args = append(args, fmt.Sprintf("--restlisten=%v", cfg.RESTAddr()))
args = append(args, fmt.Sprintf("--listen=%v", cfg.P2PAddr()))
args = append(args, fmt.Sprintf("--externalip=%v", cfg.P2PAddr()))
args = append(args, fmt.Sprintf("--logdir=%v", cfg.LogDir))
args = append(args, fmt.Sprintf("--datadir=%v", cfg.DataDir))
args = append(args, fmt.Sprintf("--tlscertpath=%v", cfg.TLSCertPath))
args = append(args, fmt.Sprintf("--tlskeypath=%v", cfg.TLSKeyPath))
args = append(args, fmt.Sprintf("--configfile=%v", cfg.DataDir))
args = append(args, fmt.Sprintf("--adminmacaroonpath=%v", cfg.AdminMacPath))
args = append(args, fmt.Sprintf("--readonlymacaroonpath=%v", cfg.ReadMacPath))
args = append(args, fmt.Sprintf("--invoicemacaroonpath=%v", cfg.InvoiceMacPath))
args = append(args, fmt.Sprintf("--externalip=%s", cfg.P2PAddr()))
args = append(args, fmt.Sprintf("--trickledelay=%v", trickleDelay))
if !cfg.HasSeed {
args = append(args, "--noseedbackup")
}
if cfg.ExtraArgs != nil {
args = append(args, cfg.ExtraArgs...)
}
return args
}
// HarnessNode represents an instance of lnd running within our test network
// harness. Each HarnessNode instance also fully embeds an RPC client in
// order to pragmatically drive the node.
type HarnessNode struct {
cfg *nodeConfig
// NodeID is a unique identifier for the node within a NetworkHarness.
NodeID int
// PubKey is the serialized compressed identity public key of the node.
// This field will only be populated once the node itself has been
// started via the start() method.
PubKey [33]byte
PubKeyStr string
cmd *exec.Cmd
pidFile string
logFile *os.File
// processExit is a channel that's closed once it's detected that the
// process this instance of HarnessNode is bound to has exited.
processExit chan struct{}
chanWatchRequests chan *chanWatchRequest
// For each outpoint, we'll track an integer which denotes the number of
// edges seen for that channel within the network. When this number
// reaches 2, then it means that both edge advertisements has propagated
// through the network.
openChans map[wire.OutPoint]int
openClients map[wire.OutPoint][]chan struct{}
closedChans map[wire.OutPoint]struct{}
closeClients map[wire.OutPoint][]chan struct{}
quit chan struct{}
wg sync.WaitGroup
lnrpc.LightningClient
lnrpc.WalletUnlockerClient
}
// Assert *HarnessNode implements the lnrpc.LightningClient interface.
var _ lnrpc.LightningClient = (*HarnessNode)(nil)
var _ lnrpc.WalletUnlockerClient = (*HarnessNode)(nil)
// newNode creates a new test lightning node instance from the passed config.
func newNode(cfg nodeConfig) (*HarnessNode, error) {
if cfg.BaseDir == "" {
var err error
cfg.BaseDir, err = ioutil.TempDir("", "lndtest-node")
if err != nil {
return nil, err
}
}
cfg.DataDir = filepath.Join(cfg.BaseDir, "data")
cfg.LogDir = filepath.Join(cfg.BaseDir, "log")
cfg.TLSCertPath = filepath.Join(cfg.DataDir, "tls.cert")
cfg.TLSKeyPath = filepath.Join(cfg.DataDir, "tls.key")
cfg.AdminMacPath = filepath.Join(cfg.DataDir, "admin.macaroon")
cfg.ReadMacPath = filepath.Join(cfg.DataDir, "readonly.macaroon")
cfg.InvoiceMacPath = filepath.Join(cfg.DataDir, "invoice.macaroon")
cfg.P2PPort, cfg.RPCPort, cfg.RESTPort = generateListeningPorts()
nodeNum := numActiveNodes
numActiveNodes++
return &HarnessNode{
cfg: &cfg,
NodeID: nodeNum,
chanWatchRequests: make(chan *chanWatchRequest),
openChans: make(map[wire.OutPoint]int),
openClients: make(map[wire.OutPoint][]chan struct{}),
closedChans: make(map[wire.OutPoint]struct{}),
closeClients: make(map[wire.OutPoint][]chan struct{}),
}, nil
}
// DBPath returns the filepath to the channeldb database file for this node.
func (hn *HarnessNode) DBPath() string {
return hn.cfg.DBPath()
}
// Name returns the name of this node set during initialization.
func (hn *HarnessNode) Name() string {
return hn.cfg.Name
}
// Start launches a new process running lnd. Additionally, the PID of the
// launched process is saved in order to possibly kill the process forcibly
// later.
//
// This may not clean up properly if an error is returned, so the caller should
// call shutdown() regardless of the return value.
func (hn *HarnessNode) start(lndError chan<- error) error {
hn.quit = make(chan struct{})
args := hn.cfg.genArgs()
args = append(args, fmt.Sprintf("--profile=%d", 9000+hn.NodeID))
hn.cmd = exec.Command("./lnd-debug", args...)
// Redirect stderr output to buffer
var errb bytes.Buffer
hn.cmd.Stderr = &errb
// Make sure the log file cleanup function is initialized, even
// if no log file is created.
var finalizeLogfile = func() {
if hn.logFile != nil {
hn.logFile.Close()
}
}
// If the logoutput flag is passed, redirect output from the nodes to
// log files.
if *logOutput {
fileName := fmt.Sprintf("output-%d-%s-%s.log", hn.NodeID,
hn.cfg.Name, hex.EncodeToString(hn.PubKey[:logPubKeyBytes]))
// If the node's PubKey is not yet initialized, create a temporary
// file name. Later, after the PubKey has been initialized, the
// file can be moved to its final name with the PubKey included.
if bytes.Equal(hn.PubKey[:4], []byte{0, 0, 0, 0}) {
fileName = fmt.Sprintf("output-%d-%s-tmp__.log", hn.NodeID,
hn.cfg.Name)
// Once the node has done its work, the log file can be renamed. | if hn.logFile != nil {
hn.logFile.Close()
newFileName := fmt.Sprintf("output-%d-%s-%s.log",
hn.NodeID, hn.cfg.Name,
hex.EncodeToString(hn.PubKey[:logPubKeyBytes]))
err := os.Rename(fileName, newFileName)
if err != nil {
fmt.Printf("could not rename "+
"%s to %s: %v\n",
fileName, newFileName,
err)
}
}
}
}
// Create file if not exists, otherwise append.
file, err := os.OpenFile(fileName,
os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
if err != nil {
return err
}
// Pass node's stderr to both errb and the file.
w := io.MultiWriter(&errb, file)
hn.cmd.Stderr = w
// Pass the node's stdout only to the file.
hn.cmd.Stdout = file
// Let the node keep a reference to this file, such
// that we can add to it if necessary.
hn.logFile = file
}
if err := hn.cmd.Start(); err != nil {
return err
}
// Launch a new goroutine which that bubbles up any potential fatal
// process errors to the goroutine running the tests.
hn.processExit = make(chan struct{})
hn.wg.Add(1)
go func() {
defer hn.wg.Done()
err := hn.cmd.Wait()
if err != nil {
lndError <- errors.Errorf("%v\n%v\n", err, errb.String())
}
// Signal any onlookers that this process has exited.
close(hn.processExit)
// Make sure log file is closed and renamed if necessary.
finalizeLogfile()
}()
// Write process ID to a file.
if err := hn.writePidFile(); err != nil {
hn.cmd.Process.Kill()
return err
}
// Since Stop uses the LightningClient to stop the node, if we fail to get a
// connected client, we have to kill the process.
useMacaroons := !hn.cfg.HasSeed
conn, err := hn.ConnectRPC(useMacaroons)
if err != nil {
hn.cmd.Process.Kill()
return err
}
// If the node was created with a seed, we will need to perform an
// additional step to unlock the wallet. The connection returned will
// only use the TLS certs, and can only perform operations necessary to
// unlock the daemon.
if hn.cfg.HasSeed {
hn.WalletUnlockerClient = lnrpc.NewWalletUnlockerClient(conn)
return nil
}
return hn.initLightningClient(conn)
}
// Init initializes a harness node by passing the init request via rpc. After
// the request is submitted, this method will block until an
// macaroon-authenticated rpc connection can be established to the harness node.
// Once established, the new connection is used to initialize the
// LightningClient and subscribes the HarnessNode to topology changes.
func (hn *HarnessNode) Init(ctx context.Context,
initReq *lnrpc.InitWalletRequest) error {
timeout := time.Duration(time.Second * 15)
ctxt, _ := context.WithTimeout(ctx, timeout)
_, err := hn.InitWallet(ctxt, initReq)
if err != nil {
return err
}
// Wait for the wallet to finish unlocking, such that we can connect to
// it via a macaroon-authenticated rpc connection.
var conn *grpc.ClientConn
if err = WaitPredicate(func() bool {
conn, err = hn.ConnectRPC(true)
return err == nil
}, 5*time.Second); err != nil {
return err
}
return hn.initLightningClient(conn)
}
// initLightningClient constructs the grpc LightningClient from the given client
// connection and subscribes the harness node to graph topology updates.
func (hn *HarnessNode) initLightningClient(conn *grpc.ClientConn) error {
// Construct the LightningClient that will allow us to use the
// HarnessNode directly for normal rpc operations.
hn.LightningClient = lnrpc.NewLightningClient(conn)
// Set the harness node's pubkey to what the node claims in GetInfo.
err := hn.FetchNodeInfo()
if err != nil {
return err
}
// Launch the watcher that will hook into graph related topology change
// from the PoV of this node.
hn.wg.Add(1)
go hn.lightningNetworkWatcher()
return nil
}
// FetchNodeInfo queries an unlocked node to retrieve its public key. This
// method also spawns a lightning network watcher for this node, which watches
// for topology changes.
func (hn *HarnessNode) FetchNodeInfo() error {
// Obtain the lnid of this node for quick identification purposes.
ctxb := context.Background()
info, err := hn.GetInfo(ctxb, &lnrpc.GetInfoRequest{})
if err != nil {
return err
}
hn.PubKeyStr = info.IdentityPubkey
pubkey, err := hex.DecodeString(info.IdentityPubkey)
if err != nil {
return err
}
copy(hn.PubKey[:], pubkey)
return nil
}
// AddToLog adds a line of choice to the node's logfile. This is useful
// to interleave test output with output from the node.
func (hn *HarnessNode) AddToLog(line string) error {
// If this node was not set up with a log file, just return early.
if hn.logFile == nil {
return nil
}
if _, err := hn.logFile.WriteString(line); err != nil {
return err
}
return nil
}
// writePidFile writes the process ID of the running lnd process to a .pid file.
func (hn *HarnessNode) writePidFile() error {
filePath := filepath.Join(hn.cfg.BaseDir, fmt.Sprintf("%v.pid", hn.NodeID))
pid, err := os.Create(filePath)
if err != nil {
return err
}
defer pid.Close()
_, err = fmt.Fprintf(pid, "%v\n", hn.cmd.Process.Pid)
if err != nil {
return err
}
hn.pidFile = filePath
return nil
}
// ConnectRPC uses the TLS certificate and admin macaroon files written by the
// lnd node to create a gRPC client connection.
func (hn *HarnessNode) ConnectRPC(useMacs bool) (*grpc.ClientConn, error) {
// Wait until TLS certificate and admin macaroon are created before
// using them, up to 20 sec.
tlsTimeout := time.After(30 * time.Second)
for !fileExists(hn.cfg.TLSCertPath) {
select {
case <-tlsTimeout:
return nil, fmt.Errorf("timeout waiting for TLS cert " +
"file to be created after 30 seconds")
case <-time.After(100 * time.Millisecond):
}
}
opts := []grpc.DialOption{
grpc.WithBlock(),
grpc.WithTimeout(time.Second * 20),
}
tlsCreds, err := credentials.NewClientTLSFromFile(hn.cfg.TLSCertPath, "")
if err != nil {
return nil, err
}
opts = append(opts, grpc.WithTransportCredentials(tlsCreds))
if !useMacs {
return grpc.Dial(hn.cfg.RPCAddr(), opts...)
}
macTimeout := time.After(30 * time.Second)
for !fileExists(hn.cfg.AdminMacPath) {
select {
case <-macTimeout:
return nil, fmt.Errorf("timeout waiting for admin " +
"macaroon file to be created after 30 seconds")
case <-time.After(100 * time.Millisecond):
}
}
macBytes, err := ioutil.ReadFile(hn.cfg.AdminMacPath)
if err != nil {
return nil, err
}
mac := &macaroon.Macaroon{}
if err = mac.UnmarshalBinary(macBytes); err != nil {
return nil, err
}
macCred := macaroons.NewMacaroonCredential(mac)
opts = append(opts, grpc.WithPerRPCCredentials(macCred))
return grpc.Dial(hn.cfg.RPCAddr(), opts...)
}
// SetExtraArgs assigns the ExtraArgs field for the node's configuration. The
// changes will take effect on restart.
func (hn *HarnessNode) SetExtraArgs(extraArgs []string) {
hn.cfg.ExtraArgs = extraArgs
}
// cleanup cleans up all the temporary files created by the node's process.
func (hn *HarnessNode) cleanup() error {
return os.RemoveAll(hn.cfg.BaseDir)
}
// Stop attempts to stop the active lnd process.
func (hn *HarnessNode) stop() error {
// Do nothing if the process is not running.
if hn.processExit == nil {
return nil
}
// If start() failed before creating a client, we will just wait for the
// child process to die.
if hn.LightningClient != nil {
// Don't watch for error because sometimes the RPC connection gets
// closed before a response is returned.
req := lnrpc.StopRequest{}
ctx := context.Background()
hn.LightningClient.StopDaemon(ctx, &req)
}
// Wait for lnd process and other goroutines to exit.
select {
case <-hn.processExit:
case <-time.After(60 * time.Second):
return fmt.Errorf("process did not exit")
}
close(hn.quit)
hn.wg.Wait()
hn.quit = nil
hn.processExit = nil
hn.LightningClient = nil
hn.WalletUnlockerClient = nil
return nil
}
// shutdown stops the active lnd process and cleans up any temporary directories
// created along the way.
func (hn *HarnessNode) shutdown() error {
if err := hn.stop(); err != nil {
return err
}
if err := hn.cleanup(); err != nil {
return err
}
return nil
}
// closeChanWatchRequest is a request to the lightningNetworkWatcher to be
// notified once it's detected within the test Lightning Network, that a
// channel has either been added or closed.
type chanWatchRequest struct {
chanPoint wire.OutPoint
chanOpen bool
eventChan chan struct{}
}
// getChanPointFundingTxid returns the given channel point's funding txid in
// raw bytes.
func getChanPointFundingTxid(chanPoint *lnrpc.ChannelPoint) ([]byte, error) {
var txid []byte
// A channel point's funding txid can be get/set as a byte slice or a
// string. In the case it is a string, decode it.
switch chanPoint.GetFundingTxid().(type) {
case *lnrpc.ChannelPoint_FundingTxidBytes:
txid = chanPoint.GetFundingTxidBytes()
case *lnrpc.ChannelPoint_FundingTxidStr:
s := chanPoint.GetFundingTxidStr()
h, err := chainhash.NewHashFromStr(s)
if err != nil {
return nil, err
}
txid = h[:]
}
return txid, nil
}
// lightningNetworkWatcher is a goroutine which is able to dispatch
// notifications once it has been observed that a target channel has been
// closed or opened within the network. In order to dispatch these
// notifications, the GraphTopologySubscription client exposed as part of the
// gRPC interface is used.
func (hn *HarnessNode) lightningNetworkWatcher() {
defer hn.wg.Done()
graphUpdates := make(chan *lnrpc.GraphTopologyUpdate)
hn.wg.Add(1)
go func() {
defer hn.wg.Done()
req := &lnrpc.GraphTopologySubscription{}
ctx, cancelFunc := context.WithCancel(context.Background())
topologyClient, err := hn.SubscribeChannelGraph(ctx, req)
if err != nil {
// We panic here in case of an error as failure to
// create the topology client will cause all subsequent
// tests to fail.
panic(fmt.Errorf("unable to create topology "+
"client: %v", err))
}
defer cancelFunc()
for {
update, err := topologyClient.Recv()
if err == io.EOF {
return
} else if err != nil {
return
}
select {
case graphUpdates <- update:
case <-hn.quit:
return
}
}
}()
for {
select {
// A new graph update has just been received, so we'll examine
// the current set of registered clients to see if we can
// dispatch any requests.
case graphUpdate := <-graphUpdates:
// For each new channel, we'll increment the number of
// edges seen by one.
for _, newChan := range graphUpdate.ChannelUpdates {
txidHash, _ := getChanPointFundingTxid(newChan.ChanPoint)
txid, _ := chainhash.NewHash(txidHash)
op := wire.OutPoint{
Hash: *txid,
Index: newChan.ChanPoint.OutputIndex,
}
hn.openChans[op]++
// For this new channel, if the number of edges
// seen is less than two, then the channel
// hasn't been fully announced yet.
if numEdges := hn.openChans[op]; numEdges < 2 {
continue
}
// Otherwise, we'll notify all the registered
// clients and remove the dispatched clients.
for _, eventChan := range hn.openClients[op] {
close(eventChan)
}
delete(hn.openClients, op)
}
// For each channel closed, we'll mark that we've
// detected a channel closure while lnd was pruning the
// channel graph.
for _, closedChan := range graphUpdate.ClosedChans {
txidHash, _ := getChanPointFundingTxid(closedChan.ChanPoint)
txid, _ := chainhash.NewHash(txidHash)
op := wire.OutPoint{
Hash: *txid,
Index: closedChan.ChanPoint.OutputIndex,
}
hn.closedChans[op] = struct{}{}
// As the channel has been closed, we'll notify
// all register clients.
for _, eventChan := range hn.closeClients[op] {
close(eventChan)
}
delete(hn.closeClients, op)
}
// A new watch request, has just arrived. We'll either be able
// to dispatch immediately, or need to add the client for
// processing later.
case watchRequest := <-hn.chanWatchRequests:
targetChan := watchRequest.chanPoint
// TODO(roasbeef): add update type also, checks for
// multiple of 2
if watchRequest.chanOpen {
// If this is an open request, then it can be
// dispatched if the number of edges seen for
// the channel is at least two.
if numEdges := hn.openChans[targetChan]; numEdges >= 2 {
close(watchRequest.eventChan)
continue
}
// Otherwise, we'll add this to the list of
// watch open clients for this out point.
hn.openClients[targetChan] = append(
hn.openClients[targetChan],
watchRequest.eventChan,
)
continue
}
// If this is a close request, then it can be
// immediately dispatched if we've already seen a
// channel closure for this channel.
if _, ok := hn.closedChans[targetChan]; ok {
close(watchRequest.eventChan)
continue
}
// Otherwise, we'll add this to the list of close watch
// clients for this out point.
hn.closeClients[targetChan] = append(
hn.closeClients[targetChan],
watchRequest.eventChan,
)
case <-hn.quit:
return
}
}
}
// WaitForNetworkChannelOpen will block until a channel with the target
// outpoint is seen as being fully advertised within the network. A channel is
// considered "fully advertised" once both of its directional edges has been
// advertised within the test Lightning Network.
func (hn *HarnessNode) WaitForNetworkChannelOpen(ctx context.Context,
op *lnrpc.ChannelPoint) error {
eventChan := make(chan struct{})
txidHash, err := getChanPointFundingTxid(op)
if err != nil {
return err
}
txid, err := chainhash.NewHash(txidHash)
if err != nil {
return err
}
hn.chanWatchRequests <- &chanWatchRequest{
chanPoint: wire.OutPoint{
Hash: *txid,
Index: op.OutputIndex,
},
eventChan: eventChan,
chanOpen: true,
}
select {
case <-eventChan:
return nil
case <-ctx.Done():
return fmt.Errorf("channel not opened before timeout")
}
}
// WaitForNetworkChannelClose will block until a channel with the target
// outpoint is seen as closed within the network. A channel is considered
// closed once a transaction spending the funding outpoint is seen within a
// confirmed block.
func (hn *HarnessNode) WaitForNetworkChannelClose(ctx context.Context,
op *lnrpc.ChannelPoint) error {
eventChan := make(chan struct{})
txidHash, err := getChanPointFundingTxid(op)
if err != nil {
return err
}
txid, err := chainhash.NewHash(txidHash)
if err != nil {
return err
}
hn.chanWatchRequests <- &chanWatchRequest{
chanPoint: wire.OutPoint{
Hash: *txid,
Index: op.OutputIndex,
},
eventChan: eventChan,
chanOpen: false,
}
select {
case <-eventChan:
return nil
case <-ctx.Done():
return fmt.Errorf("channel not closed before timeout")
}
}
// WaitForBlockchainSync will block until the target nodes has fully
// synchronized with the blockchain. If the passed context object has a set
// timeout, then the goroutine will continually poll until the timeout has
// elapsed. In the case that the chain isn't synced before the timeout is up,
// then this function will return an error.
func (hn *HarnessNode) WaitForBlockchainSync(ctx context.Context) error {
errChan := make(chan error, 1)
retryDelay := time.Millisecond * 100
go func() {
for {
select {
case <-ctx.Done():
case <-hn.quit:
return
default:
}
getInfoReq := &lnrpc.GetInfoRequest{}
getInfoResp, err := hn.GetInfo(ctx, getInfoReq)
if err != nil {
errChan <- err
return
}
if getInfoResp.SyncedToChain {
errChan <- nil
return
}
select {
case <-ctx.Done():
return
case <-time.After(retryDelay):
}
}
}()
select {
case <-hn.quit:
return nil
case err := <-errChan:
return err
case <-ctx.Done():
return fmt.Errorf("Timeout while waiting for blockchain sync")
}
}
// WaitForBalance waits until the node sees the expected confirmed/unconfirmed
// balance within their wallet.
func (hn *HarnessNode) WaitForBalance(expectedBalance int64, confirmed bool) error {
ctx := context.Background()
req := &lnrpc.WalletBalanceRequest{}
var lastBalance btcutil.Amount
doesBalanceMatch := func() bool {
balance, err := hn.WalletBalance(ctx, req)
if err != nil {
return false
}
if confirmed {
lastBalance = btcutil.Amount(balance.ConfirmedBalance)
return balance.ConfirmedBalance == expectedBalance
}
lastBalance = btcutil.Amount(balance.UnconfirmedBalance)
return balance.UnconfirmedBalance == expectedBalance
}
err := WaitPredicate(doesBalanceMatch, 30*time.Second)
if err != nil {
return fmt.Errorf("balances not synced after deadline: "+
"expected %v, only have %v", expectedBalance, lastBalance)
}
return nil
}
// fileExists reports whether the named file or directory exists.
// This function is taken from https://github.com/btcsuite/btcd
func fileExists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
} | finalizeLogfile = func() { |
server.js | "use strict";
const Hapi = require('hapi');
const Wreck = require('wreck');
const server = new Hapi.Server({
port: 3000
}); |
server.route({
method: 'GET',
path: '/',
handler
});
server
.start()
.then(() => {
console.log(`Server running at: ${server.info.uri}`);
}) // if needed
.catch(err => {
console.log(err);
}); |
const handler = (request, h) => {
return "Order API";
}; |
bipdersig-p2p.py | #!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test BIP66 (DER SIG).
Test that the DERSIG soft-fork activates at (regtest) height 1251.
"""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.mininode import *
from test_framework.blocktools import create_coinbase, create_block
from test_framework.script import CScript
from io import BytesIO
DERSIG_HEIGHT = 1251
# Reject codes that we might receive in this test
REJECT_INVALID = 16
REJECT_OBSOLETE = 17
REJECT_NONSTANDARD = 64
# A canonical signature consists of:
# <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
def unDERify(tx):
"""
Make the signature in vin 0 of a tx non-DER-compliant,
by adding padding after the S-value.
"""
scriptSig = CScript(tx.vin[0].scriptSig)
newscript = []
for i in scriptSig:
if (len(newscript) == 0):
newscript.append(i[0:-1] + b'\0' + i[-1:])
else:
newscript.append(i)
tx.vin[0].scriptSig = CScript(newscript)
def create_transaction(node, coinbase, to_address, amount):
from_txid = node.getblock(coinbase)['tx'][0]
inputs = [{ "txid" : from_txid, "vout" : 0}]
outputs = { to_address : amount }
rawtx = node.createrawtransaction(inputs, outputs)
signresult = node.signrawtransaction(rawtx)
tx = CTransaction()
tx.deserialize(BytesIO(hex_str_to_bytes(signresult['hex'])))
return tx
class BIP66Test(BitcoinTestFramework):
def | (self):
self.num_nodes = 1
self.extra_args = [['-whitelist=127.0.0.1', '-dip3params=9000:9000']]
self.setup_clean_chain = True
def run_test(self):
self.nodes[0].add_p2p_connection(P2PInterface())
network_thread_start()
# wait_for_verack ensures that the P2P connection is fully up.
self.nodes[0].p2p.wait_for_verack()
self.log.info("Mining %d blocks", DERSIG_HEIGHT - 2)
self.coinbase_blocks = self.nodes[0].generate(DERSIG_HEIGHT - 2)
self.nodeaddress = self.nodes[0].getnewaddress()
self.log.info("Test that a transaction with non-DER signature can still appear in a block")
spendtx = create_transaction(self.nodes[0], self.coinbase_blocks[0],
self.nodeaddress, 1.0)
unDERify(spendtx)
spendtx.rehash()
tip = self.nodes[0].getbestblockhash()
block_time = self.nodes[0].getblockheader(tip)['mediantime'] + 1
block = create_block(int(tip, 16), create_coinbase(DERSIG_HEIGHT - 1), block_time)
block.nVersion = 2
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.nodes[0].p2p.send_and_ping(msg_block(block))
assert_equal(self.nodes[0].getbestblockhash(), block.hash)
self.log.info("Test that blocks must now be at least version 3")
tip = block.sha256
block_time += 1
block = create_block(tip, create_coinbase(DERSIG_HEIGHT), block_time)
block.nVersion = 2
block.rehash()
block.solve()
self.nodes[0].p2p.send_and_ping(msg_block(block))
assert_equal(int(self.nodes[0].getbestblockhash(), 16), tip)
wait_until(lambda: "reject" in self.nodes[0].p2p.last_message.keys(), lock=mininode_lock)
with mininode_lock:
assert_equal(self.nodes[0].p2p.last_message["reject"].code, REJECT_OBSOLETE)
assert_equal(self.nodes[0].p2p.last_message["reject"].reason, b'bad-version(0x00000002)')
assert_equal(self.nodes[0].p2p.last_message["reject"].data, block.sha256)
del self.nodes[0].p2p.last_message["reject"]
self.log.info("Test that transactions with non-DER signatures cannot appear in a block")
block.nVersion = 3
spendtx = create_transaction(self.nodes[0], self.coinbase_blocks[1],
self.nodeaddress, 1.0)
unDERify(spendtx)
spendtx.rehash()
# First we show that this tx is valid except for DERSIG by getting it
# rejected from the mempool for exactly that reason.
assert_raises_rpc_error(-26, '64: non-mandatory-script-verify-flag (Non-canonical DER signature)', self.nodes[0].sendrawtransaction, bytes_to_hex_str(spendtx.serialize()), True)
# Now we verify that a block with this transaction is also invalid.
block.vtx.append(spendtx)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.nodes[0].p2p.send_and_ping(msg_block(block))
assert_equal(int(self.nodes[0].getbestblockhash(), 16), tip)
wait_until(lambda: "reject" in self.nodes[0].p2p.last_message.keys(), lock=mininode_lock)
with mininode_lock:
# We can receive different reject messages depending on whether
# dashd is running with multiple script check threads. If script
# check threads are not in use, then transaction script validation
# happens sequentially, and dashd produces more specific reject
# reasons.
assert self.nodes[0].p2p.last_message["reject"].code in [REJECT_INVALID, REJECT_NONSTANDARD]
assert_equal(self.nodes[0].p2p.last_message["reject"].data, block.sha256)
if self.nodes[0].p2p.last_message["reject"].code == REJECT_INVALID:
# Generic rejection when a block is invalid
assert_equal(self.nodes[0].p2p.last_message["reject"].reason, b'block-validation-failed')
else:
assert b'Non-canonical DER signature' in self.nodes[0].p2p.last_message["reject"].reason
self.log.info("Test that a version 3 block with a DERSIG-compliant transaction is accepted")
block.vtx[1] = create_transaction(self.nodes[0],
self.coinbase_blocks[1], self.nodeaddress, 1.0)
block.hashMerkleRoot = block.calc_merkle_root()
block.rehash()
block.solve()
self.nodes[0].p2p.send_and_ping(msg_block(block))
assert_equal(int(self.nodes[0].getbestblockhash(), 16), block.sha256)
if __name__ == '__main__':
BIP66Test().main()
| set_test_params |
mysql_test.go | package main
import (
"flag"
"os"
"testing"
"github.com/newrelic/infra-integrations-sdk/data/inventory"
"github.com/newrelic/infra-integrations-sdk/data/metric"
"github.com/newrelic/infra-integrations-sdk/integration"
"github.com/stretchr/testify/assert"
)
func TestAsValue(t *testing.T) {
intValue, ok := asValue("10").(int)
if ok != true {
t.Error()
}
if intValue != 10 {
t.Error()
}
floatValue, ok := asValue("0.12").(float64)
if ok != true {
t.Error()
}
if floatValue != 0.12 {
t.Error()
}
boolValue, ok := asValue("true").(bool)
if ok != true {
t.Error()
}
if boolValue != true {
t.Error()
}
stringValue, ok := asValue("test string").(string)
if ok != true {
t.Error()
}
if stringValue != "test string" {
t.Error()
}
}
func TestPopulatePartialMetrics(t *testing.T) {
var rawMetrics = map[string]interface{}{
"raw_metric_1": 1,
"raw_metric_2": 2,
"raw_metric_3": "foo",
}
functionSource := func(a map[string]interface{}) (float64, bool) {
return float64(a["raw_metric_1"].(int) + a["raw_metric_2"].(int)), true
}
var metricDefinition = map[string][]interface{}{
"rawMetric1": {"raw_metric_1", metric.GAUGE},
"rawMetric2": {"raw_metric_2", metric.GAUGE},
"rawMetric3": {"raw_metric_3", metric.ATTRIBUTE},
"unknownMetric": {"raw_metric_4", metric.GAUGE},
"badRawSource": {10, metric.GAUGE},
"functionSource": {functionSource, metric.GAUGE},
}
var ms = metric.NewSet("eventType", nil)
populatePartialMetrics(ms, rawMetrics, metricDefinition)
assert.Equal(t, 1., ms.Metrics["rawMetric1"])
assert.Equal(t, 2., ms.Metrics["rawMetric2"])
assert.Equal(t, "foo", ms.Metrics["rawMetric3"])
assert.Nil(t, ms.Metrics["unknownMetric"])
assert.Nil(t, ms.Metrics["badRawSource"])
assert.Equal(t, 3., ms.Metrics["functionSource"])
}
func TestPopulateInventory(t *testing.T) {
var rawInventory = map[string]interface{}{
"key_1": 1,
"key_2": 2,
"key_3": "foo",
}
i := inventory.New()
populateInventory(i, rawInventory)
for key, value := range rawInventory {
v, exists := i.Item(key)
assert.True(t, exists)
assert.Equal(t, value, v["value"])
}
}
type testdb struct {
inventory map[string]interface{}
metrics map[string]interface{}
replica map[string]interface{}
}
func (d testdb) close() {}
func (d testdb) query(query string) (map[string]interface{}, error) {
if query == inventoryQuery {
return d.inventory, nil
}
if query == metricsQuery {
return d.metrics, nil
}
if query == replicaQuery {
return d.replica, nil
}
return nil, nil
}
func TestGetRawData(t *testing.T) {
database := testdb{
inventory: map[string]interface{}{
"key_cache_block_size": 10,
"key_buffer_size": 10,
"version_comment": "mysql",
"version": "5.4.3",
},
metrics: map[string]interface{}{},
replica: map[string]interface{}{},
}
inventory, metrics, err := getRawData(database)
if err != nil {
t.Error()
}
if metrics == nil {
t.Error()
}
if inventory == nil {
t.Error()
}
}
func TestPopulateMetricsWithZeroValuesInData(t *testing.T) {
rawMetrics := map[string]interface{}{
"Qcache_free_blocks": 0,
"Qcache_total_blocks": 0,
"Qcache_not_cached": 0,
"Qcache_hits": 0,
"Queries": 0,
"Threads_created": 0,
"Connections": 0,
"Key_blocks_unused": 0,
"Key_cache_block_size": 0,
"Key_buffer_size": 0,
}
ms := metric.NewSet("eventType", nil)
populatePartialMetrics(ms, rawMetrics, defaultMetrics)
populatePartialMetrics(ms, rawMetrics, extendedMetrics)
populatePartialMetrics(ms, rawMetrics, myisamMetrics)
testMetrics := []string{"db.qCacheUtilization", "db.qCacheHitRatio", "db.threadCacheMissRate", "db.myisam.keyCacheUtilization"}
expected := float64(0)
for _, metricName := range testMetrics {
actual := ms.Metrics[metricName]
if actual != expected {
t.Errorf("For metric '%s', expected value: %f. Actual value: %f", metricName, expected, actual)
}
}
}
func | (t *testing.T) {
os.Setenv("USERNAME", "dbuser")
os.Setenv("HOSTNAME", "foo")
os.Args = []string{
"cmd",
"-hostname=bar",
"-port=1234",
"-password=dbpwd",
}
_, err := integration.New(integrationName, integrationVersion, integration.Args(&args))
fatalIfErr(err)
assert.Equal(t, "dbuser:dbpwd@tcp(bar:1234)/?", generateDSN(args))
flag.CommandLine = flag.NewFlagSet("cmd", flag.ContinueOnError)
}
func TestGenerateDSNSupportsOldPasswords(t *testing.T) {
os.Args = []string{
"cmd",
"-hostname=dbhost",
"-username=dbuser",
"-password=dbpwd",
"-port=1234",
"-old_passwords",
}
_, err := integration.New(integrationName, integrationVersion, integration.Args(&args))
fatalIfErr(err)
assert.Equal(t, "dbuser:dbpwd@tcp(dbhost:1234)/?allowOldPasswords=true", generateDSN(args))
flag.CommandLine = flag.NewFlagSet("cmd", flag.ContinueOnError)
}
func TestGenerateDSNSupportsEnableTLS(t *testing.T) {
os.Args = []string{
"cmd",
"-hostname=dbhost",
"-username=dbuser",
"-password=dbpwd",
"-port=1234",
"-enable_tls",
}
_, err := integration.New(integrationName, integrationVersion, integration.Args(&args))
fatalIfErr(err)
assert.Equal(t, "dbuser:dbpwd@tcp(dbhost:1234)/?tls=true", generateDSN(args))
flag.CommandLine = flag.NewFlagSet("cmd", flag.ContinueOnError)
}
func TestGenerateDSNSupportsInsecureSkipVerify(t *testing.T) {
os.Args = []string{
"cmd",
"-hostname=dbhost",
"-username=dbuser",
"-password=dbpwd",
"-port=1234",
"-insecure_skip_verify",
}
_, err := integration.New(integrationName, integrationVersion, integration.Args(&args))
fatalIfErr(err)
assert.Equal(t, "dbuser:dbpwd@tcp(dbhost:1234)/?tls=skip-verify", generateDSN(args))
flag.CommandLine = flag.NewFlagSet("cmd", flag.ContinueOnError)
}
func TestGenerateDSNSupportsExtraConnectionURLArgs(t *testing.T) {
os.Args = []string{
"cmd",
"-hostname=dbhost",
"-username=dbuser",
"-password=dbpwd",
"-port=1234",
"-extra_connection_url_args=readTimeout=1s&timeout=5s&tls=skip-verify",
}
_, err := integration.New(integrationName, integrationVersion, integration.Args(&args))
fatalIfErr(err)
assert.Equal(t, "dbuser:dbpwd@tcp(dbhost:1234)/?readTimeout=1s&timeout=5s&tls=skip-verify", generateDSN(args))
flag.CommandLine = flag.NewFlagSet("cmd", flag.ContinueOnError)
}
func TestGenerateDSNSocketDiscardPort(t *testing.T) {
os.Args = []string{
"cmd",
"-hostname=dbhost",
"-username=dbuser",
"-password=dbpwd",
"-port=1234",
"-socket=/path/to/socket/file",
}
_, err := integration.New(integrationName, integrationVersion, integration.Args(&args))
fatalIfErr(err)
assert.Equal(t, "dbuser:dbpwd@unix(/path/to/socket/file)/?", generateDSN(args))
flag.CommandLine = flag.NewFlagSet("cmd", flag.ContinueOnError)
}
| TestGenerateDSNPriorizesCliOverEnvArgs |
count-mount-handler.tsx | import * as React from 'react'
interface ContentMountHandlerProps {
children: React.ReactNode
onLoad?: () => void
}
| }: ContentMountHandlerProps): JSX.Element {
React.useEffect(
function effect(): void {
if (onLoad) {
onLoad()
}
},
[onLoad]
)
return <>{children}</>
}
export default React.memo(ContentMountHandler) | function ContentMountHandler({
children,
onLoad, |
test_db.py | import os
import time
from copy import deepcopy
from shutil import copyfile
from unittest.mock import patch
import pytest
from pysqlcipher3 import dbapi2 as sqlcipher
from rotkehlchen.assets.asset import Asset, EthereumToken
from rotkehlchen.constants import YEAR_IN_SECONDS
from rotkehlchen.constants.assets import A_BTC, A_CNY, A_ETH, A_EUR, A_USD, FIAT_CURRENCIES
from rotkehlchen.constants.misc import ZERO
from rotkehlchen.data_handler import DataHandler
from rotkehlchen.db.dbhandler import DBINFO_FILENAME, DBHandler, detect_sqlcipher_version
from rotkehlchen.db.settings import (
DEFAULT_ANONYMIZED_LOGS,
DEFAULT_BALANCE_SAVE_FREQUENCY,
DEFAULT_DATE_DISPLAY_FORMAT,
DEFAULT_INCLUDE_CRYPTO2CRYPTO,
DEFAULT_INCLUDE_GAS_COSTS,
DEFAULT_MAIN_CURRENCY,
DEFAULT_START_DATE,
DEFAULT_UI_FLOATING_PRECISION,
ROTKEHLCHEN_DB_VERSION,
DBSettings,
ModifiableDBSettings,
)
from rotkehlchen.db.utils import AssetBalance, BlockchainAccounts, LocationData
from rotkehlchen.errors import AuthenticationError, InputError
from rotkehlchen.exchanges.data_structures import AssetMovement, MarginPosition, Trade
from rotkehlchen.fval import FVal
from rotkehlchen.premium.premium import PremiumCredentials
from rotkehlchen.tests.utils.constants import (
A_DAO,
A_DOGE,
A_GNO,
A_RDN,
A_XMR,
DEFAULT_TESTS_MAIN_CURRENCY,
ETH_ADDRESS1,
ETH_ADDRESS2,
ETH_ADDRESS3,
MOCK_INPUT_DATA,
)
from rotkehlchen.tests.utils.rotkehlchen import add_starting_balances
from rotkehlchen.typing import (
ApiKey,
ApiSecret,
AssetAmount,
AssetMovementCategory,
BlockchainAccountData,
EthereumTransaction,
ExternalService,
ExternalServiceApiCredentials,
Fee,
Location,
SupportedBlockchain,
Timestamp,
TradeType,
)
from rotkehlchen.user_messages import MessagesAggregator
from rotkehlchen.utils.misc import ts_now
from rotkehlchen.utils.serialization import rlk_jsondumps
TABLES_AT_INIT = [
'timed_balances',
'timed_location_data',
'asset_movement_category',
'external_service_credentials',
'user_credentials',
'blockchain_accounts',
'multisettings',
'current_balances',
'trades',
'ethereum_transactions',
'manually_tracked_balances',
'trade_type',
'location',
'settings',
'used_query_ranges',
'margin_positions',
'asset_movements',
'tag_mappings',
'tags',
]
def test_data_init_and_password(data_dir, username):
"""DB Creation logic and tables at start testing"""
msg_aggregator = MessagesAggregator()
# Creating a new data dir should work
data = DataHandler(data_dir, msg_aggregator)
data.unlock(username, '123', create_new=True)
assert os.path.exists(os.path.join(data_dir, username))
# Trying to re-create it should throw
with pytest.raises(AuthenticationError):
data.unlock(username, '123', create_new=True)
# Trying to unlock a non-existing user without create_new should throw
with pytest.raises(AuthenticationError):
data.unlock('otheruser', '123', create_new=False)
# now relogin and check all tables are there
del data
data = DataHandler(data_dir, msg_aggregator)
data.unlock(username, '123', create_new=False)
cursor = data.db.conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
results = cursor.fetchall()
results = [result[0] for result in results]
assert set(results) == set(TABLES_AT_INIT)
# finally logging in with wrong password should also fail
del data
data = DataHandler(data_dir, msg_aggregator)
with pytest.raises(AuthenticationError):
data.unlock(username, '1234', create_new=False)
def test_add_remove_exchange(data_dir, username):
"""Tests that adding and removing an exchange in the DB works.
Also unknown exchanges should fail
"""
msg_aggregator = MessagesAggregator()
username = 'foo'
userdata_dir = os.path.join(data_dir, username)
os.mkdir(userdata_dir)
db = DBHandler(userdata_dir, '123', msg_aggregator)
# Test that an unknown exchange fails
with pytest.raises(InputError):
db.add_exchange('non_existing_exchange', 'api_key', 'api_secret')
credentials = db.get_exchange_credentials()
assert len(credentials) == 0
kraken_api_key = ApiKey('kraken_api_key')
kraken_api_secret = ApiSecret(b'kraken_api_secret')
binance_api_key = ApiKey('binance_api_key')
binance_api_secret = ApiSecret(b'binance_api_secret')
# add mock kraken and binance
db.add_exchange('kraken', kraken_api_key, kraken_api_secret)
db.add_exchange('binance', binance_api_key, binance_api_secret)
# and check the credentials can be retrieved
credentials = db.get_exchange_credentials()
assert len(credentials) == 2
assert credentials['kraken'].api_key == kraken_api_key
assert credentials['kraken'].api_secret == kraken_api_secret
assert credentials['binance'].api_key == binance_api_key
assert credentials['binance'].api_secret == binance_api_secret
# remove an exchange and see it works
db.remove_exchange('kraken')
credentials = db.get_exchange_credentials()
assert len(credentials) == 1
def test_export_import_db(data_dir, username):
"""Create a DB, write some data and then after export/import confirm it's there"""
msg_aggregator = MessagesAggregator()
data = DataHandler(data_dir, msg_aggregator)
data.unlock(username, '123', create_new=True)
data.set_fiat_balances({A_EUR: AssetAmount(FVal('10'))})
encoded_data, _ = data.compress_and_encrypt_db('123')
# The server would return them decoded
encoded_data = encoded_data.decode() # pylint: disable=no-member
data.decompress_and_decrypt_db('123', encoded_data)
fiat_balances = data.get_fiat_balances()
assert len(fiat_balances) == 1
assert int(fiat_balances[A_EUR]) == 10
def test_writting_fetching_data(data_dir, username):
msg_aggregator = MessagesAggregator()
data = DataHandler(data_dir, msg_aggregator)
data.unlock(username, '123', create_new=True)
tokens = [A_GNO, A_RDN]
data.write_owned_eth_tokens(tokens)
result = data.db.get_owned_tokens()
assert set(tokens) == set(result)
data.db.add_blockchain_accounts(
SupportedBlockchain.BITCOIN,
[BlockchainAccountData(address='1CB7Pbji3tquDtMRp8mBkerimkFzWRkovS')],
)
data.db.add_blockchain_accounts(
SupportedBlockchain.ETHEREUM,
[
BlockchainAccountData(address='0xd36029d76af6fE4A356528e4Dc66B2C18123597D'),
BlockchainAccountData(address='0x80B369799104a47e98A553f3329812a44A7FaCDc'),
],
)
accounts = data.db.get_blockchain_accounts()
assert isinstance(accounts, BlockchainAccounts)
assert accounts.btc == ['1CB7Pbji3tquDtMRp8mBkerimkFzWRkovS']
# See that after addition the address has been checksummed
assert set(accounts.eth) == {
'0xd36029d76af6fE4A356528e4Dc66B2C18123597D',
'0x80B369799104a47e98A553f3329812a44A7FaCDc',
}
# Add existing account should fail
with pytest.raises(sqlcipher.IntegrityError): # pylint: disable=no-member
data.db.add_blockchain_accounts(
SupportedBlockchain.ETHEREUM,
[BlockchainAccountData(address='0xd36029d76af6fE4A356528e4Dc66B2C18123597D')],
)
# Remove non-existing account
with pytest.raises(InputError):
data.db.remove_blockchain_accounts(
SupportedBlockchain.ETHEREUM,
['0x136029d76af6fE4A356528e4Dc66B2C18123597D'],
)
# Remove existing account
data.db.remove_blockchain_accounts(
SupportedBlockchain.ETHEREUM,
['0xd36029d76af6fE4A356528e4Dc66B2C18123597D'],
)
accounts = data.db.get_blockchain_accounts()
assert accounts.eth == ['0x80B369799104a47e98A553f3329812a44A7FaCDc']
result, _ = data.add_ignored_assets([A_DAO])
assert result
result, _ = data.add_ignored_assets([A_DOGE])
assert result
result, _ = data.add_ignored_assets([A_DOGE])
assert not result
ignored_assets = data.db.get_ignored_assets()
assert all(isinstance(asset, Asset) for asset in ignored_assets)
assert set(ignored_assets) == {A_DAO, A_DOGE}
# Test removing asset that is not in the list
result, msg = data.remove_ignored_assets([A_RDN])
assert 'not in ignored assets' in msg
assert not result
result, _ = data.remove_ignored_assets([A_DOGE])
assert result
assert data.db.get_ignored_assets() == [A_DAO]
# With nothing inserted in settings make sure default values are returned
result = data.db.get_settings()
last_write_diff = ts_now() - result.last_write_ts
# make sure last_write was within 3 secs
assert last_write_diff >= 0 and last_write_diff < 3
expected_dict = {
'have_premium': False,
'historical_data_start': DEFAULT_START_DATE,
'eth_rpc_endpoint': 'http://localhost:8545',
'ui_floating_precision': DEFAULT_UI_FLOATING_PRECISION,
'version': ROTKEHLCHEN_DB_VERSION,
'include_crypto2crypto': DEFAULT_INCLUDE_CRYPTO2CRYPTO,
'include_gas_costs': DEFAULT_INCLUDE_GAS_COSTS,
'taxfree_after_period': YEAR_IN_SECONDS,
'balance_save_frequency': DEFAULT_BALANCE_SAVE_FREQUENCY,
'last_balance_save': 0,
'main_currency': DEFAULT_MAIN_CURRENCY.identifier,
'anonymized_logs': DEFAULT_ANONYMIZED_LOGS,
'date_display_format': DEFAULT_DATE_DISPLAY_FORMAT,
'last_data_upload_ts': 0,
'premium_should_sync': False,
'submit_usage_analytics': True,
'last_write_ts': 0,
}
assert len(expected_dict) == len(DBSettings()), 'One or more settings are missing'
# Make sure that results are the same. Comparing like this since we ignore last
# write ts check
result_dict = result._asdict()
for key, value in expected_dict.items():
assert key in result_dict
if key != 'last_write_ts':
assert value == result_dict[key]
def test_settings_entry_types(database):
database.set_settings(ModifiableDBSettings(
premium_should_sync=True,
include_crypto2crypto=True,
anonymized_logs=True,
ui_floating_precision=1,
taxfree_after_period=1,
include_gas_costs=True,
historical_data_start='01/08/2015',
eth_rpc_endpoint='http://localhost:8545',
balance_save_frequency=24,
date_display_format='%d/%m/%Y %H:%M:%S %z',
submit_usage_analytics=False,
))
res = database.get_settings()
assert isinstance(res.version, int)
assert res.version == ROTKEHLCHEN_DB_VERSION
assert isinstance(res.last_write_ts, int)
assert isinstance(res.premium_should_sync, bool)
# assert res.premium_should_sync is DEFAULT_PREMIUM_SHOULD_SYNC
assert res.premium_should_sync is True
assert isinstance(res.include_crypto2crypto, bool)
assert res.include_crypto2crypto is True
assert isinstance(res.ui_floating_precision, int)
assert res.ui_floating_precision == 1
assert isinstance(res.taxfree_after_period, int)
assert res.taxfree_after_period == 1
assert isinstance(res.historical_data_start, str)
assert res.historical_data_start == '01/08/2015'
assert isinstance(res.eth_rpc_endpoint, str)
assert res.eth_rpc_endpoint == 'http://localhost:8545'
assert isinstance(res.balance_save_frequency, int)
assert res.balance_save_frequency == 24
assert isinstance(res.last_balance_save, int)
assert res.last_balance_save == 0
assert isinstance(res.main_currency, Asset)
assert res.main_currency == DEFAULT_TESTS_MAIN_CURRENCY
assert isinstance(res.anonymized_logs, bool)
assert res.anonymized_logs is True
assert isinstance(res.date_display_format, str)
assert res.date_display_format == '%d/%m/%Y %H:%M:%S %z'
assert isinstance(res.submit_usage_analytics, bool)
assert res.submit_usage_analytics is False
def | (data_dir, username):
msg_aggregator = MessagesAggregator()
data = DataHandler(data_dir, msg_aggregator)
data.unlock(username, '123', create_new=True)
now = int(time.time())
data_save_ts = now - 24 * 60 * 60 + 20
data.db.add_multiple_location_data([LocationData(
time=data_save_ts, location=Location.KRAKEN.serialize_for_db(), usd_value='1500',
)])
assert not data.should_save_balances()
data.db.set_settings(ModifiableDBSettings(balance_save_frequency=5))
assert data.should_save_balances()
last_save_ts = data.db.get_last_balance_save_time()
assert last_save_ts == data_save_ts
def test_upgrade_sqlcipher_v3_to_v4_without_dbinfo(data_dir):
"""Test that we can upgrade from an sqlcipher v3 to v4 rotkehlchen database
Issue: https://github.com/rotki/rotki/issues/229
"""
sqlcipher_version = detect_sqlcipher_version()
if sqlcipher_version != 4:
# nothing to test
return
username = 'foo'
userdata_dir = os.path.join(data_dir, username)
os.mkdir(userdata_dir)
# get the v3 database file and copy it into the user's data directory
dir_path = os.path.dirname(os.path.realpath(__file__))
copyfile(
os.path.join(os.path.dirname(dir_path), 'data', 'sqlcipher_v3_rotkehlchen.db'),
os.path.join(userdata_dir, 'rotkehlchen.db'),
)
# the constructor should migrate it in-place and we should have a working DB
msg_aggregator = MessagesAggregator()
db = DBHandler(userdata_dir, '123', msg_aggregator)
assert db.get_version() == ROTKEHLCHEN_DB_VERSION
def test_upgrade_sqlcipher_v3_to_v4_with_dbinfo(data_dir):
sqlcipher_version = detect_sqlcipher_version()
if sqlcipher_version != 4:
# nothing to test
return
username = 'foo'
userdata_dir = os.path.join(data_dir, username)
os.mkdir(userdata_dir)
# get the v3 database file and copy it into the user's data directory
dir_path = os.path.dirname(os.path.realpath(__file__))
copyfile(
os.path.join(os.path.dirname(dir_path), 'data', 'sqlcipher_v3_rotkehlchen.db'),
os.path.join(userdata_dir, 'rotkehlchen.db'),
)
dbinfo = {'sqlcipher_version': 3, 'md5_hash': '20c910c28ca42370e4a5f24d6d4a73d2'}
with open(os.path.join(userdata_dir, DBINFO_FILENAME), 'w') as f:
f.write(rlk_jsondumps(dbinfo))
# the constructor should migrate it in-place and we should have a working DB
msg_aggregator = MessagesAggregator()
db = DBHandler(userdata_dir, '123', msg_aggregator)
assert db.get_version() == ROTKEHLCHEN_DB_VERSION
def test_sqlcipher_detect_version():
class QueryMock():
def __init__(self, version):
self.version = version
def fetchall(self):
return [[self.version]]
class ConnectionMock():
def __init__(self, version):
self.version = version
def execute(self, command): # pylint: disable=unused-argument
return QueryMock(self.version)
def close(self):
pass
with patch('pysqlcipher3.dbapi2.connect') as sql_mock:
sql_mock.return_value = ConnectionMock('4.0.0 community')
assert detect_sqlcipher_version() == 4
sql_mock.return_value = ConnectionMock('4.0.1 something')
assert detect_sqlcipher_version() == 4
sql_mock.return_value = ConnectionMock('4.9.12 somethingelse')
assert detect_sqlcipher_version() == 4
sql_mock.return_value = ConnectionMock('5.10.13 somethingelse')
assert detect_sqlcipher_version() == 5
sql_mock.return_value = ConnectionMock('3.1.15 somethingelse')
assert detect_sqlcipher_version() == 3
with pytest.raises(ValueError):
sql_mock.return_value = ConnectionMock('no version')
detect_sqlcipher_version()
def test_data_set_fiat_balances(data_dir, username):
msg_aggregator = MessagesAggregator()
data = DataHandler(data_dir, msg_aggregator)
data.unlock(username, '123', create_new=True)
amount_eur = AssetAmount(FVal('100'))
amount_cny = AssetAmount(FVal('500'))
data.set_fiat_balances({A_EUR: amount_eur})
data.set_fiat_balances({A_CNY: amount_cny})
balances = data.get_fiat_balances()
assert len(balances) == 2
assert FVal(balances[A_EUR]) == amount_eur
assert FVal(balances[A_CNY]) == amount_cny
data.set_fiat_balances({A_EUR: ZERO})
balances = data.get_fiat_balances()
assert len(balances) == 1
assert FVal(balances[A_CNY]) == amount_cny
# also check that all the fiat assets in the fiat table are in
# all_assets.json
for fiat_asset in FIAT_CURRENCIES:
assert fiat_asset.is_fiat()
asset_balances = [
AssetBalance(
time=Timestamp(1451606400),
asset=A_USD,
amount='10',
usd_value='10',
), AssetBalance(
time=Timestamp(1451606401),
asset=A_ETH,
amount='2',
usd_value='1.7068',
), AssetBalance(
time=Timestamp(1465171200),
asset=A_USD,
amount='500',
usd_value='500',
), AssetBalance(
time=Timestamp(1465171201),
asset=A_ETH,
amount='10',
usd_value='123',
), AssetBalance(
time=Timestamp(1485907200),
asset=A_USD,
amount='350',
usd_value='350',
), AssetBalance(
time=Timestamp(1485907201),
asset=A_ETH,
amount='25',
usd_value='249.5',
),
]
def test_get_fiat_balances_unhappy_path(data_dir, username):
"""Test that if somehow unsupported assets end up in the DB we don't crash"""
msg_aggregator = MessagesAggregator()
data = DataHandler(data_dir, msg_aggregator)
data.unlock(username, '123', create_new=True)
cursor = data.db.conn.cursor()
cursor.execute(
'INSERT INTO current_balances(asset, amount) '
' VALUES(?, ?)',
('DSADASDSAD', '10.1'),
)
data.db.conn.commit()
balances = data.get_fiat_balances()
warnings = msg_aggregator.consume_warnings()
errors = msg_aggregator.consume_errors()
assert len(balances) == 0
assert len(warnings) == 0
assert len(errors) == 1
assert 'Unknown FIAT asset' in errors[0]
def test_query_timed_balances(data_dir, username):
msg_aggregator = MessagesAggregator()
data = DataHandler(data_dir, msg_aggregator)
data.unlock(username, '123', create_new=True)
data.db.add_multiple_balances(asset_balances)
result = data.db.query_timed_balances(
from_ts=1451606401,
to_ts=1485907100,
asset=A_USD,
)
assert len(result) == 1
assert result[0].time == 1465171200
assert result[0].amount == '500'
assert result[0].usd_value == '500'
result = data.db.query_timed_balances(
from_ts=1451606300,
to_ts=1485907000,
asset=A_ETH,
)
assert len(result) == 2
assert result[0].time == 1451606401
assert result[0].amount == '2'
assert result[0].usd_value == '1.7068'
assert result[1].time == 1465171201
assert result[1].amount == '10'
assert result[1].usd_value == '123'
def test_query_owned_assets(data_dir, username):
"""Test the get_owned_assets with also an unknown asset in the DB"""
msg_aggregator = MessagesAggregator()
data = DataHandler(data_dir, msg_aggregator)
data.unlock(username, '123', create_new=True)
balances = deepcopy(asset_balances)
balances.extend([
AssetBalance(
time=Timestamp(1488326400),
asset=A_BTC,
amount='1',
usd_value='1222.66',
),
AssetBalance(
time=Timestamp(1489326500),
asset=A_XMR,
amount='2',
usd_value='33.8',
),
])
data.db.add_multiple_balances(balances)
cursor = data.db.conn.cursor()
cursor.execute(
'INSERT INTO timed_balances('
' time, currency, amount, usd_value) '
' VALUES(?, ?, ?, ?)',
(1469326500, 'ADSADX', '10.1', '100.5'),
)
data.db.conn.commit()
assets_list = data.db.query_owned_assets()
assert assets_list == [A_USD, A_ETH, A_BTC, A_XMR]
assert all(isinstance(x, Asset) for x in assets_list)
warnings = data.db.msg_aggregator.consume_warnings()
assert len(warnings) == 1
assert 'Unknown/unsupported asset ADSADX' in warnings[0]
def test_get_latest_location_value_distribution(data_dir, username):
msg_aggregator = MessagesAggregator()
data = DataHandler(data_dir, msg_aggregator)
data.unlock(username, '123', create_new=True)
add_starting_balances(data)
distribution = data.db.get_latest_location_value_distribution()
assert len(distribution) == 5
assert all(entry.time == Timestamp(1491607800) for entry in distribution)
assert distribution[0].location == 'B' # kraken location serialized for DB enum
assert distribution[0].usd_value == '2000'
assert distribution[1].location == 'C' # poloniex location serialized for DB enum
assert distribution[1].usd_value == '100'
assert distribution[2].location == 'H' # total location serialized for DB enum
assert distribution[2].usd_value == '10700.5'
assert distribution[3].location == 'I' # banks location serialized for DB enum
assert distribution[3].usd_value == '10000'
assert distribution[4].location == 'J' # blockchain location serialized for DB enum
assert distribution[4].usd_value == '200000'
def test_get_latest_asset_value_distribution(data_dir, username):
msg_aggregator = MessagesAggregator()
data = DataHandler(data_dir, msg_aggregator)
data.unlock(username, '123', create_new=True)
balances = add_starting_balances(data)
assets = data.db.get_latest_asset_value_distribution()
assert len(assets) == 4
# Make sure they are sorted by usd value
assert assets[0] == balances[1]
assert assets[1] == balances[0]
assert FVal(assets[0].usd_value) > FVal(assets[1].usd_value)
assert assets[2] == balances[3]
assert FVal(assets[1].usd_value) > FVal(assets[2].usd_value)
assert assets[3] == balances[2]
assert FVal(assets[2].usd_value) > FVal(assets[3].usd_value)
def test_get_owned_tokens(data_dir, username):
"""Test the get_owned_tokens with also an unknown token in the DB"""
msg_aggregator = MessagesAggregator()
data = DataHandler(data_dir, msg_aggregator)
data.unlock(username, '123', create_new=True)
cursor = data.db.conn.cursor()
tokens = ['RDN', 'GNO', 'DASDSADSAD']
cursor.executemany(
'INSERT INTO multisettings(name, value) VALUES(?, ?)',
[('eth_token', t) for t in tokens],
)
data.db.conn.commit()
tokens = data.db.get_owned_tokens()
assert tokens == [EthereumToken('GNO'), EthereumToken('RDN')]
warnings = data.db.msg_aggregator.consume_warnings()
assert len(warnings) == 1
assert 'Unknown/unsupported asset DASDSADSAD' in warnings[0]
def test_get_netvalue_data(data_dir, username):
msg_aggregator = MessagesAggregator()
data = DataHandler(data_dir, msg_aggregator)
data.unlock(username, '123', create_new=True)
add_starting_balances(data)
times, values = data.db.get_netvalue_data()
assert len(times) == 3
assert times[0] == 1451606400
assert times[1] == 1461606500
assert times[2] == 1491607800
assert len(values) == 3
assert values[0] == '1500'
assert values[1] == '4500'
assert values[2] == '10700.5'
def test_add_trades(data_dir, username):
"""Test that adding and retrieving trades from the DB works fine.
Also duplicates should be ignored and an error returned
"""
msg_aggregator = MessagesAggregator()
data = DataHandler(data_dir, msg_aggregator)
data.unlock(username, '123', create_new=True)
trade1 = Trade(
timestamp=1451606400,
location=Location.KRAKEN,
pair='ETH_EUR',
trade_type=TradeType.BUY,
amount=FVal('1.1'),
rate=FVal('10'),
fee=Fee(FVal('0.01')),
fee_currency=A_EUR,
link='',
notes='',
)
trade2 = Trade(
timestamp=1451607500,
location=Location.BINANCE,
pair='BTC_ETH',
trade_type=TradeType.BUY,
amount=FVal('0.00120'),
rate=FVal('10'),
fee=Fee(FVal('0.001')),
fee_currency=A_ETH,
link='',
notes='',
)
trade3 = Trade(
timestamp=1451608600,
location=Location.COINBASE,
pair='BTC_ETH',
trade_type=TradeType.SELL,
amount=FVal('0.00120'),
rate=FVal('1'),
fee=Fee(FVal('0.001')),
fee_currency=A_ETH,
link='',
notes='',
)
# Add and retrieve the first 2 trades. All should be fine.
data.db.add_trades([trade1, trade2])
errors = msg_aggregator.consume_errors()
warnings = msg_aggregator.consume_warnings()
assert len(errors) == 0
assert len(warnings) == 0
returned_trades = data.db.get_trades()
assert returned_trades == [trade1, trade2]
# Add the last 2 trades. Since trade2 already exists in the DB it should be
# ignored and a warning should be shown
data.db.add_trades([trade2, trade3])
errors = msg_aggregator.consume_errors()
warnings = msg_aggregator.consume_warnings()
assert len(errors) == 0
assert len(warnings) == 1
returned_trades = data.db.get_trades()
assert returned_trades == [trade1, trade2, trade3]
def test_add_margin_positions(data_dir, username):
"""Test that adding and retrieving margin positions from the DB works fine.
Also duplicates should be ignored and an error returned
"""
msg_aggregator = MessagesAggregator()
data = DataHandler(data_dir, msg_aggregator)
data.unlock(username, '123', create_new=True)
margin1 = MarginPosition(
location=Location.BITMEX,
open_time=1451606400,
close_time=1451616500,
profit_loss=FVal('1.0'),
pl_currency=A_BTC,
fee=Fee(FVal('0.01')),
fee_currency=A_EUR,
link='',
notes='',
)
margin2 = MarginPosition(
location=Location.BITMEX,
open_time=1451626500,
close_time=1451636500,
profit_loss=FVal('0.5'),
pl_currency=A_BTC,
fee=Fee(FVal('0.01')),
fee_currency=A_EUR,
link='',
notes='',
)
margin3 = MarginPosition(
location=Location.POLONIEX,
open_time=1452636501,
close_time=1459836501,
profit_loss=FVal('2.5'),
pl_currency=A_BTC,
fee=Fee(FVal('0.01')),
fee_currency=A_EUR,
link='',
notes='',
)
# Add and retrieve the first 2 margins. All should be fine.
data.db.add_margin_positions([margin1, margin2])
errors = msg_aggregator.consume_errors()
warnings = msg_aggregator.consume_warnings()
assert len(errors) == 0
assert len(warnings) == 0
returned_margins = data.db.get_margin_positions()
assert returned_margins == [margin1, margin2]
# Add the last 2 margins. Since margin2 already exists in the DB it should be
# ignored and a warning should be shown
data.db.add_margin_positions([margin2, margin3])
errors = msg_aggregator.consume_errors()
warnings = msg_aggregator.consume_warnings()
assert len(errors) == 0
assert len(warnings) == 1
returned_margins = data.db.get_margin_positions()
assert returned_margins == [margin1, margin2, margin3]
def test_add_asset_movements(data_dir, username):
"""Test that adding and retrieving asset movements from the DB works fine.
Also duplicates should be ignored and an error returned
"""
msg_aggregator = MessagesAggregator()
data = DataHandler(data_dir, msg_aggregator)
data.unlock(username, '123', create_new=True)
movement1 = AssetMovement(
location=Location.BITMEX,
category=AssetMovementCategory.DEPOSIT,
timestamp=1451606400,
asset=A_BTC,
amount=FVal('1.0'),
fee_asset=A_EUR,
fee=Fee(FVal('0')),
link='',
)
movement2 = AssetMovement(
location=Location.POLONIEX,
category=AssetMovementCategory.WITHDRAWAL,
timestamp=1451608501,
asset=A_ETH,
amount=FVal('1.0'),
fee_asset=A_EUR,
fee=Fee(FVal('0.01')),
link='',
)
movement3 = AssetMovement(
location=Location.BITTREX,
category=AssetMovementCategory.WITHDRAWAL,
timestamp=1461708501,
asset=A_ETH,
amount=FVal('1.0'),
fee_asset=A_EUR,
fee=Fee(FVal('0.01')),
link='',
)
# Add and retrieve the first 2 margins. All should be fine.
data.db.add_asset_movements([movement1, movement2])
errors = msg_aggregator.consume_errors()
warnings = msg_aggregator.consume_warnings()
assert len(errors) == 0
assert len(warnings) == 0
returned_movements = data.db.get_asset_movements()
assert returned_movements == [movement1, movement2]
# Add the last 2 movements. Since movement2 already exists in the DB it should be
# ignored and a warning should be shown
data.db.add_asset_movements([movement2, movement3])
errors = msg_aggregator.consume_errors()
warnings = msg_aggregator.consume_warnings()
assert len(errors) == 0
assert len(warnings) == 1
returned_movements = data.db.get_asset_movements()
assert returned_movements == [movement1, movement2, movement3]
def test_add_ethereum_transactions(data_dir, username):
"""Test that adding and retrieving ethereum transactions from the DB works fine.
Also duplicates should be ignored and an error returned
"""
msg_aggregator = MessagesAggregator()
data = DataHandler(data_dir, msg_aggregator)
data.unlock(username, '123', create_new=True)
tx1 = EthereumTransaction(
tx_hash=b'1',
timestamp=Timestamp(1451606400),
block_number=1,
from_address=ETH_ADDRESS1,
to_address=ETH_ADDRESS3,
value=FVal('2000000'),
gas=FVal('5000000'),
gas_price=FVal('2000000000'),
gas_used=FVal('25000000'),
input_data=MOCK_INPUT_DATA,
nonce=1,
)
tx2 = EthereumTransaction(
tx_hash=b'2',
timestamp=Timestamp(1451706400),
block_number=3,
from_address=ETH_ADDRESS2,
to_address=ETH_ADDRESS3,
value=FVal('4000000'),
gas=FVal('5000000'),
gas_price=FVal('2000000000'),
gas_used=FVal('25000000'),
input_data=MOCK_INPUT_DATA,
nonce=1,
)
tx3 = EthereumTransaction(
tx_hash=b'3',
timestamp=Timestamp(1452806400),
block_number=5,
from_address=ETH_ADDRESS3,
to_address=ETH_ADDRESS1,
value=FVal('1000000'),
gas=FVal('5000000'),
gas_price=FVal('2000000000'),
gas_used=FVal('25000000'),
input_data=MOCK_INPUT_DATA,
nonce=3,
)
# Add and retrieve the first 2 margins. All should be fine.
data.db.add_ethereum_transactions([tx1, tx2], from_etherscan=True)
errors = msg_aggregator.consume_errors()
warnings = msg_aggregator.consume_warnings()
assert len(errors) == 0
assert len(warnings) == 0
returned_transactions = data.db.get_ethereum_transactions()
assert returned_transactions == [tx1, tx2]
# Add the last 2 transactions. Since tx2 already exists in the DB it should be
# ignored (no errors shown for attempting to add already existing transaction)
data.db.add_ethereum_transactions([tx2, tx3], from_etherscan=True)
errors = msg_aggregator.consume_errors()
warnings = msg_aggregator.consume_warnings()
assert len(errors) == 0
assert len(warnings) == 0
returned_transactions = data.db.get_ethereum_transactions()
assert returned_transactions == [tx1, tx2, tx3]
@pytest.mark.parametrize('ethereum_accounts', [[]])
def test_non_checksummed_eth_account_in_db(database):
"""
Regression test for https://github.com/rotki/rotki/issues/519
This is a test for an occasion that should not happen in a normal run.
Only if the user manually edits the DB and modifies a blockchain account
to be non-checksummed then this scenario will happen.
This test verifies that the user is warned and the address is skipped.
"""
# Manually enter three blockchain ETH accounts one of which is only valid
cursor = database.conn.cursor()
valid_address = '0x9531C059098e3d194fF87FebB587aB07B30B1306'
non_checksummed_address = '0xe7302e6d805656cf37bd6839a977fe070184bf45'
invalid_address = 'dsads'
cursor.executemany(
'INSERT INTO blockchain_accounts(blockchain, account) VALUES (?, ?)',
(
('ETH', non_checksummed_address),
('ETH', valid_address),
('ETH', invalid_address)),
)
database.conn.commit()
blockchain_accounts = database.get_blockchain_accounts()
eth_accounts = blockchain_accounts.eth
assert len(eth_accounts) == 1
assert eth_accounts[0] == valid_address
errors = database.msg_aggregator.consume_errors()
warnings = database.msg_aggregator.consume_warnings()
assert len(errors) == 0
assert len(warnings) == 2
assert f'Non-checksummed eth address {non_checksummed_address}' in warnings[0]
assert f'Non-checksummed eth address {invalid_address}' in warnings[1]
def test_can_unlock_db_with_disabled_taxfree_after_period(data_dir, username):
"""Test that with taxfree_after_period being empty the DB can be opened
Regression test for https://github.com/rotki/rotki/issues/587
"""
# Set the setting
msg_aggregator = MessagesAggregator()
data = DataHandler(data_dir, msg_aggregator)
data.unlock(username, '123', create_new=True)
data.db.set_settings(ModifiableDBSettings(taxfree_after_period=-1))
# now relogin and check that no exception is thrown
del data
data = DataHandler(data_dir, msg_aggregator)
data.unlock(username, '123', create_new=False)
settings = data.db.get_settings()
assert settings.taxfree_after_period is None
def test_set_get_rotkehlchen_premium_credentials(data_dir, username):
"""Test that setting the premium credentials and getting them back from the DB works
"""
api_key = (
'kWT/MaPHwM2W1KUEl2aXtkKG6wJfMW9KxI7SSerI6/QzchC45/GebPV9xYZy7f+VKBeh5nDRBJBCYn7WofMO4Q=='
)
secret = (
'TEF5dFFrOFcwSXNrM2p1aDdHZmlndFRoMTZQRWJhU2dacTdscUZSeHZTRmJLRm5ZaVRlV2NYU'
'llYR1lxMjlEdUtRdFptelpCYmlXSUZGRTVDNWx3NDNYbjIx'
)
credentials = PremiumCredentials(
given_api_key=api_key,
given_api_secret=secret,
)
msg_aggregator = MessagesAggregator()
data = DataHandler(data_dir, msg_aggregator)
data.unlock(username, '123', create_new=True)
data.db.set_rotkehlchen_premium(credentials)
returned_credentials = data.db.get_rotkehlchen_premium()
assert returned_credentials == credentials
assert returned_credentials.serialize_key() == api_key
assert returned_credentials.serialize_secret() == secret
def test_unlock_with_invalid_premium_data(data_dir, username):
"""Test that invalid premium credentials unlock still works
"""
# First manually write invalid data to the DB
msg_aggregator = MessagesAggregator()
data = DataHandler(data_dir, msg_aggregator)
data.unlock(username, '123', create_new=True)
cursor = data.db.conn.cursor()
cursor.execute(
'INSERT OR REPLACE INTO user_credentials(name, api_key, api_secret) VALUES (?, ?, ?)',
('rotkehlchen', 'foo', 'boo'),
)
data.db.conn.commit()
# now relogin and check that no exception is thrown
del data
data = DataHandler(data_dir, msg_aggregator)
data.unlock(username, '123', create_new=False)
# and that an error is logged when trying to get premium
assert not data.db.get_rotkehlchen_premium()
warnings = msg_aggregator.consume_warnings()
errors = msg_aggregator.consume_errors()
assert len(warnings) == 0
assert len(errors) == 1
assert 'Incorrect Rotki API Key/Secret format found in the DB' in errors[0]
@pytest.mark.parametrize('include_etherscan_key', [False])
@pytest.mark.parametrize('include_cryptocompare_key', [False])
def test_get_external_service_credentials(database):
# Test that if the service is not in DB 'None' is returned
for service in ExternalService:
assert not database.get_external_service_credentials(service)
# add entries for all services
database.add_external_service_credentials(
[ExternalServiceApiCredentials(s, f'{s.name.lower()}_key') for s in ExternalService],
)
# now make sure that they are returned individually
for service in ExternalService:
credentials = database.get_external_service_credentials(service)
assert credentials.service == service
assert credentials.api_key == f'{service.name.lower()}_key'
| test_balance_save_frequency_check |
state_test.go | package session
import (
"context" |
"github.com/argoproj/argo-cd/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestUserStateStorage_LoadRevokedTokens(t *testing.T) {
redis, closer := test.NewInMemoryRedis()
defer closer()
err := redis.Set(context.Background(), revokedTokenPrefix+"abc", "", time.Hour).Err()
require.NoError(t, err)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
storage := NewUserStateStorage(redis)
storage.Init(ctx)
time.Sleep(time.Millisecond * 100)
assert.True(t, storage.IsTokenRevoked("abc"))
} | "testing"
"time" |
decoded.dto.ts | import { Role } from '@prisma/client';
export class | {
id: number;
userId: string;
name: string;
role: Role;
iat: number;
exp: number;
}
| DecodedDto |
Vote.tsx | import { useWeb3React } from '@web3-react/core';
import { ReactComponent as IconLink } from 'assets/icons/link.svg';
import { CountdownTimer } from 'components/countdownTimer/CountdownTimer';
import { ModalVbnt } from 'elements/modalVbnt/ModalVbnt';
import { useInterval } from 'hooks/useInterval';
import { useCallback, useState } from 'react';
import { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { useAppSelector } from 'redux/index';
import { openWalletModal } from 'redux/user/user';
import { Token } from 'services/observables/tokens';
import { getNetworkVariables } from 'services/web3/config';
import {
getStakedAmount,
getUnstakeTimer,
} from 'services/web3/governance/governance';
import { EthNetworks } from 'services/web3/types';
import { formatTime, prettifyNumber } from 'utils/helperFunctions';
interface VoteCardProps {
title: string;
step: number;
content: string;
button: string;
onClick: Function;
footer: JSX.Element;
}
const VoteCard = ({
title,
step,
content,
button,
onClick,
footer,
}: VoteCardProps) => {
return (
<div className="flex flex-col bg-white dark:bg-blue-4 max-w-[535px] min-h-[325px] px-30 pt-30 pb-[22px] shadow hover:shadow-lg dark:shadow-none rounded-20">
<div className="flex text-20 font-semibold mb-18">
<div className="text-primary dark:text-primary-light mr-12">{`Step ${step}`}</div>
{title}
</div>
<div className="text-14 text-grey-4 dark:text-grey-0 mb-auto">
{content}
</div>
<button
className="btn-primary rounded w-[220px] h-[37px] mt-20 text-14"
onClick={() => onClick()}
>
{button}
</button>
<hr className="widget-separator mb-15 mt-50" />
<div className="min-h-[48px]">{footer}</div>
</div>
);
};
export const Vote = () => {
const { chainId, account } = useWeb3React();
const tokens = useAppSelector<Token[]>((state) => state.bancor.tokens);
const [govToken, setGovToken] = useState<Token | undefined>();
const [stakeAmount, setStakeAmount] = useState<string | undefined>();
const [unstakeTime, setUnstakeTime] = useState<number | undefined>();
const [stakeModal, setStakeModal] = useState<boolean>(false);
const [isStake, setIsStake] = useState<boolean>(false);
const dispatch = useDispatch();
useEffect(() => {
const networkVars = getNetworkVariables(
chainId ? chainId : EthNetworks.Mainnet
);
setGovToken(tokens.find((x) => x.address === networkVars.govToken));
}, [tokens, chainId]);
const refresh = useCallback(async () => {
if (account && govToken) {
const [unstakeTimer, stakedAmount] = await Promise.all([
getUnstakeTimer(account),
getStakedAmount(account, govToken),
]);
setUnstakeTime(unstakeTimer);
setStakeAmount(stakedAmount);
} else {
setUnstakeTime(undefined);
setStakeAmount(undefined);
}
}, [account, govToken]);
useEffect(() => {
refresh();
}, [refresh]);
return (
<div className="flex flex-col text-14 max-w-[1140px] md:mx-auto mx-20">
<div className="font-bold text-3xl text-blue-4 dark:text-grey-0 mb-18">
Vote
</div>
<div className="text-blue-4 dark:text-grey-0 mb-44">
Bancor is a DAO managed by vBNT stakers who determine the future of the
protocol with their proposals.
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-y-50 gap-x-50">
<VoteCard
step={1}
title="Stake your vBNT"
content="In order to participate in Bancor governance activities, you should first stake your vBNT tokens."
button="Stake Tokens"
onClick={() => {
if (!account) {
dispatch(openWalletModal(true));
return;
}
setIsStake(true);
setStakeModal(true);
}}
footer={
<div className="grid grid-cols-2 text-grey-4 dark:text-grey-0">
<div>
{!account || (govToken && govToken.balance) ? (
<div className="text-blue-4 font-semibold text-20 dark:text-grey-0 mb-4">
{govToken && govToken.balance
? `${prettifyNumber(govToken.balance)} ${govToken.symbol}`
: '--'}
</div>
) : (
<div className="loading-skeleton h-[24px] w-[140px] mb-4" />
)}
Unstaked Balance
</div>
<div>
{!account || stakeAmount ? (
<div className="text-blue-4 font-semibold text-20 dark:text-grey-0 mb-4">
{stakeAmount && govToken
? `${prettifyNumber(stakeAmount)} ${govToken.symbol}`
: '--'}
</div>
) : (
<div className="loading-skeleton h-[24px] w-[140px] mb-4" />
)}
Staked Balance
</div>
</div>
}
/>
<VoteCard
step={2}
title="Make a Difference"
content="Voting on Bancor DAO is free as it is using the Snapshot off-chain infrastructure. Every user can vote on every available proposal and help shape the future of the Bancor Protocol."
button="Vote on Snapshot"
onClick={() => {
window.open('https://vote.bancor.network/', '_blank', 'noopener');
}}
footer={
<div className="flex items-end h-[48px]">
<a
href="https://blog.bancor.network/gasless-voting-is-live-on-bancor-governance-82d232da16b9"
target="_blank"
className="flex items-center text-primary dark:text-primary-light font-medium"
rel="noreferrer"
>
How to Vote <IconLink className="w-14 ml-6" />
</a>
</div>
}
/>
<div className="flex flex-col md:flex-row md:col-span-2 md:items-center bg-white dark:bg-blue-4 shadow hover:shadow-lg dark:shadow-none rounded-20 mb-20">
<div className="flex flex-col max-w-[520px] min-h-[170px] p-24">
<div className="text-16 text-blue-4 dark:text-grey-0 mb-18 font-medium">
Unstake from Governance
</div>
<div className="text-12 text-grey-4 dark:text-grey-0 mb-auto">
In order to remove vBNT from governance you would need to unstake
them first.
</div>
<button | className={`text-12 font-medium btn-sm rounded-10 max-w-[190px] ${
!!unstakeTime || !stakeAmount || Number(stakeAmount) === 0
? 'btn-outline-secondary text-grey-3 dark:bg-blue-3 dark:text-grey-3 dark:border-grey-3'
: 'btn-outline-primary border border-primary hover:border-primary-dark hover:bg-white hover:text-primary-dark dark:border-primary-light dark:hover:border-primary-light dark:hover:bg-blue-3 dark:hover:text-primary-light'
}`}
disabled={
!!unstakeTime || !stakeAmount || Number(stakeAmount) === 0
}
onClick={() => {
setIsStake(false);
setStakeModal(true);
}}
>
{unstakeTime && (
<span className="mr-[3px]">
<CountdownTimer date={unstakeTime} />
</span>
)}
Unstake Tokens
</button>
</div>
<hr className="widget-separator md:transform md:rotate-90 md:w-[120px] my-0 ml-2" />
<div className="flex flex-col max-w-[525px] min-h-[170px] py-24 pl-24 md:pl-8">
<div className="text-16 text-blue-4 dark:text-grey-0 mb-18 font-medium">
Legacy onchain contract
</div>
<div className="text-12 text-grey-4 dark:text-grey-0 mb-auto">
View previous votes and decisions made onchain.
</div>
<a
href="https://etherscan.io/address/0x892f481bd6e9d7d26ae365211d9b45175d5d00e4"
target="_blank"
className="flex items-center text-primary dark:text-primary-light font-medium"
rel="noreferrer"
>
View Legacy Gov <IconLink className="w-14 ml-6" />
</a>
</div>
</div>
</div>
{govToken && (
<ModalVbnt
isOpen={stakeModal}
setIsOpen={setStakeModal}
token={govToken}
stake={isStake}
stakeBalance={stakeAmount}
onCompleted={refresh}
/>
)}
</div>
);
}; | |
materi.js | var _validFileExtensions = [".jpg", ".jpeg", ".png"];
function | () {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("cover").files[0]);
oFReader.onload = function (oFREvent)
{
document.getElementById("uploadPreviewCover").src = oFREvent.target.result;
};
}
function ValidateSingleInputCover(oInput) {
if (oInput.type == "file") {
var sFileName = oInput.value;
if (typeof (oInput.files) != "undefined") {
var size = parseFloat(oInput.files[0].size / 1024).toFixed(2);
if (size > 1024) {
$("#cover").val('');
toastr.error("Size exceeds limit!", "Notifications");
oInput.value = "";
document.getElementById("uploadPreviewCover").src = BASE_URL + "/backend/images/no_image.png";
return false;
}else{
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
PreviewImageCover();
break;
}
}
if (!blnValid) {
$("#cover").val('');
toastr.error("Format is not suitable!", "Notifications");
oInput.value = "";
document.getElementById("uploadPreviewCover").src = BASE_URL + "assets/backend/image/no_image.png";
return false;
}
}
}
} else {
toastr.error("The browser does not support this feature!", "Notifications");
}
}
return true;
}
$('.save').click(function(event) {
$('#form_add').validate({ // initialize the plugin
rules: {
judul_materi: {
required: true
},
materi_mapel: {
required: true
},
materi_kelas: {
required: true
},
isi_materi: {
required: true,
}
},
highlight: function(element) {
$(element).closest('.m-form__group').addClass('has-danger');
},
unhighlight: function(element) {
$(element).closest('.m-form__group').removeClass('has-danger');
},
errorElement: 'span',
errorClass: 'form-control-feedback',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
});
function formatRupiahType(bilangan, prefix)
{
var number_string = bilangan.replace(/[^,\d]/g, '').toString(),
split = number_string.split(','),
sisa = split[0].length % 3,
rupiah = split[0].substr(0, sisa),
ribuan = split[0].substr(sisa).match(/\d{1,3}/gi);
if (ribuan) {
separator = sisa ? '.' : '';
rupiah += separator + ribuan.join('.');
}
rupiah = split[1] != undefined ? rupiah + ',' + split[1] : rupiah;
return prefix == undefined ? rupiah : (rupiah ? 'Rp. ' + rupiah : '');
}
function limitCharacter(event)
{
key = event.which || event.keyCode;
if ( key != 188 // Comma
&& key != 8 // Backspace
&& key != 17 && key != 86 & key != 67 // Ctrl c, ctrl v
&& (key < 48 || key > 57) // Non digit
// Dan masih banyak lagi seperti tombol del, panah kiri dan kanan, tombol tab, dll
)
{
event.preventDefault();
return false;
}
}
$(document).ready(function() {
$('#content').summernote({
height: 150,
});
}); | PreviewImageCover |
pain.rs | #[doc = "Reader of register PAIN"]
pub type R = crate::R<u16, super::PAIN>;
#[doc = "Reader of field `P1IN`"]
pub type P1IN_R = crate::R<u8, u8>;
#[doc = "Reader of field `P2IN`"]
pub type P2IN_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:7 - Port 1 Input"]
#[inline(always)]
pub fn p1in(&self) -> P1IN_R {
P1IN_R::new((self.bits & 0xff) as u8)
}
#[doc = "Bits 8:15 - Port 2 Input"]
#[inline(always)]
pub fn p2in(&self) -> P2IN_R {
P2IN_R::new(((self.bits >> 8) & 0xff) as u8)
} | } |
|
courses.controller.ts | import { Body, Controller, Delete, Get, Param, Patch, Post} from '@nestjs/common';
import { response } from 'express';
import { CoursesService } from './courses.service';
import { CreateCourseDto } from './dto/create-course.dto';
import { UpdateCourseDto } from './dto/update-course.dto';
@Controller('courses')
export class CoursesController {
constructor(
private readonly coursesService: CoursesService
){}
@Get()
findAll(){
return this.coursesService.findAll();
}
@Get(':id')
findOne(@Param('id') id: string){
return this.coursesService.findOne(id); | }
@Post()
async create(@Body()createCourseDto: CreateCourseDto){
return this.coursesService.create(createCourseDto);
}
@Patch(':id')
update(@Param('id') id: string, @Body() updateCourseDto: UpdateCourseDto){
return this.coursesService.update(id, updateCourseDto);
}
@Delete(':id')
remove( @Param('id') id :string ){
return this.coursesService.remove(id);
}
} | |
setting.rs | use std::collections::{BTreeMap, BTreeSet};
use actix_web::{delete, get, post};
use actix_web::{web, HttpResponse};
use meilisearch_core::{MainReader, UpdateWriter};
use meilisearch_core::settings::{Settings, SettingsUpdate, UpdateState, DEFAULT_RANKING_RULES};
use meilisearch_schema::Schema;
use crate::Data;
use crate::error::{Error, ResponseError};
use crate::helpers::Authentication;
use crate::routes::{IndexParam, IndexUpdateResponse};
pub fn services(cfg: &mut web::ServiceConfig) {
cfg.service(update_all)
.service(get_all)
.service(delete_all)
.service(get_rules)
.service(update_rules)
.service(delete_rules)
.service(get_distinct)
.service(update_distinct)
.service(delete_distinct)
.service(get_searchable)
.service(update_searchable)
.service(delete_searchable)
.service(get_displayed)
.service(update_displayed)
.service(delete_displayed)
.service(get_attributes_for_faceting)
.service(delete_attributes_for_faceting)
.service(update_attributes_for_faceting);
}
pub fn update_all_settings_txn(
data: &web::Data<Data>,
settings: SettingsUpdate,
index_uid: &str,
write_txn: &mut UpdateWriter,
) -> Result<u64, Error> {
let index = data
.db
.open_index(index_uid)
.ok_or(Error::index_not_found(index_uid))?;
let update_id = index.settings_update(write_txn, settings)?;
Ok(update_id)
}
#[post("/indexes/{index_uid}/settings", wrap = "Authentication::Private")]
async fn update_all(
data: web::Data<Data>,
path: web::Path<IndexParam>,
body: web::Json<Settings>,
) -> Result<HttpResponse, ResponseError> {
let update_id = data.get_or_create_index(&path.index_uid, |index| {
Ok(data.db.update_write::<_, _, ResponseError>(|writer| {
let settings = body.into_inner().to_update().map_err(Error::bad_request)?;
let update_id = index.settings_update(writer, settings)?;
Ok(update_id)
})?)
})?;
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
}
pub fn get_all_sync(data: &web::Data<Data>, reader: &MainReader, index_uid: &str) -> Result<Settings, Error> {
let index = data
.db
.open_index(index_uid)
.ok_or(Error::index_not_found(index_uid))?;
let stop_words: BTreeSet<String> = index.main.stop_words(&reader)?.into_iter().collect();
let synonyms_list = index.main.synonyms(reader)?;
let mut synonyms = BTreeMap::new();
let index_synonyms = &index.synonyms;
for synonym in synonyms_list {
let list = index_synonyms.synonyms(reader, synonym.as_bytes())?;
synonyms.insert(synonym, list);
}
let ranking_rules = index
.main
.ranking_rules(reader)?
.unwrap_or(DEFAULT_RANKING_RULES.to_vec())
.into_iter()
.map(|r| r.to_string())
.collect();
let schema = index.main.schema(&reader)?;
let distinct_attribute = match (index.main.distinct_attribute(reader)?, &schema) {
(Some(id), Some(schema)) => schema.name(id).map(str::to_string),
_ => None,
};
let attributes_for_faceting = match (&schema, &index.main.attributes_for_faceting(&reader)?) {
(Some(schema), Some(attrs)) => attrs
.iter()
.filter_map(|&id| schema.name(id))
.map(str::to_string)
.collect(),
_ => vec![],
};
let searchable_attributes = schema.as_ref().map(get_indexed_attributes);
let displayed_attributes = schema.as_ref().map(get_displayed_attributes);
Ok(Settings {
ranking_rules: Some(Some(ranking_rules)),
distinct_attribute: Some(distinct_attribute),
searchable_attributes: Some(searchable_attributes),
displayed_attributes: Some(displayed_attributes),
stop_words: Some(Some(stop_words)),
synonyms: Some(Some(synonyms)),
attributes_for_faceting: Some(Some(attributes_for_faceting)),
})
}
#[get("/indexes/{index_uid}/settings", wrap = "Authentication::Private")]
async fn get_all(
data: web::Data<Data>,
path: web::Path<IndexParam>,
) -> Result<HttpResponse, ResponseError> {
let reader = data.db.main_read_txn()?;
let settings = get_all_sync(&data, &reader, &path.index_uid)?;
Ok(HttpResponse::Ok().json(settings))
}
#[delete("/indexes/{index_uid}/settings", wrap = "Authentication::Private")]
async fn delete_all(
data: web::Data<Data>,
path: web::Path<IndexParam>,
) -> Result<HttpResponse, ResponseError> {
let index = data
.db
.open_index(&path.index_uid)
.ok_or(Error::index_not_found(&path.index_uid))?;
let settings = SettingsUpdate {
ranking_rules: UpdateState::Clear,
distinct_attribute: UpdateState::Clear,
primary_key: UpdateState::Clear,
searchable_attributes: UpdateState::Clear,
displayed_attributes: UpdateState::Clear,
stop_words: UpdateState::Clear,
synonyms: UpdateState::Clear,
attributes_for_faceting: UpdateState::Clear,
};
let update_id = data
.db
.update_write(|w| index.settings_update(w, settings))?;
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
}
#[get(
"/indexes/{index_uid}/settings/ranking-rules",
wrap = "Authentication::Private"
)]
async fn get_rules(
data: web::Data<Data>,
path: web::Path<IndexParam>,
) -> Result<HttpResponse, ResponseError> {
let index = data
.db
.open_index(&path.index_uid)
.ok_or(Error::index_not_found(&path.index_uid))?;
let reader = data.db.main_read_txn()?;
let ranking_rules = index
.main
.ranking_rules(&reader)?
.unwrap_or(DEFAULT_RANKING_RULES.to_vec())
.into_iter()
.map(|r| r.to_string())
.collect::<Vec<String>>();
Ok(HttpResponse::Ok().json(ranking_rules))
}
#[post(
"/indexes/{index_uid}/settings/ranking-rules",
wrap = "Authentication::Private"
)]
async fn update_rules(
data: web::Data<Data>,
path: web::Path<IndexParam>,
body: web::Json<Option<Vec<String>>>,
) -> Result<HttpResponse, ResponseError> {
let update_id = data.get_or_create_index(&path.index_uid, |index| {
let settings = Settings {
ranking_rules: Some(body.into_inner()),
..Settings::default()
};
let settings = settings.to_update().map_err(Error::bad_request)?;
Ok(data
.db
.update_write(|w| index.settings_update(w, settings))?)
})?;
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
}
#[delete(
"/indexes/{index_uid}/settings/ranking-rules",
wrap = "Authentication::Private"
)]
async fn delete_rules(
data: web::Data<Data>,
path: web::Path<IndexParam>,
) -> Result<HttpResponse, ResponseError> {
let index = data
.db
.open_index(&path.index_uid)
.ok_or(Error::index_not_found(&path.index_uid))?;
let settings = SettingsUpdate {
ranking_rules: UpdateState::Clear,
..SettingsUpdate::default()
};
let update_id = data
.db
.update_write(|w| index.settings_update(w, settings))?;
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
}
#[get(
"/indexes/{index_uid}/settings/distinct-attribute",
wrap = "Authentication::Private"
)]
async fn get_distinct(
data: web::Data<Data>,
path: web::Path<IndexParam>,
) -> Result<HttpResponse, ResponseError> {
let index = data
.db
.open_index(&path.index_uid)
.ok_or(Error::index_not_found(&path.index_uid))?;
let reader = data.db.main_read_txn()?;
let distinct_attribute_id = index.main.distinct_attribute(&reader)?;
let schema = index.main.schema(&reader)?;
let distinct_attribute = match (schema, distinct_attribute_id) {
(Some(schema), Some(id)) => schema.name(id).map(str::to_string),
_ => None,
};
Ok(HttpResponse::Ok().json(distinct_attribute))
}
#[post(
"/indexes/{index_uid}/settings/distinct-attribute",
wrap = "Authentication::Private"
)]
async fn update_distinct(
data: web::Data<Data>,
path: web::Path<IndexParam>,
body: web::Json<Option<String>>,
) -> Result<HttpResponse, ResponseError> {
let update_id = data.get_or_create_index(&path.index_uid, |index| {
let settings = Settings {
distinct_attribute: Some(body.into_inner()),
..Settings::default()
};
let settings = settings.to_update().map_err(Error::bad_request)?;
Ok(data
.db
.update_write(|w| index.settings_update(w, settings))?)
})?;
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
}
#[delete(
"/indexes/{index_uid}/settings/distinct-attribute",
wrap = "Authentication::Private"
)]
async fn delete_distinct(
data: web::Data<Data>,
path: web::Path<IndexParam>,
) -> Result<HttpResponse, ResponseError> {
let index = data
.db
.open_index(&path.index_uid)
.ok_or(Error::index_not_found(&path.index_uid))?;
let settings = SettingsUpdate {
distinct_attribute: UpdateState::Clear,
..SettingsUpdate::default()
};
let update_id = data
.db
.update_write(|w| index.settings_update(w, settings))?;
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
}
#[get(
"/indexes/{index_uid}/settings/searchable-attributes",
wrap = "Authentication::Private"
)]
async fn get_searchable(
data: web::Data<Data>,
path: web::Path<IndexParam>,
) -> Result<HttpResponse, ResponseError> {
let index = data
.db
.open_index(&path.index_uid)
.ok_or(Error::index_not_found(&path.index_uid))?;
let reader = data.db.main_read_txn()?;
let schema = index.main.schema(&reader)?;
let searchable_attributes: Option<Vec<String>> = schema.as_ref().map(get_indexed_attributes);
Ok(HttpResponse::Ok().json(searchable_attributes))
}
#[post(
"/indexes/{index_uid}/settings/searchable-attributes",
wrap = "Authentication::Private"
)]
async fn update_searchable(
data: web::Data<Data>,
path: web::Path<IndexParam>,
body: web::Json<Option<Vec<String>>>,
) -> Result<HttpResponse, ResponseError> {
let update_id = data.get_or_create_index(&path.index_uid, |index| {
let settings = Settings {
searchable_attributes: Some(body.into_inner()),
..Settings::default()
};
let settings = settings.to_update().map_err(Error::bad_request)?;
Ok(data
.db
.update_write(|w| index.settings_update(w, settings))?)
})?;
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
}
#[delete(
"/indexes/{index_uid}/settings/searchable-attributes",
wrap = "Authentication::Private"
)]
async fn delete_searchable(
data: web::Data<Data>,
path: web::Path<IndexParam>,
) -> Result<HttpResponse, ResponseError> {
let index = data
.db
.open_index(&path.index_uid)
.ok_or(Error::index_not_found(&path.index_uid))?;
let settings = SettingsUpdate {
searchable_attributes: UpdateState::Clear,
..SettingsUpdate::default()
};
let update_id = data
.db
.update_write(|w| index.settings_update(w, settings))?;
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
}
#[get(
"/indexes/{index_uid}/settings/displayed-attributes",
wrap = "Authentication::Private"
)]
async fn get_displayed(
data: web::Data<Data>,
path: web::Path<IndexParam>,
) -> Result<HttpResponse, ResponseError> {
let index = data
.db
.open_index(&path.index_uid)
.ok_or(Error::index_not_found(&path.index_uid))?;
let reader = data.db.main_read_txn()?;
let schema = index.main.schema(&reader)?;
let displayed_attributes = schema.as_ref().map(get_displayed_attributes);
Ok(HttpResponse::Ok().json(displayed_attributes))
}
#[post(
"/indexes/{index_uid}/settings/displayed-attributes",
wrap = "Authentication::Private"
)]
async fn update_displayed(
data: web::Data<Data>,
path: web::Path<IndexParam>,
body: web::Json<Option<BTreeSet<String>>>,
) -> Result<HttpResponse, ResponseError> {
let update_id = data.get_or_create_index(&path.index_uid, |index| {
let settings = Settings {
displayed_attributes: Some(body.into_inner()),
..Settings::default()
};
let settings = settings.to_update().map_err(Error::bad_request)?;
Ok(data
.db
.update_write(|w| index.settings_update(w, settings))?)
})?;
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
}
#[delete(
"/indexes/{index_uid}/settings/displayed-attributes",
wrap = "Authentication::Private"
)]
async fn delete_displayed(
data: web::Data<Data>,
path: web::Path<IndexParam>,
) -> Result<HttpResponse, ResponseError> {
let index = data
.db
.open_index(&path.index_uid)
.ok_or(Error::index_not_found(&path.index_uid))?;
let settings = SettingsUpdate {
displayed_attributes: UpdateState::Clear,
..SettingsUpdate::default()
};
let update_id = data
.db
.update_write(|w| index.settings_update(w, settings))?;
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
}
#[get(
"/indexes/{index_uid}/settings/attributes-for-faceting",
wrap = "Authentication::Private"
)]
async fn get_attributes_for_faceting(
data: web::Data<Data>,
path: web::Path<IndexParam>,
) -> Result<HttpResponse, ResponseError> {
let index = data
.db
.open_index(&path.index_uid)
.ok_or(Error::index_not_found(&path.index_uid))?;
let attributes_for_faceting = data.db.main_read::<_, _, ResponseError>(|reader| {
let schema = index.main.schema(reader)?;
let attrs = index.main.attributes_for_faceting(reader)?;
let attr_names = match (&schema, &attrs) {
(Some(schema), Some(attrs)) => attrs
.iter()
.filter_map(|&id| schema.name(id))
.map(str::to_string)
.collect(),
_ => vec![],
};
Ok(attr_names)
})?;
Ok(HttpResponse::Ok().json(attributes_for_faceting))
}
#[post( | data: web::Data<Data>,
path: web::Path<IndexParam>,
body: web::Json<Option<Vec<String>>>,
) -> Result<HttpResponse, ResponseError> {
let update_id = data.get_or_create_index(&path.index_uid, |index| {
let settings = Settings {
attributes_for_faceting: Some(body.into_inner()),
..Settings::default()
};
let settings = settings.to_update().map_err(Error::bad_request)?;
Ok(data
.db
.update_write(|w| index.settings_update(w, settings))?)
})?;
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
}
#[delete(
"/indexes/{index_uid}/settings/attributes-for-faceting",
wrap = "Authentication::Private"
)]
async fn delete_attributes_for_faceting(
data: web::Data<Data>,
path: web::Path<IndexParam>,
) -> Result<HttpResponse, ResponseError> {
let index = data
.db
.open_index(&path.index_uid)
.ok_or(Error::index_not_found(&path.index_uid))?;
let settings = SettingsUpdate {
attributes_for_faceting: UpdateState::Clear,
..SettingsUpdate::default()
};
let update_id = data
.db
.update_write(|w| index.settings_update(w, settings))?;
Ok(HttpResponse::Accepted().json(IndexUpdateResponse::with_id(update_id)))
}
fn get_indexed_attributes(schema: &Schema) -> Vec<String> {
if schema.is_searchable_all() {
vec!["*".to_string()]
} else {
schema
.searchable_names()
.iter()
.map(|s| s.to_string())
.collect()
}
}
fn get_displayed_attributes(schema: &Schema) -> BTreeSet<String> {
if schema.is_displayed_all() {
["*"].iter().map(|s| s.to_string()).collect()
} else {
schema
.displayed_names()
.iter()
.map(|s| s.to_string())
.collect()
}
} | "/indexes/{index_uid}/settings/attributes-for-faceting",
wrap = "Authentication::Private"
)]
async fn update_attributes_for_faceting( |
any_of.rs | use crate::{
compilation::{compile_validators, context::CompilationContext, JSONSchema},
error::{CompilationError, ValidationError},
keywords::{format_vec_of_validators, CompilationResult, Validators},
validator::Validate,
};
use serde_json::{Map, Value};
pub(crate) struct AnyOfValidator {
schemas: Vec<Validators>,
}
impl AnyOfValidator {
#[inline]
pub(crate) fn compile(schema: &Value, context: &CompilationContext) -> CompilationResult {
if let Value::Array(items) = schema {
let mut schemas = Vec::with_capacity(items.len());
for item in items {
let validators = compile_validators(item, context)?;
schemas.push(validators)
}
Ok(Box::new(AnyOfValidator { schemas }))
} else {
Err(CompilationError::SchemaError)
}
}
}
macro_rules! any_of_impl_is_valid {
($method_suffix:tt, $instance_type: ty) => {
paste::item! {
#[inline]
fn [<is_valid_ $method_suffix>](
&self,
schema: &JSONSchema,
instance: &Value,
instance_value: $instance_type,
) -> bool {
self.schemas.iter().any(move |validators| {
validators.iter().all(move |validator| {
validator.[<is_valid_ $method_suffix>](schema, instance, instance_value)
})
})
}
}
};
}
impl Validate for AnyOfValidator {
#[inline]
fn build_validation_error<'a>(&self, instance: &'a Value) -> ValidationError<'a> {
ValidationError::any_of(instance)
}
any_of_impl_is_valid!(array, &[Value]);
any_of_impl_is_valid!(boolean, bool);
any_of_impl_is_valid!(null, ());
any_of_impl_is_valid!(number, f64);
any_of_impl_is_valid!(object, &Map<String, Value>);
any_of_impl_is_valid!(signed_integer, i64);
any_of_impl_is_valid!(string, &str);
any_of_impl_is_valid!(unsigned_integer, u64);
}
impl ToString for AnyOfValidator {
fn to_string(&self) -> String {
format!("anyOf: [{}]", format_vec_of_validators(&self.schemas))
}
}
#[inline]
pub(crate) fn compile(
_: &Map<String, Value>,
schema: &Value,
context: &CompilationContext,
) -> Option<CompilationResult> | {
Some(AnyOfValidator::compile(schema, context))
} |
|
lib.rs | use std::{
cmp::PartialEq,
collections::HashSet,
hash::{Hash, Hasher},
str::{self, FromStr},
};
use golang_parser::{tree_sitter::Node, Parser};
use pest::{iterators::Pairs, Parser as _};
// https://github.com/pest-parser/pest/issues/490#issuecomment-808942497
#[allow(clippy::upper_case_acronyms)]
pub(crate) mod convention_struct_tag_parser;
pub mod json;
use self::convention_struct_tag_parser::{ConventionStructTagParser, Rule};
pub use self::json::{JsonStructTag, JsonStructTagOption};
//
//
// | pub enum StructTag {
RawStringLiteral(String),
InterpretedStringLiteral(String),
Convention(HashSet<ConventionStructTag>),
}
#[derive(Eq, Debug, Clone)]
pub enum ConventionStructTag {
Json(JsonStructTag),
Unknown(String, String),
}
impl PartialEq for ConventionStructTag {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Json(_), Self::Json(_)) => true,
(Self::Unknown(key, _), Self::Unknown(other_key, _)) => key == other_key,
_ => false,
}
}
}
impl Hash for ConventionStructTag {
fn hash<H: Hasher>(&self, state: &mut H) {
match self {
Self::Json(_) => "json".hash(state),
Self::Unknown(key, _) => key.hash(state),
}
}
}
impl StructTag {
pub fn as_json_struct_tag(&self) -> Option<&JsonStructTag> {
match self {
Self::Convention(set) => match set
.iter()
.find(|x| x == &&ConventionStructTag::Json(JsonStructTag::Ignored))
{
Some(ConventionStructTag::Json(x)) => Some(x),
_ => None,
},
_ => None,
}
}
}
#[derive(thiserror::Error, Debug)]
pub enum StructTagParseError {
#[error("GolangParserError {0:?}")]
GolangParserError(#[from] golang_parser::Error),
#[error("NodeMissing {0}")]
NodeMissing(String),
#[error("NodeKindUnknown {0}")]
NodeKindUnknown(String),
#[error("Utf8Error {0:?}")]
Utf8Error(str::Utf8Error),
#[error("Unknown")]
Unknown,
}
impl FromStr for StructTag {
type Err = StructTagParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let parser = Parser::new(format!("type _ struct {{ string {} }};", s))?;
let source = parser.get_source();
let root_node = parser.get_root_node();
let mut cursor = root_node.walk();
let node_type_declaration = root_node
.named_children(&mut cursor)
.find(|node| node.kind() == "type_declaration")
.ok_or_else(|| StructTagParseError::NodeMissing("type_declaration".to_string()))?;
let node_type_spec = node_type_declaration
.named_children(&mut cursor)
.find(|node| node.kind() == "type_spec")
.ok_or_else(|| StructTagParseError::NodeMissing("type_spec".to_string()))?;
let _ = node_type_spec
.named_child(0)
.ok_or_else(|| StructTagParseError::NodeMissing("type_spec name".to_string()))?;
let node_struct_type = node_type_spec
.named_child(1)
.ok_or_else(|| StructTagParseError::NodeMissing("type_spec type".to_string()))?;
let node_field_declaration_list = node_struct_type
.named_children(&mut cursor)
.find(|node| node.kind() == "field_declaration_list")
.ok_or_else(|| {
StructTagParseError::NodeMissing("field_declaration_list".to_string())
})?;
let node_field_declaration = node_field_declaration_list
.named_children(&mut cursor)
.find(|node| node.kind() == "field_declaration")
.ok_or_else(|| StructTagParseError::NodeMissing("field_declaration".to_string()))?;
let _ = node_field_declaration.named_child(0).ok_or_else(|| {
StructTagParseError::NodeMissing("field_declaration type".to_string())
})?;
let node_field_declaration_tag = node_field_declaration
.named_child(1)
.ok_or_else(|| StructTagParseError::NodeMissing("field_declaration tag".to_string()))?;
match node_field_declaration_tag.kind() {
"raw_string_literal" => {
Self::from_raw_string_literal_node(node_field_declaration_tag, source)
}
"interpreted_string_literal" => {
Self::from_interpreted_string_literal_node(node_field_declaration_tag, source)
}
_ => Err(StructTagParseError::NodeKindUnknown(
node_field_declaration_tag.kind().to_owned(),
)),
}
}
}
impl StructTag {
pub fn from_raw_string_literal_node(
node: Node,
source: &[u8],
) -> Result<Self, StructTagParseError> {
let s = node
.utf8_text(source)
.map_err(StructTagParseError::Utf8Error)?;
match ConventionStructTagParser::parse(Rule::tag, s) {
Ok(pairs) => ConventionStructTag::from_pairs(pairs)
.map(|x| Self::Convention(x.into_iter().collect())),
Err(_) => Ok(Self::RawStringLiteral(s.to_owned())),
}
}
pub fn from_interpreted_string_literal_node(
node: Node,
source: &[u8],
) -> Result<Self, StructTagParseError> {
let s = node
.utf8_text(source)
.map_err(StructTagParseError::Utf8Error)?;
Ok(Self::InterpretedStringLiteral(s.to_owned()))
}
}
impl ConventionStructTag {
fn from_pairs(mut pairs: Pairs<'_, Rule>) -> Result<Vec<Self>, StructTagParseError> {
let pair = pairs.next().ok_or(StructTagParseError::Unknown)?;
match pair.as_rule() {
Rule::tag => pair
.into_inner()
.map(|pair| {
let pair = pair
.into_inner()
.next()
.ok_or(StructTagParseError::Unknown)?;
match pair.as_rule() {
Rule::json => {
JsonStructTag::from_json_pairs(pair.into_inner()).map(Self::Json)
}
Rule::other => {
let mut pairs = pair.into_inner();
let key = pairs.next().ok_or(StructTagParseError::Unknown)?;
let value = pairs.next().ok_or(StructTagParseError::Unknown)?;
Ok(Self::Unknown(
key.as_str().to_owned(),
value.as_str().to_owned(),
))
}
_ => Err(StructTagParseError::Unknown),
}
})
.collect(),
_ => Err(StructTagParseError::Unknown),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::error;
#[test]
fn test_parse() -> Result<(), Box<dyn error::Error>> {
assert_eq!(
StructTag::RawStringLiteral(r#"`foo"bar`"#.to_owned()),
r#"`foo"bar`"#.parse()?
);
assert_eq!(
StructTag::InterpretedStringLiteral(r#""foo`bar""#.to_owned()),
r#""foo`bar""#.parse()?
);
assert_eq!(
StructTag::Convention(
vec![ConventionStructTag::Unknown(
"foo".to_owned(),
"bar".to_owned()
)]
.into_iter()
.collect()
),
r#"`foo:"bar"`"#.parse()?
);
Ok(())
}
#[test]
fn test_json_struct_tag() {
assert_eq!(
StructTag::Convention(
vec![ConventionStructTag::Json(JsonStructTag::Ignored)]
.into_iter()
.collect(),
)
.as_json_struct_tag(),
Some(&JsonStructTag::Ignored)
);
assert_eq!(
StructTag::Convention(
vec![ConventionStructTag::Json(JsonStructTag::Normal(
Some("foo".to_owned()),
vec![]
))]
.into_iter()
.collect(),
)
.as_json_struct_tag(),
Some(&JsonStructTag::Normal(Some("foo".to_owned()), vec![]))
);
assert_eq!(
StructTag::Convention(
vec![ConventionStructTag::Unknown(
"foo".to_owned(),
"bar".to_owned(),
)]
.into_iter()
.collect(),
)
.as_json_struct_tag(),
None
);
}
} | #[derive(PartialEq, Eq, Debug, Clone)] |
watcher_client.py | import time
import logging
from .spotify_client import SpotifyPlaylistClient
from . import config
logger = logging.getLogger(name='spotify_tracker')
class SpotifyWatcherClient(SpotifyPlaylistClient):
def __init__(self):
self.playlist_id = config.get_config_value('watcher_playlist_id')
self.last_track_id = None
return super().__init__()
def setup_playlist_id(self):
print("You need to add a playlist_id to your config to save "
"song history to.")
sp_playlists = self.sp.user_playlists(self.username)
playlists = [p for p in sp_playlists['items']
if p['owner']['id'] == self.username]
for playlist in playlists:
print('{}: {}'.format(playlist['name'], playlist['id']))
playlist_id = input("Please input the playlist_id of the Playlist "
"you'd like to save your history to: ")
config.save_config_value('watcher_playlist_id', playlist_id)
def main(self):
track_id = self.get_current_track_id()
if not track_id or track_id == self.last_track_id:
return
logger.info('Currently listening to {}'.format(
self.get_track_name_and_artist_string(track_id)
))
self.add_track_to_playlist(track_id)
self.last_track_id = track_id
def | (self):
if not self.check_config():
raise Exception("Please run setupwatcher command.")
logger.debug('Starting watch loop')
while True:
logger.debug('New watch lap completed.')
self.safe_main()
time.sleep(5)
| watch |
operations.rs | #![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use super::{models, API_VERSION};
#[derive(Clone)]
pub struct Client {
endpoint: String,
credential: std::sync::Arc<dyn azure_core::TokenCredential>,
scopes: Vec<String>,
pipeline: azure_core::pipeline::Pipeline,
}
#[derive(Clone)]
pub struct ClientBuilder {
credential: std::sync::Arc<dyn azure_core::TokenCredential>,
endpoint: Option<String>,
scopes: Option<Vec<String>>,
}
pub const DEFAULT_ENDPOINT: &str = azure_core::resource_manager_endpoint::AZURE_PUBLIC_CLOUD;
impl ClientBuilder {
pub fn new(credential: std::sync::Arc<dyn azure_core::TokenCredential>) -> Self {
Self {
credential,
endpoint: None,
scopes: None,
}
}
pub fn endpoint(mut self, endpoint: impl Into<String>) -> Self {
self.endpoint = Some(endpoint.into());
self
}
pub fn scopes(mut self, scopes: &[&str]) -> Self {
self.scopes = Some(scopes.iter().map(|scope| (*scope).to_owned()).collect());
self
}
pub fn build(self) -> Client {
let endpoint = self.endpoint.unwrap_or_else(|| DEFAULT_ENDPOINT.to_owned());
let scopes = self.scopes.unwrap_or_else(|| vec![format!("{}/", endpoint)]);
Client::new(endpoint, self.credential, scopes)
}
}
impl Client {
pub(crate) fn endpoint(&self) -> &str {
self.endpoint.as_str()
}
pub(crate) fn token_credential(&self) -> &dyn azure_core::TokenCredential {
self.credential.as_ref()
}
pub(crate) fn scopes(&self) -> Vec<&str> {
self.scopes.iter().map(String::as_str).collect()
}
pub(crate) async fn send(&self, request: impl Into<azure_core::Request>) -> Result<azure_core::Response, azure_core::Error> {
let mut context = azure_core::Context::default();
let mut request = request.into();
self.pipeline.send(&mut context, &mut request).await
}
pub fn new(endpoint: impl Into<String>, credential: std::sync::Arc<dyn azure_core::TokenCredential>, scopes: Vec<String>) -> Self {
let endpoint = endpoint.into();
let pipeline = azure_core::pipeline::Pipeline::new(
option_env!("CARGO_PKG_NAME"),
option_env!("CARGO_PKG_VERSION"),
azure_core::ClientOptions::default(),
Vec::new(),
Vec::new(),
);
Self {
endpoint,
credential,
scopes,
pipeline,
}
}
pub fn jobs(&self) -> jobs::Client {
jobs::Client(self.clone())
}
pub fn operations(&self) -> operations::Client {
operations::Client(self.clone())
}
pub fn service(&self) -> service::Client {
service::Client(self.clone())
}
}
#[non_exhaustive]
#[derive(Debug, thiserror :: Error)]
#[allow(non_camel_case_types)]
pub enum Error {
#[error(transparent)]
Operations_List(#[from] operations::list::Error),
#[error(transparent)]
Jobs_List(#[from] jobs::list::Error),
#[error(transparent)]
Mitigate(#[from] mitigate::Error),
#[error(transparent)]
Service_ListAvailableSkusByResourceGroup(#[from] service::list_available_skus_by_resource_group::Error),
#[error(transparent)]
Service_ValidateAddress(#[from] service::validate_address::Error),
#[error(transparent)]
Service_ValidateInputsByResourceGroup(#[from] service::validate_inputs_by_resource_group::Error),
#[error(transparent)]
Service_ValidateInputs(#[from] service::validate_inputs::Error),
#[error(transparent)]
Jobs_ListByResourceGroup(#[from] jobs::list_by_resource_group::Error),
#[error(transparent)]
Jobs_Get(#[from] jobs::get::Error),
#[error(transparent)]
Jobs_Create(#[from] jobs::create::Error),
#[error(transparent)]
Jobs_Update(#[from] jobs::update::Error),
#[error(transparent)]
Jobs_Delete(#[from] jobs::delete::Error),
#[error(transparent)]
Jobs_BookShipmentPickUp(#[from] jobs::book_shipment_pick_up::Error),
#[error(transparent)]
Jobs_Cancel(#[from] jobs::cancel::Error),
#[error(transparent)]
Jobs_ListCredentials(#[from] jobs::list_credentials::Error),
#[error(transparent)]
Service_RegionConfiguration(#[from] service::region_configuration::Error),
#[error(transparent)]
Service_RegionConfigurationByResourceGroup(#[from] service::region_configuration_by_resource_group::Error),
}
pub mod operations {
use super::{models, API_VERSION};
pub struct Client(pub(crate) super::Client);
impl Client {
pub fn list(&self) -> list::Builder {
list::Builder { client: self.0.clone() }
}
}
pub mod list {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ApiError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::OperationList, Error>> {
Box::pin(async move {
let url_str = &format!("{}/providers/Microsoft.DataBox/operations", self.client.endpoint(),);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::OperationList =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ApiError =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
}
pub mod jobs {
use super::{models, API_VERSION};
pub struct Client(pub(crate) super::Client);
impl Client {
pub fn list(&self, subscription_id: impl Into<String>) -> list::Builder {
list::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
skip_token: None,
}
}
pub fn list_by_resource_group(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
) -> list_by_resource_group::Builder {
list_by_resource_group::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
skip_token: None,
}
}
pub fn get(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
) -> get::Builder {
get::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
expand: None,
}
}
pub fn create(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
job_resource: impl Into<models::JobResource>,
) -> create::Builder {
create::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
job_resource: job_resource.into(),
}
}
pub fn update(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
job_resource_update_parameter: impl Into<models::JobResourceUpdateParameter>,
) -> update::Builder {
update::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
job_resource_update_parameter: job_resource_update_parameter.into(),
if_match: None,
}
}
pub fn delete(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
) -> delete::Builder {
delete::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
}
}
pub fn book_shipment_pick_up(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
shipment_pick_up_request: impl Into<models::ShipmentPickUpRequest>,
) -> book_shipment_pick_up::Builder {
book_shipment_pick_up::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
shipment_pick_up_request: shipment_pick_up_request.into(),
}
}
pub fn cancel(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
cancellation_reason: impl Into<models::CancellationReason>,
) -> cancel::Builder {
cancel::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
cancellation_reason: cancellation_reason.into(),
}
}
pub fn list_credentials(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
job_name: impl Into<String>,
) -> list_credentials::Builder {
list_credentials::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
job_name: job_name.into(),
}
}
}
pub mod list {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ApiError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) skip_token: Option<String>,
}
impl Builder {
pub fn skip_token(mut self, skip_token: impl Into<String>) -> Self {
self.skip_token = Some(skip_token.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::JobResourceList, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.DataBox/jobs",
self.client.endpoint(),
&self.subscription_id
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(skip_token) = &self.skip_token {
url.query_pairs_mut().append_pair("$skipToken", skip_token);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::JobResourceList =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ApiError =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod list_by_resource_group {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ApiError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) skip_token: Option<String>,
}
impl Builder {
pub fn skip_token(mut self, skip_token: impl Into<String>) -> Self {
self.skip_token = Some(skip_token.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::JobResourceList, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.DataBox/jobs",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(skip_token) = &self.skip_token {
url.query_pairs_mut().append_pair("$skipToken", skip_token);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::JobResourceList =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ApiError =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod get {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ApiError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) expand: Option<String>,
}
impl Builder {
pub fn expand(mut self, expand: impl Into<String>) -> Self {
self.expand = Some(expand.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::JobResource, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.DataBox/jobs/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(expand) = &self.expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::JobResource =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ApiError =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod create {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::JobResource),
Accepted202,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ApiError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) job_resource: models::JobResource,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.DataBox/jobs/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.job_resource).map_err(Error::Serialize)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::JobResource =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ApiError =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod update {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200(models::JobResource),
Accepted202,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ApiError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) job_resource_update_parameter: models::JobResourceUpdateParameter,
pub(crate) if_match: Option<String>,
}
impl Builder {
pub fn if_match(mut self, if_match: impl Into<String>) -> Self {
self.if_match = Some(if_match.into());
self
}
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.DataBox/jobs/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PATCH);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
if let Some(if_match) = &self.if_match {
req_builder = req_builder.header("If-Match", if_match);
}
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.job_resource_update_parameter).map_err(Error::Serialize)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?; | let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::JobResource =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(Response::Ok200(rsp_value))
}
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ApiError =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod delete {
use super::{models, API_VERSION};
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
NoContent204,
}
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ApiError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<Response, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.DataBox/jobs/{}",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::DELETE);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => Ok(Response::Ok200),
http::StatusCode::ACCEPTED => Ok(Response::Accepted202),
http::StatusCode::NO_CONTENT => Ok(Response::NoContent204),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ApiError =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod book_shipment_pick_up {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ApiError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) shipment_pick_up_request: models::ShipmentPickUpRequest,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::ShipmentPickUpResponse, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.DataBox/jobs/{}/bookShipmentPickUp",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.shipment_pick_up_request).map_err(Error::Serialize)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ShipmentPickUpResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ApiError =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod cancel {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ApiError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
pub(crate) cancellation_reason: models::CancellationReason,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<(), Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.DataBox/jobs/{}/cancel",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.cancellation_reason).map_err(Error::Serialize)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::NO_CONTENT => Ok(()),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ApiError =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod list_credentials {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ApiError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) job_name: String,
}
impl Builder {
pub fn into_future(
self,
) -> futures::future::BoxFuture<'static, std::result::Result<models::UnencryptedCredentialsList, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.DataBox/jobs/{}/listCredentials",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::UnencryptedCredentialsList =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ApiError =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
}
impl Client {
pub fn mitigate(
&self,
job_name: impl Into<String>,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
mitigate_job_request: impl Into<models::MitigateJobRequest>,
) -> mitigate::Builder {
mitigate::Builder {
client: self.clone(),
job_name: job_name.into(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
mitigate_job_request: mitigate_job_request.into(),
}
}
}
pub mod mitigate {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ApiError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::Client,
pub(crate) job_name: String,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) mitigate_job_request: models::MitigateJobRequest,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<(), Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.DataBox/jobs/{}/mitigate",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.job_name
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.mitigate_job_request).map_err(Error::Serialize)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::NO_CONTENT => Ok(()),
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ApiError =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod service {
use super::{models, API_VERSION};
pub struct Client(pub(crate) super::Client);
impl Client {
pub fn list_available_skus_by_resource_group(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
location: impl Into<String>,
available_sku_request: impl Into<models::AvailableSkuRequest>,
) -> list_available_skus_by_resource_group::Builder {
list_available_skus_by_resource_group::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
location: location.into(),
available_sku_request: available_sku_request.into(),
}
}
pub fn validate_address(
&self,
subscription_id: impl Into<String>,
location: impl Into<String>,
validate_address: impl Into<models::ValidateAddress>,
) -> validate_address::Builder {
validate_address::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
location: location.into(),
validate_address: validate_address.into(),
}
}
pub fn validate_inputs_by_resource_group(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
location: impl Into<String>,
validation_request: impl Into<models::ValidationRequest>,
) -> validate_inputs_by_resource_group::Builder {
validate_inputs_by_resource_group::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
location: location.into(),
validation_request: validation_request.into(),
}
}
pub fn validate_inputs(
&self,
subscription_id: impl Into<String>,
location: impl Into<String>,
validation_request: impl Into<models::ValidationRequest>,
) -> validate_inputs::Builder {
validate_inputs::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
location: location.into(),
validation_request: validation_request.into(),
}
}
pub fn region_configuration(
&self,
subscription_id: impl Into<String>,
location: impl Into<String>,
region_configuration_request: impl Into<models::RegionConfigurationRequest>,
) -> region_configuration::Builder {
region_configuration::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
location: location.into(),
region_configuration_request: region_configuration_request.into(),
}
}
pub fn region_configuration_by_resource_group(
&self,
subscription_id: impl Into<String>,
resource_group_name: impl Into<String>,
location: impl Into<String>,
region_configuration_request: impl Into<models::RegionConfigurationRequest>,
) -> region_configuration_by_resource_group::Builder {
region_configuration_by_resource_group::Builder {
client: self.0.clone(),
subscription_id: subscription_id.into(),
resource_group_name: resource_group_name.into(),
location: location.into(),
region_configuration_request: region_configuration_request.into(),
}
}
}
pub mod list_available_skus_by_resource_group {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ApiError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) location: String,
pub(crate) available_sku_request: models::AvailableSkuRequest,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::AvailableSkusResult, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.DataBox/locations/{}/availableSkus",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.location
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.available_sku_request).map_err(Error::Serialize)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::AvailableSkusResult =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ApiError =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod validate_address {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ApiError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) location: String,
pub(crate) validate_address: models::ValidateAddress,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::AddressValidationOutput, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.DataBox/locations/{}/validateAddress",
self.client.endpoint(),
&self.subscription_id,
&self.location
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.validate_address).map_err(Error::Serialize)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::AddressValidationOutput =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ApiError =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod validate_inputs_by_resource_group {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ApiError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) location: String,
pub(crate) validation_request: models::ValidationRequest,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::ValidationResponse, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.DataBox/locations/{}/validateInputs",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.location
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.validation_request).map_err(Error::Serialize)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ValidationResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ApiError =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod validate_inputs {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ApiError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) location: String,
pub(crate) validation_request: models::ValidationRequest,
}
impl Builder {
pub fn into_future(self) -> futures::future::BoxFuture<'static, std::result::Result<models::ValidationResponse, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.DataBox/locations/{}/validateInputs",
self.client.endpoint(),
&self.subscription_id,
&self.location
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.validation_request).map_err(Error::Serialize)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ValidationResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ApiError =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod region_configuration {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ApiError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) location: String,
pub(crate) region_configuration_request: models::RegionConfigurationRequest,
}
impl Builder {
pub fn into_future(
self,
) -> futures::future::BoxFuture<'static, std::result::Result<models::RegionConfigurationResponse, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.DataBox/locations/{}/regionConfiguration",
self.client.endpoint(),
&self.subscription_id,
&self.location
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.region_configuration_request).map_err(Error::Serialize)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::RegionConfigurationResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ApiError =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
pub mod region_configuration_by_resource_group {
use super::{models, API_VERSION};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ApiError,
},
#[error("Failed to parse request URL: {0}")]
ParseUrl(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequest(http::Error),
#[error("Failed to serialize request body: {0}")]
Serialize(serde_json::Error),
#[error("Failed to get access token: {0}")]
GetToken(azure_core::Error),
#[error("Failed to execute request: {0}")]
SendRequest(azure_core::Error),
#[error("Failed to get response bytes: {0}")]
ResponseBytes(azure_core::StreamError),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
Deserialize(serde_json::Error, bytes::Bytes),
}
#[derive(Clone)]
pub struct Builder {
pub(crate) client: super::super::Client,
pub(crate) subscription_id: String,
pub(crate) resource_group_name: String,
pub(crate) location: String,
pub(crate) region_configuration_request: models::RegionConfigurationRequest,
}
impl Builder {
pub fn into_future(
self,
) -> futures::future::BoxFuture<'static, std::result::Result<models::RegionConfigurationResponse, Error>> {
Box::pin(async move {
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.DataBox/locations/{}/regionConfiguration",
self.client.endpoint(),
&self.subscription_id,
&self.resource_group_name,
&self.location
);
let mut url = url::Url::parse(url_str).map_err(Error::ParseUrl)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
let credential = self.client.token_credential();
let token_response = credential
.get_token(&self.client.scopes().join(" "))
.await
.map_err(Error::GetToken)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
url.query_pairs_mut().append_pair("api-version", super::API_VERSION);
req_builder = req_builder.header("content-type", "application/json");
let req_body = azure_core::to_json(&self.region_configuration_request).map_err(Error::Serialize)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(Error::BuildRequest)?;
let rsp = self.client.send(req).await.map_err(Error::SendRequest)?;
let (rsp_status, rsp_headers, rsp_stream) = rsp.deconstruct();
match rsp_status {
http::StatusCode::OK => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::RegionConfigurationResponse =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = azure_core::collect_pinned_stream(rsp_stream).await.map_err(Error::ResponseBytes)?;
let rsp_value: models::ApiError =
serde_json::from_slice(&rsp_body).map_err(|source| Error::Deserialize(source, rsp_body.clone()))?;
Err(Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
})
}
}
}
} | |
Profile.tsx | import { useSelector } from "react-redux"; | enum Help {
start = "Draw a card or build line!",
draw = "Draw one more card or end turn!",
build_1 = "Select a destination from the map!",
build_2 = "Select the ending destination!",
}
function Profile() {
const player = useSelector(getCurrentPlayer);
const help: Help = Help.start;
return (
<div className="game-profile">
<div className="h4">Aktuális játékos:</div>
<div className="h5">{player?.name}</div>
<div>
<strong>{help}</strong>
</div>
</div>
);
}
export default Profile; | import { getCurrentPlayer } from "../../../state/selectors";
import "./profile.css";
|
empty-item.ts | import {
NodeDefinition,
StaticGraphNode,
StaticNodeDefinition,
StaticNodeType,
} from '../../types/graph';
import createNodeDefinition from '../../utils/create-node-definition';
import { createNodeType } from '../../utils/create-node-type';
/**
* An instance of the [[emptyItem]] node.
* See the [[emptyItem]] documentation to find out more.
*/
export interface EmptyItemNode extends StaticGraphNode<'empty-item', EmptyItemNodeProperties> {}
/**
* A definition of the [[emptyItem]] node.
* See the [[emptyItem]] documentation to find out more.
*/
export interface EmptyItemNodeDefinition
extends StaticNodeDefinition<'empty-item', EmptyItemNodeProperties> {}
export interface EmptyItemNodeProperties {}
/**
* An implementation of the [[emptyItem]] node.
* See the [[emptyItem]] documentation to find out more.
*/
export const EmptyItemNodeType: StaticNodeType<
'empty-item',
EmptyItemNodeProperties
> = createNodeType<'empty-item', EmptyItemNodeProperties>('empty-item', {
shape: {},
});
/**
* Creates a new instance of the [[emptyItem]] node. This node is used internally by [[proxy]] and [[placeholder]] nodes
* to indicate to the [[query]] node that a given remote collection query has returned no items, and that the [[query]]
* node should return an empty array instead.
*/
export function | (): EmptyItemNodeDefinition {
return createNodeDefinition(EmptyItemNodeType, {});
}
export function isEmptyItemNodeDefinition(value: NodeDefinition): value is EmptyItemNodeDefinition {
return value.type === EmptyItemNodeType;
}
| emptyItem |
fdp.py | #!/usr/env/python
# -*- coding: utf-8 -*-
'''
Python class for Forza Motorsport 7's data stream format.
Copyright (c) 2018 Morten Wang
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''
from struct import unpack
## Documentation of the packet format is available on
## https://forums.forzamotorsport.net/turn10_postsm926839_Forza-Motorsport-7--Data-Out--feature-details.aspx#post_926839
class ForzaDataPacket:
## Class variables are the specification of the format and the names of all
## the properties found in the data packet.
## Format string that allows unpack to process the data bytestream
## for the V1 format called 'sled'
sled_format = '<iIfffffffffffffffffffffffffffffffffffffffffffffffffffiiiii'
## Format string for the V2 format called 'car dash'
dash_format = '<iIfffffffffffffffffffffffffffffffffffffffffffffffffffiiiiifffffffffffffffffHBBBBBBbbb'
## Names of the properties in the order they're featured in the packet:
sled_props = [
'is_race_on', 'timestamp_ms',
'engine_max_rpm', 'engine_idle_rpm', 'current_engine_rpm',
'acceleration_x', 'acceleration_y', 'acceleration_z',
'velocity_x', 'velocity_y', 'velocity_z', | 'tire_slip_ratio_FL', 'tire_slip_ratio_FR',
'tire_slip_ratio_RL', 'tire_slip_ratio_RR',
'wheel_rotation_speed_FL', 'wheel_rotation_speed_FR',
'wheel_rotation_speed_RL', 'wheel_rotation_speed_RR',
'wheel_on_rumble_strip_FL', 'wheel_on_rumble_strip_FR',
'wheel_on_rumble_strip_RL', 'wheel_on_rumble_strip_RR',
'wheel_in_puddle_FL', 'wheel_in_puddle_FR',
'wheel_in_puddle_RL', 'wheel_in_puddle_RR',
'surface_rumble_FL', 'surface_rumble_FR',
'surface_rumble_RL', 'surface_rumble_RR',
'tire_slip_angle_FL', 'tire_slip_angle_FR',
'tire_slip_angle_RL', 'tire_slip_angle_RR',
'tire_combined_slip_FL', 'tire_combined_slip_FR',
'tire_combined_slip_RL', 'tire_combined_slip_RR',
'suspension_travel_meters_FL', 'suspension_travel_meters_FR',
'suspension_travel_meters_RL', 'suspension_travel_meters_RR',
'car_ordinal', 'car_class', 'car_performance_index',
'drivetrain_type', 'num_cylinders'
]
## The additional props added in the 'car dash' format
dash_props = ['position_x', 'position_y', 'position_z',
'speed', 'power', 'torque',
'tire_temp_FL', 'tire_temp_FR',
'tire_temp_RL', 'tire_temp_RR',
'boost', 'fuel', 'dist_traveled',
'best_lap_time', 'last_lap_time',
'cur_lap_time', 'cur_race_time',
'lap_no', 'race_pos',
'accel', 'brake', 'clutch', 'handbrake',
'gear', 'steer',
'norm_driving_line', 'norm_ai_brake_diff']
def __init__(self, data, packet_format='dash'):
## The format this data packet was created with:
self.packet_format = packet_format
## zip makes for convenient flexibility when mapping names to
## values in the data packet:
if packet_format == 'sled':
for prop_name, prop_value in zip(self.sled_props,
unpack(self.sled_format, data)):
setattr(self, prop_name, prop_value)
elif packet_format == 'fh4':
patched_data = data[:232] + data[244:323]
for prop_name, prop_value in zip(self.sled_props + self.dash_props,
unpack(self.dash_format,
patched_data)):
setattr(self, prop_name, prop_value)
else:
for prop_name, prop_value in zip(self.sled_props + self.dash_props,
unpack(self.dash_format, data)):
setattr(self, prop_name, prop_value)
@classmethod
def get_props(cls, packet_format = 'dash'):
'''
Return the list of properties in the data packet, in order.
:param packet_format: which packet format to get properties for,
one of either 'sled' or 'dash'
:type packet_format: str
'''
if packet_format == 'sled':
return(cls.sled_props)
return(cls.sled_props + cls.dash_props)
def to_list(self, attributes):
'''
Return the values of this data packet, in order. If a list of
attributes are provided, only return those.
:param attributes: the attributes to return
:type attributes: list
'''
if attributes:
return([getattr(self, a) for a in attributes])
if self.packet_format == 'sled':
return([getattr(self, prop_name) for prop_name in self.sled_props])
return([getattr(self, prop_name) for prop_name in \
self.sled_props + self.dash_props])
def get_format(self):
'''
Return the format this packet was sent with.
'''
return(self.packet_format)
def get_tsv_header(self):
'''
Return a tab-separated string with the names of all properties in the order defined in the data packet.
'''
if self.packet_format == 'sled':
return('\t'.join(self.sled_props))
return('\t'.join(self.sled_props + self.dash_props))
def to_tsv(self):
'''
Return a tab-separated values string with all data in the given order.
All floating point numbers are defined as such to allow for changing
the number of significant digits if desired.
'''
if self.packet_format == 'sled':
return('{0.is_race_on}\t{0.timestamp_ms}\t{0.engine_max_rpm:f}\t{0.engine_idle_rpm:f}\t{0.current_engine_rpm:f}\t{0.acceleration_x:f}\t{0.acceleration_y:f}\t{0.acceleration_z:f}\t{0.velocity_x:f}\t{0.velocity_y:f}\t{0.velocity_z:f}\t{0.angular_velocity_x:f}\t{0.angular_velocity_y:f}\t{0.angular_velocity_z:f}\t{0.yaw:f}\t{0.pitch:f}\t{0.roll:f}\t{0.norm_suspension_travel_FL:f}\t{0.norm_suspension_travel_FR:f}\t{0.norm_suspension_travel_RL:f}\t{0.norm_suspension_travel_RR:f}\t{0.tire_slip_ratio_FL:f}\t{0.tire_slip_ratio_FR:f}\t{0.tire_slip_ratio_RL:f}\t{0.tire_slip_ratio_RR:f}\t{0.wheel_rotation_speed_FL:f}\t{0.wheel_rotation_speed_FR:f}\t{0.wheel_rotation_speed_RL:f}\t{0.wheel_rotation_speed_RR:f}\t{0.wheel_on_rumble_strip_FL:f}\t{0.wheel_on_rumble_strip_FR:f}\t{0.wheel_on_rumble_strip_RL:f}\t{0.wheel_on_rumble_strip_RR:f}\t{0.wheel_in_puddle_FL:f}\t{0.wheel_in_puddle_FR:f}\t{0.wheel_in_puddle_RL:f}\t{0.wheel_in_puddle_RR:f}\t{0.surface_rumble_FL:f}\t{0.surface_rumble_FR:f}\t{0.surface_rumble_RL:f}\t{0.surface_rumble_RR:f}\t{0.tire_slip_angle_FL:f}\t{0.tire_slip_angle_FR:f}\t{0.tire_slip_angle_RL:f}\t{0.tire_slip_angle_RR:f}\t{0.tire_combined_slip_FL:f}\t{0.tire_combined_slip_FR:f}\t{0.tire_combined_slip_RL:f}\t{0.tire_combined_slip_RR:f}\t{0.suspension_travel_meters_FL:f}\t{0.suspension_travel_meters_FR:f}\t{0.suspension_travel_meters_RL:f}\t{0.suspension_travel_meters_RR:f}\t{0.car_ordinal}\t{0.car_class}\t{0.car_performance_index}\t{0.drivetrain_type}\t{0.num_cylinders}'.format(self))
return('{0.is_race_on}\t{0.timestamp_ms}\t{0.engine_max_rpm:f}\t{0.engine_idle_rpm:f}\t{0.current_engine_rpm:f}\t{0.acceleration_x:f}\t{0.acceleration_y:f}\t{0.acceleration_z:f}\t{0.velocity_x:f}\t{0.velocity_y:f}\t{0.velocity_z:f}\t{0.angular_velocity_x:f}\t{0.angular_velocity_y:f}\t{0.angular_velocity_z:f}\t{0.yaw:f}\t{0.pitch:f}\t{0.roll:f}\t{0.norm_suspension_travel_FL:f}\t{0.norm_suspension_travel_FR:f}\t{0.norm_suspension_travel_RL:f}\t{0.norm_suspension_travel_RR:f}\t{0.tire_slip_ratio_FL:f}\t{0.tire_slip_ratio_FR:f}\t{0.tire_slip_ratio_RL:f}\t{0.tire_slip_ratio_RR:f}\t{0.wheel_rotation_speed_FL:f}\t{0.wheel_rotation_speed_FR:f}\t{0.wheel_rotation_speed_RL:f}\t{0.wheel_rotation_speed_RR:f}\t{0.wheel_on_rumble_strip_FL:f}\t{0.wheel_on_rumble_strip_FR:f}\t{0.wheel_on_rumble_strip_RL:f}\t{0.wheel_on_rumble_strip_RR:f}\t{0.wheel_in_puddle_FL:f}\t{0.wheel_in_puddle_FR:f}\t{0.wheel_in_puddle_RL:f}\t{0.wheel_in_puddle_RR:f}\t{0.surface_rumble_FL:f}\t{0.surface_rumble_FR:f}\t{0.surface_rumble_RL:f}\t{0.surface_rumble_RR:f}\t{0.tire_slip_angle_FL:f}\t{0.tire_slip_angle_FR:f}\t{0.tire_slip_angle_RL:f}\t{0.tire_slip_angle_RR:f}\t{0.tire_combined_slip_FL:f}\t{0.tire_combined_slip_FR:f}\t{0.tire_combined_slip_RL:f}\t{0.tire_combined_slip_RR:f}\t{0.suspension_travel_meters_FL:f}\t{0.suspension_travel_meters_FR:f}\t{0.suspension_travel_meters_RL:f}\t{0.suspension_travel_meters_RR:f}\t{0.car_ordinal}\t{0.car_class}\t{0.car_performance_index}\t{0.drivetrain_type}\t{0.num_cylinders}\t{0.position_x}\t{0.position_y}\t{0.position_z}\t{0.speed}\t{0.power}\t{0.torque}\t{0.tire_temp_FL}\t{0.tire_temp_FR}\t{0.tire_temp_RL}\t{0.tire_temp_RR}\t{0.boost}\t{0.fuel}\t{0.dist_traveled}\t{0.best_lap}\t{0.last_lap}\t{0.cur_lap}\t{0.cur_race_time}\t{0.lap_no}\t{0.race_pos}\t{0.accel}\t{0.brake}\t{0.clutch}\t{0.handbrake}\t{0.gear}\t{0.steer}\t{0.norm_driving_line}\t{0.norm_ai_brake_diff}'.format(self)) | 'angular_velocity_x', 'angular_velocity_y', 'angular_velocity_z',
'yaw', 'pitch', 'roll',
'norm_suspension_travel_FL', 'norm_suspension_travel_FR',
'norm_suspension_travel_RL', 'norm_suspension_travel_RR', |
AdditionalTabsLoading.js | /**
* @flow
* @file Preview sidebar additional tabs loading component
* @author Box
*/
import * as React from 'react';
import AdditionalTabLoading from './AdditionalTabLoading';
import MoreTabLoading from './MoreTabLoading';
import './AdditionalTabs.scss';
import './AdditionalTabsLoading.scss';
| AdditionalTabLoading,
AdditionalTabLoading,
AdditionalTabLoading,
AdditionalTabLoading,
AdditionalTabLoading,
MoreTabLoading,
];
const AdditionalTabsLoading = (): Array<React.Element<any>> => {
return LOADING_TABS.map((LoadingComponent, idx) => <LoadingComponent key={idx} />);
};
export default AdditionalTabsLoading; | // Loading layout for the sidebar's additional tabs
const LOADING_TABS = [ |
lib.rs | #![deny(missing_docs)]
//! The official Piston window wrapper for the Piston game engine
//!
//! **Notice! If this is your first time visiting Piston, [start here](https://github.com/PistonDevelopers/piston).**
//!
//! The purpose of this library is to provide an easy-to-use,
//! simple-to-get-started and convenient-for-applications API for Piston.
//!
//! Sets up:
//!
//! - [Gfx](https://github.com/gfx-rs/gfx) with an OpenGL back-end.
//! - [gfx_graphics](https://github.com/pistondevelopers/gfx_graphics)
//! for 2D rendering.
//! - [glutin_window](https://github.com/pistondevelopers/glutin_window)
//! as default window back-end, but this can be swapped (see below).
//!
//! ### Example
//!
//! ```no_run
//! extern crate piston_window;
//!
//! use piston_window::*;
//!
//! fn main() {
//! let mut window: PistonWindow =
//! WindowSettings::new("Hello World!", [512; 2])
//! .build().unwrap();
//! while let Some(e) = window.next() {
//! window.draw_2d(&e, |c, g, _| {
//! clear([0.5, 0.5, 0.5, 1.0], g);
//! rectangle([1.0, 0.0, 0.0, 1.0], // red
//! [0.0, 0.0, 100.0, 100.0], // rectangle
//! c.transform, g);
//! });
//! }
//! }
//! ```
//!
//! The `draw_2d` function calls the closure on render events.
//! There is no need to filter events manually, and there is no overhead.
//!
//! ### Swap to another window back-end
//!
//! Change the generic parameter to the window back-end you want to use.
//!
//! ```ignore
//! extern crate piston_window;
//! extern crate sdl2_window;
//!
//! use piston_window::*;
//! use sdl2_window::Sdl2Window;
//!
//! # fn main() {
//!
//! let window: PistonWindow<Sdl2Window> =
//! WindowSettings::new("title", [512; 2])
//! .build().unwrap();
//!
//! # }
//! ```
//!
//! ### sRGB
//!
//! The impl of `BuildFromWindowSettings` in this library turns on
//! `WindowSettings::srgb`, because it is required by gfx_graphics.
//!
//! Most images such as those found on the internet uses sRGB,
//! that has a non-linear gamma corrected space.
//! When rendering 3D, make sure textures and colors are in linear gamma space.
//! Alternative is to use `Srgb8` and `Srgba8` formats for textures.
//!
//! For more information about sRGB, see
//! https://github.com/PistonDevelopers/piston/issues/1014
//!
//! ### Library dependencies
//!
//! This library is meant to be used in applications only.
//! It is not meant to be depended on by generic libraries.
//! Instead, libraries should depend on the lower abstractions,
//! such as the [Piston core](https://github.com/pistondevelopers/piston).
extern crate piston;
extern crate gfx;
extern crate gfx_device_gl;
extern crate gfx_graphics;
extern crate graphics;
extern crate shader_version;
pub extern crate texture;
pub use shader_version::OpenGL;
pub use graphics::*;
pub use piston::window::*;
pub use piston::input::*;
pub use piston::event_loop::*;
pub use gfx_graphics::{ Texture, TextureContext, TextureSettings, Filter, Flip };
use gfx_graphics::{ Gfx2d, GfxGraphics };
use std::time::Duration;
use std::error::Error;
/// Actual factory used by Gfx backend.
pub type GfxFactory = gfx_device_gl::Factory;
/// Actual gfx::Stream implementation carried by the window.
pub type GfxEncoder = gfx::Encoder<gfx_device_gl::Resources,
gfx_device_gl::CommandBuffer>;
/// Glyph cache.
pub type Glyphs = gfx_graphics::GlyphCache<'static,
gfx_device_gl::Factory,
gfx_device_gl::Resources,
gfx_device_gl::CommandBuffer>;
/// 2D graphics.
pub type G2d<'a> = GfxGraphics<'a,
gfx_device_gl::Resources,
gfx_device_gl::CommandBuffer>;
/// Texture type compatible with `G2d`.
pub type G2dTexture = Texture<gfx_device_gl::Resources>;
/// Texture context.
pub type G2dTextureContext = TextureContext<
gfx_device_gl::Factory,
gfx_device_gl::Resources,
gfx_device_gl::CommandBuffer>;
/// Contains everything required for controlling window, graphics, event loop.
#[cfg(not(feature="glutin"))]
pub struct PistonWindow<W: Window> {
/// The window.
pub window: W,
/// GFX encoder.
pub encoder: GfxEncoder,
/// GFX device.
pub device: gfx_device_gl::Device,
/// Output frame buffer.
pub output_color: gfx::handle::RenderTargetView<
gfx_device_gl::Resources, gfx::format::Srgba8>,
/// Output stencil buffer.
pub output_stencil: gfx::handle::DepthStencilView<
gfx_device_gl::Resources, gfx::format::DepthStencil>,
/// Gfx2d.
pub g2d: Gfx2d<gfx_device_gl::Resources>,
/// Event loop state.
pub events: Events,
/// The factory that was created along with the device.
pub factory: gfx_device_gl::Factory,
}
#[cfg(feature="glutin")]
extern crate glutin_window;
#[cfg(feature="glutin")]
use glutin_window::GlutinWindow;
/// Contains everything required for controlling window, graphics, event loop.
#[cfg(feature="glutin")]
pub struct PistonWindow<W: Window = GlutinWindow> {
/// The window.
pub window: W,
/// GFX encoder.
pub encoder: GfxEncoder,
/// GFX device.
pub device: gfx_device_gl::Device,
/// Output frame buffer.
pub output_color: gfx::handle::RenderTargetView<
gfx_device_gl::Resources, gfx::format::Srgba8>,
/// Output stencil buffer.
pub output_stencil: gfx::handle::DepthStencilView<
gfx_device_gl::Resources, gfx::format::DepthStencil>,
/// Gfx2d.
pub g2d: Gfx2d<gfx_device_gl::Resources>,
/// Event loop state.
pub events: Events,
/// The factory that was created along with the device.
pub factory: gfx_device_gl::Factory,
}
impl<W> BuildFromWindowSettings for PistonWindow<W>
where W: Window + OpenGLWindow + BuildFromWindowSettings
{
fn build_from_window_settings(settings: &WindowSettings) -> Result<PistonWindow<W>, Box<dyn Error>> {
// Turn on sRGB.
let settings = settings.clone().srgb(true);
// Use OpenGL 3.2 by default, because this is what window backends
// usually do.
let api = settings.get_maybe_graphics_api().unwrap_or(Api::opengl(3, 2));
let samples = settings.get_samples();
let opengl = OpenGL::from_api(api)
.expect("Could not detect OpenGL version from graphics API");
Ok(PistonWindow::new(opengl, samples, settings.build()?))
}
}
fn create_main_targets(dim: gfx::texture::Dimensions) ->
(gfx::handle::RenderTargetView<
gfx_device_gl::Resources, gfx::format::Srgba8>,
gfx::handle::DepthStencilView<
gfx_device_gl::Resources, gfx::format::DepthStencil>) {
use gfx::format::{DepthStencil, Format, Formatted, Srgba8};
use gfx::memory::Typed;
let color_format: Format = <Srgba8 as Formatted>::get_format();
let depth_format: Format = <DepthStencil as Formatted>::get_format();
let (output_color, output_stencil) =
gfx_device_gl::create_main_targets_raw(dim,
color_format.0,
depth_format.0);
let output_color = Typed::new(output_color);
let output_stencil = Typed::new(output_stencil);
(output_color, output_stencil)
}
impl<W> PistonWindow<W>
where W: Window
{
/// Creates a new piston window.
pub fn new(opengl: OpenGL, samples: u8, mut window: W) -> Self
where W: OpenGLWindow
{
let (device, mut factory) =
gfx_device_gl::create(|s|
window.get_proc_address(s) as *const _);
let (output_color, output_stencil) = {
let aa = samples as gfx::texture::NumSamples;
let draw_size = window.draw_size();
let dim = (draw_size.width as u16, draw_size.height as u16,
1, aa.into());
create_main_targets(dim)
};
let g2d = Gfx2d::new(opengl, &mut factory);
let encoder = factory.create_command_buffer().into();
let events = Events::new(EventSettings::new());
PistonWindow {
window: window,
encoder: encoder,
device: device,
output_color: output_color,
output_stencil: output_stencil,
g2d: g2d,
events: events,
factory: factory,
}
}
/// Creates context used to create and update textures.
pub fn create_texture_context(&mut self) -> G2dTextureContext {
TextureContext {
factory: self.factory.clone(),
encoder: self.factory.create_command_buffer().into()
}
}
/// Loads font from a path.
pub fn load_font<P: AsRef<std::path::Path>>(&mut self, path: P) -> Result<Glyphs, std::io::Error> {
Glyphs::new(path, TextureContext {
factory: self.factory.clone(),
encoder: self.factory.create_command_buffer().into()
}, TextureSettings::new())
}
/// Renders 2D graphics.
///
/// Calls the closure on render events.
/// There is no need to filter events manually, and there is no overhead.
pub fn draw_2d<E, F, U>(&mut self, e: &E, f: F) -> Option<U> where
W: OpenGLWindow,
E: GenericEvent,
F: FnOnce(Context, &mut G2d, &mut gfx_device_gl::Device) -> U
{
if let Some(args) = e.render_args() {
self.window.make_current();
let device = &mut self.device;
let res = self.g2d.draw(
&mut self.encoder,
&self.output_color,
&self.output_stencil,
args.viewport(),
|c, g| f(c, g, device)
);
self.encoder.flush(device);
Some(res)
} else {
None
}
}
/// Renders 3D graphics.
///
/// Calls the closure on render events.
/// There is no need to filter events manually, and there is no overhead.
pub fn draw_3d<E, F, U>(&mut self, e: &E, f: F) -> Option<U> where
W: OpenGLWindow,
E: GenericEvent,
F: FnOnce(&mut Self) -> U
{
if let Some(_) = e.render_args() | else {
None
}
}
/// Returns next event.
/// Cleans up after rendering and resizes frame buffers.
pub fn next(&mut self) -> Option<Event> {
if let Some(e) = self.events.next(&mut self.window) {
self.event(&e);
Some(e)
} else {
None
}
}
/// Let window handle new event.
/// Cleans up after rendering and resizes frame buffers.
pub fn event<E: GenericEvent>(&mut self, event: &E) {
use gfx::Device;
use gfx::memory::Typed;
if let Some(_) = event.after_render_args() {
// After swapping buffers.
self.device.cleanup();
}
// Check whether window has resized and update the output.
let dim = self.output_color.raw().get_dimensions();
let (w, h) = (dim.0, dim.1);
let draw_size = self.window.draw_size();
if w != draw_size.width as u16 || h != draw_size.height as u16 {
let dim = (draw_size.width as u16,
draw_size.height as u16,
dim.2, dim.3);
let (output_color, output_stencil) = create_main_targets(dim);
self.output_color = output_color;
self.output_stencil = output_stencil;
}
}
}
impl<W> Window for PistonWindow<W>
where W: Window
{
fn should_close(&self) -> bool { self.window.should_close() }
fn set_should_close(&mut self, value: bool) {
self.window.set_should_close(value)
}
fn size(&self) -> Size { self.window.size() }
fn draw_size(&self) -> Size { self.window.draw_size() }
fn swap_buffers(&mut self) { self.window.swap_buffers() }
fn wait_event(&mut self) -> Event {
Window::wait_event(&mut self.window)
}
fn wait_event_timeout(&mut self, timeout: Duration) -> Option<Event> {
Window::wait_event_timeout(&mut self.window, timeout)
}
fn poll_event(&mut self) -> Option<Event> {
Window::poll_event(&mut self.window)
}
}
impl<W> AdvancedWindow for PistonWindow<W>
where W: AdvancedWindow
{
fn get_title(&self) -> String { self.window.get_title() }
fn set_title(&mut self, title: String) {
self.window.set_title(title)
}
fn get_automatic_close(&self) -> bool { self.window.get_automatic_close() }
fn set_automatic_close(&mut self, value: bool) {
self.window.set_automatic_close(value);
}
fn get_exit_on_esc(&self) -> bool { self.window.get_exit_on_esc() }
fn set_exit_on_esc(&mut self, value: bool) {
self.window.set_exit_on_esc(value)
}
fn set_capture_cursor(&mut self, value: bool) {
self.window.set_capture_cursor(value)
}
fn show(&mut self) { self.window.show() }
fn hide(&mut self) { self.window.hide() }
fn get_position(&self) -> Option<Position> {
self.window.get_position()
}
fn set_position<P: Into<Position>>(&mut self, pos: P) {
self.window.set_position(pos)
}
fn set_size<S: Into<Size>>(&mut self, size: S) {
self.window.set_size(size)
}
}
impl<W> EventLoop for PistonWindow<W>
where W: Window
{
fn get_event_settings(&self) -> EventSettings {
self.events.get_event_settings()
}
fn set_event_settings(&mut self, settings: EventSettings) {
self.events.set_event_settings(settings);
}
}
| {
self.window.make_current();
let res = f(self);
self.encoder.flush(&mut self.device);
Some(res)
} |
supernode.client.controller.js | angular.module("webapp").controller("SupernodeController", ["$scope", "SupernodeService", SupernodeController]);
angular.module("webapp").controller("SupernodeCustomController", ["$scope", "$timeout", "$cookies", "SupernodeService", SupernodeCustomController]);
function SupernodeController($scope, SupernodeService){
$scope.changeSelectOption = function(){
if(!$scope.select.value)
return;
SupernodeService.payoutList({"round": $scope.select.value}, function(r_payoutList) {
if(!r_payoutList){
$scope.payoutList = [];
return;
}
for(let i in r_payoutList) {
let payout = r_payoutList[i];
payout.round = (payout.round-3) + "-" + payout.round;
payout.recipient = "<a href='#s_account?account="+payout.recipient+"' target='_blank'>"+payout.recipient+"</a>";
payout.amount = fmtXEM(payout.amount);
payout.fee = fmtXEM(payout.fee);
payout.timeStamp = fmtDate(payout.timeStamp);
if(payout.supernodeName){
payout.supernodeName = XBBCODE.process({
text: payout.supernodeName,
removeMisalignedTags: true,
addInLineBreaks: false
}).html;
}
if(i==0)
$scope.payoutAddress = "<a href='#s_account?account="+payout.sender+"' target='_blank'>"+payout.sender+"</a>";
}
$scope.allPayoutList = r_payoutList;
$scope.payoutList = r_payoutList;
});
};
SupernodeService.payoutRoundList(function(r_payoutRoundList){
if(!r_payoutRoundList)
return;
$scope.selectOptions = r_payoutRoundList;
$scope.select = $scope.selectOptions[0];
$scope.changeSelectOption();
});
}
function SupernodeCustomController($scope, $timeout, $cookies, SupernodeService){
$scope.tableList = [];
$scope.payoutMap = new Map();
$scope.roundSet = new Set();
$scope.supernodeMap = new Map();
$scope.selectedSupernodeNames = [];
$scope.selectedSupernodeNamesText = "";
$scope.showLoadingFlag = true;
$scope.showButtonFlag = false;
$scope.showWarningFlag = false;
SupernodeService.supernodeList(function(data){
if(!data || data.length==0){
$scope.items = [{label: "Supernodes data Not Found", content: ""}];
return;
}
$scope.supernodeList = data;
for(let i in data){
$scope.supernodeMap.set(""+data[i].id, data[i].name);
}
SupernodeService.payoutListLast10Rounds(function(r_payoutList){
if(!r_payoutList)
return;
// load pay out data list
for(let i in r_payoutList) {
let payout = r_payoutList[i];
if(payout.round && !$scope.roundSet.has(payout.round))
$scope.roundSet.add(payout.round);
payout.recipient = "<a href='#s_account?account="+payout.recipient+"' target='_blank'>"+payout.recipient+"</a>";
payout.amount = fmtXEM(payout.amount);
payout.fee = fmtXEM(payout.fee);
payout.timeStamp = fmtDate(payout.timeStamp);
if(payout.supernodeName){
payout.supernodeName = XBBCODE.process({
text: payout.supernodeName,
removeMisalignedTags: true,
addInLineBreaks: false
}).html;
}
$scope.payoutMap.set(payout.round+"_"+payout.supernodeID, payout);
}
$scope.showLoadingFlag = false;
$scope.showButtonFlag = true;
$scope.loadPayoutList();
});
});
$scope.loadPayoutList = function(refreshFlag){
// clean table list
$scope.tableList = [];
// load my supernodes from cookies
let mySupernodes = $cookies.get("mySupernodes")?$cookies.get("mySupernodes"):"";
mySupernodes = validateNumberCookies(mySupernodes, $scope.supernodeMap);
let mySupernodesArr = mySupernodes.split(",");
if(mySupernodesArr.length==1 && mySupernodesArr[0]==""){
$scope.showWarningFlag = true;
} else {
$scope.roundSet.forEach(function(round){
let table = {};
let payoutList = [];
let realPayoutCount = 0;
for(let i in mySupernodesArr){
if(!$scope.supernodeMap.get(mySupernodesArr[i]))
continue;
let index = round + "_" + mySupernodesArr[i];
let payout = $scope.payoutMap.get(index);
let failFlag = "x";
if(!payout){
payout = {};
payout.recipient = failFlag;
payout.amount = failFlag;
payout.fee = failFlag;
payout.recipient = failFlag;
payout.timeStamp = failFlag;
payout.supernodeName = $scope.supernodeMap.get(mySupernodesArr[i]);
} else {
realPayoutCount++;
}
payoutList.push(payout);
}
table.round = (round-3) + "-" + round + " (" + realPayoutCount + "/" + payoutList.length + ")";
table.payoutList = payoutList;
$scope.tableList.push(table);
});
$scope.showWarningFlag = false; | if(refreshFlag)
$scope.$apply();
}
$scope.showManageMySupernodes = function(){
$("#manageMySupernodes").modal("show");
if(!$scope.initTableFlag){
$scope.initTableFlag = true;
$scope.datatable = $('#supernodeTable').DataTable({
"select": {style: true},
"paging": false,
"ordering": false,
"searching": true,
"columnDefs": [
{"searchable": false, "targets": 0}
]
});
// load selected supernodes from cookie
let mySupernodes = validateNumberCookies($cookies.get('mySupernodes'));
if(mySupernodes){
mySupernodes = "," + mySupernodes + ",";
for(let i in $scope.supernodeList){
if(mySupernodes.indexOf("," + $scope.supernodeList[i].id + ",")!=-1){
let item = {};
item.id = $scope.supernodeList[i].id;
item.name = $scope.supernodeList[i].name;
$scope.addMySupernodes(item);
$scope.datatable.rows(i).select();
}
}
}
$scope.datatable.on('select', function(e, dt, type, indexes){
if(!indexes || indexes.length==0)
return;
// add supernode
$scope.addMySupernodes($scope.supernodeList[indexes[0]], true);
// add value into cookies
$scope.addMySupernodesCookies($scope.supernodeList[indexes[0]]);
});
$scope.datatable.on('deselect', function(e, dt, type, indexes){
if(!indexes || indexes.length==0)
return;
// remove supernode from UI
$scope.removeMySupernodes($scope.supernodeList[indexes[0]], true);
// remove value from cookies
$scope.removeMySupernodesCookies($scope.supernodeList[indexes[0]]);
});
}
};
$scope.addMySupernodes = function(item, refreshFlag){
$scope.selectedSupernodeNames.push(item.name);
let text = "";
for(let i in $scope.selectedSupernodeNames)
text += $scope.selectedSupernodeNames[i] + ", ";
if(text)
text = text.substring(0, text.length-2);
$scope.selectedSupernodeNamesText = text;
if(refreshFlag)
$scope.$apply();
};
$scope.removeMySupernodes = function(item, refreshFlag){
// remove name
let selectedSupernodeNames_new = [];
for(let i in $scope.selectedSupernodeNames){
if(item.name!=$scope.selectedSupernodeNames[i])
selectedSupernodeNames_new.push($scope.selectedSupernodeNames[i]);
}
$scope.selectedSupernodeNames = selectedSupernodeNames_new;
let text = "";
for(let i in $scope.selectedSupernodeNames)
text += $scope.selectedSupernodeNames[i] + ", ";
if(text)
text = text.substring(0, text.length-2);
$scope.selectedSupernodeNamesText = text;
if(refreshFlag)
$scope.$apply();
};
$scope.addMySupernodesCookies = function(item){
let mySupernodes = validateNumberCookies($cookies.get("mySupernodes"));
let expireDate = new Date();
expireDate.setFullYear(expireDate.getFullYear() + 1);
if(!mySupernodes)
mySupernodes = item.id;
else
mySupernodes += "," + item.id;
mySupernodes = sortMySupernodes(mySupernodes);
$cookies.put("mySupernodes", mySupernodes, {expires: expireDate});
$scope.loadPayoutList(true);
};
$scope.removeMySupernodesCookies = function(item){
let mySupernodes = validateNumberCookies($cookies.get("mySupernodes"));
let expireDate = new Date();
expireDate.setFullYear(expireDate.getFullYear() + 1);
if(!mySupernodes)
return;
let mySupernodesArr = mySupernodes.split(",");
mySupernodes = "";
for(let i in mySupernodesArr){
if(mySupernodesArr[i]!=item.id)
mySupernodes += mySupernodesArr[i] + ",";
}
if(mySupernodes.length>0)
mySupernodes = mySupernodes.substring(0, mySupernodes.length-1);
mySupernodes = sortMySupernodes(mySupernodes);
$cookies.put("mySupernodes", mySupernodes, {expires: expireDate});
$scope.loadPayoutList(true);
};
}
function sortMySupernodes(mySupernodes){
if(!mySupernodes)
return;
mySupernodes = "" + mySupernodes;
let mySupernodesArr = mySupernodes.split(",");
mySupernodesArr.sort(sortNumber);
let r_mySupernodes = "";
for(let i in mySupernodesArr)
r_mySupernodes += mySupernodesArr[i] + ",";
if(r_mySupernodes!="")
r_mySupernodes = r_mySupernodes.substring(0, r_mySupernodes.length-1);
return r_mySupernodes;
}
function validateNumberCookies(value, supernodesMap){
if(!value){
return "";
}
let arr = value.split(",");
let r_value = "";
for(let i in arr){
if(isNaN(Number(arr[i])))
continue;
if(supernodesMap && !supernodesMap.get(""+arr[i]))
continue;
r_value += arr[i] + ",";
}
if(r_value.length>0)
r_value = r_value.substring(0, r_value.length-1);
return r_value;
}
function sortNumber(a, b) {
return a - b;
} | } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.